1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements extra semantic analysis beyond what is enforced
11 // by the C type system.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
41 using namespace clang;
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
46 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking. Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
104 ExprResult Arg(TheCall->getArg(0));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
109 TheCall->setArg(0, Arg.get());
110 TheCall->setType(ResultType);
114 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
124 llvm::APSInt Size, DstSize;
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
131 if (Size.ule(DstSize))
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
142 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
187 QualType ReturnTy = CE->getCallReturnType();
188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
206 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
208 ExprResult TheCallResult(TheCall);
210 // Find out if any arguments are required to be integer constant expressions.
211 unsigned ICEArguments = 0;
212 ASTContext::GetBuiltinTypeError Error;
213 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
214 if (Error != ASTContext::GE_None)
215 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
217 // If any arguments are required to be ICE's, check and diagnose.
218 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
219 // Skip arguments not required to be ICE's.
220 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
223 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
225 ICEArguments &= ~(1 << ArgNo);
229 case Builtin::BI__builtin___CFStringMakeConstantString:
230 assert(TheCall->getNumArgs() == 1 &&
231 "Wrong # arguments to builtin CFStringMakeConstantString");
232 if (CheckObjCString(TheCall->getArg(0)))
235 case Builtin::BI__builtin_stdarg_start:
236 case Builtin::BI__builtin_va_start:
237 if (SemaBuiltinVAStart(TheCall))
240 case Builtin::BI__va_start: {
241 switch (Context.getTargetInfo().getTriple().getArch()) {
242 case llvm::Triple::arm:
243 case llvm::Triple::thumb:
244 if (SemaBuiltinVAStartARM(TheCall))
248 if (SemaBuiltinVAStart(TheCall))
254 case Builtin::BI__builtin_isgreater:
255 case Builtin::BI__builtin_isgreaterequal:
256 case Builtin::BI__builtin_isless:
257 case Builtin::BI__builtin_islessequal:
258 case Builtin::BI__builtin_islessgreater:
259 case Builtin::BI__builtin_isunordered:
260 if (SemaBuiltinUnorderedCompare(TheCall))
263 case Builtin::BI__builtin_fpclassify:
264 if (SemaBuiltinFPClassification(TheCall, 6))
267 case Builtin::BI__builtin_isfinite:
268 case Builtin::BI__builtin_isinf:
269 case Builtin::BI__builtin_isinf_sign:
270 case Builtin::BI__builtin_isnan:
271 case Builtin::BI__builtin_isnormal:
272 if (SemaBuiltinFPClassification(TheCall, 1))
275 case Builtin::BI__builtin_shufflevector:
276 return SemaBuiltinShuffleVector(TheCall);
277 // TheCall will be freed by the smart pointer here, but that's fine, since
278 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
279 case Builtin::BI__builtin_prefetch:
280 if (SemaBuiltinPrefetch(TheCall))
283 case Builtin::BI__assume:
284 case Builtin::BI__builtin_assume:
285 if (SemaBuiltinAssume(TheCall))
288 case Builtin::BI__builtin_assume_aligned:
289 if (SemaBuiltinAssumeAligned(TheCall))
292 case Builtin::BI__builtin_object_size:
293 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
296 case Builtin::BI__builtin_longjmp:
297 if (SemaBuiltinLongjmp(TheCall))
301 case Builtin::BI__builtin_classify_type:
302 if (checkArgCount(*this, TheCall, 1)) return true;
303 TheCall->setType(Context.IntTy);
305 case Builtin::BI__builtin_constant_p:
306 if (checkArgCount(*this, TheCall, 1)) return true;
307 TheCall->setType(Context.IntTy);
309 case Builtin::BI__sync_fetch_and_add:
310 case Builtin::BI__sync_fetch_and_add_1:
311 case Builtin::BI__sync_fetch_and_add_2:
312 case Builtin::BI__sync_fetch_and_add_4:
313 case Builtin::BI__sync_fetch_and_add_8:
314 case Builtin::BI__sync_fetch_and_add_16:
315 case Builtin::BI__sync_fetch_and_sub:
316 case Builtin::BI__sync_fetch_and_sub_1:
317 case Builtin::BI__sync_fetch_and_sub_2:
318 case Builtin::BI__sync_fetch_and_sub_4:
319 case Builtin::BI__sync_fetch_and_sub_8:
320 case Builtin::BI__sync_fetch_and_sub_16:
321 case Builtin::BI__sync_fetch_and_or:
322 case Builtin::BI__sync_fetch_and_or_1:
323 case Builtin::BI__sync_fetch_and_or_2:
324 case Builtin::BI__sync_fetch_and_or_4:
325 case Builtin::BI__sync_fetch_and_or_8:
326 case Builtin::BI__sync_fetch_and_or_16:
327 case Builtin::BI__sync_fetch_and_and:
328 case Builtin::BI__sync_fetch_and_and_1:
329 case Builtin::BI__sync_fetch_and_and_2:
330 case Builtin::BI__sync_fetch_and_and_4:
331 case Builtin::BI__sync_fetch_and_and_8:
332 case Builtin::BI__sync_fetch_and_and_16:
333 case Builtin::BI__sync_fetch_and_xor:
334 case Builtin::BI__sync_fetch_and_xor_1:
335 case Builtin::BI__sync_fetch_and_xor_2:
336 case Builtin::BI__sync_fetch_and_xor_4:
337 case Builtin::BI__sync_fetch_and_xor_8:
338 case Builtin::BI__sync_fetch_and_xor_16:
339 case Builtin::BI__sync_fetch_and_nand:
340 case Builtin::BI__sync_fetch_and_nand_1:
341 case Builtin::BI__sync_fetch_and_nand_2:
342 case Builtin::BI__sync_fetch_and_nand_4:
343 case Builtin::BI__sync_fetch_and_nand_8:
344 case Builtin::BI__sync_fetch_and_nand_16:
345 case Builtin::BI__sync_add_and_fetch:
346 case Builtin::BI__sync_add_and_fetch_1:
347 case Builtin::BI__sync_add_and_fetch_2:
348 case Builtin::BI__sync_add_and_fetch_4:
349 case Builtin::BI__sync_add_and_fetch_8:
350 case Builtin::BI__sync_add_and_fetch_16:
351 case Builtin::BI__sync_sub_and_fetch:
352 case Builtin::BI__sync_sub_and_fetch_1:
353 case Builtin::BI__sync_sub_and_fetch_2:
354 case Builtin::BI__sync_sub_and_fetch_4:
355 case Builtin::BI__sync_sub_and_fetch_8:
356 case Builtin::BI__sync_sub_and_fetch_16:
357 case Builtin::BI__sync_and_and_fetch:
358 case Builtin::BI__sync_and_and_fetch_1:
359 case Builtin::BI__sync_and_and_fetch_2:
360 case Builtin::BI__sync_and_and_fetch_4:
361 case Builtin::BI__sync_and_and_fetch_8:
362 case Builtin::BI__sync_and_and_fetch_16:
363 case Builtin::BI__sync_or_and_fetch:
364 case Builtin::BI__sync_or_and_fetch_1:
365 case Builtin::BI__sync_or_and_fetch_2:
366 case Builtin::BI__sync_or_and_fetch_4:
367 case Builtin::BI__sync_or_and_fetch_8:
368 case Builtin::BI__sync_or_and_fetch_16:
369 case Builtin::BI__sync_xor_and_fetch:
370 case Builtin::BI__sync_xor_and_fetch_1:
371 case Builtin::BI__sync_xor_and_fetch_2:
372 case Builtin::BI__sync_xor_and_fetch_4:
373 case Builtin::BI__sync_xor_and_fetch_8:
374 case Builtin::BI__sync_xor_and_fetch_16:
375 case Builtin::BI__sync_nand_and_fetch:
376 case Builtin::BI__sync_nand_and_fetch_1:
377 case Builtin::BI__sync_nand_and_fetch_2:
378 case Builtin::BI__sync_nand_and_fetch_4:
379 case Builtin::BI__sync_nand_and_fetch_8:
380 case Builtin::BI__sync_nand_and_fetch_16:
381 case Builtin::BI__sync_val_compare_and_swap:
382 case Builtin::BI__sync_val_compare_and_swap_1:
383 case Builtin::BI__sync_val_compare_and_swap_2:
384 case Builtin::BI__sync_val_compare_and_swap_4:
385 case Builtin::BI__sync_val_compare_and_swap_8:
386 case Builtin::BI__sync_val_compare_and_swap_16:
387 case Builtin::BI__sync_bool_compare_and_swap:
388 case Builtin::BI__sync_bool_compare_and_swap_1:
389 case Builtin::BI__sync_bool_compare_and_swap_2:
390 case Builtin::BI__sync_bool_compare_and_swap_4:
391 case Builtin::BI__sync_bool_compare_and_swap_8:
392 case Builtin::BI__sync_bool_compare_and_swap_16:
393 case Builtin::BI__sync_lock_test_and_set:
394 case Builtin::BI__sync_lock_test_and_set_1:
395 case Builtin::BI__sync_lock_test_and_set_2:
396 case Builtin::BI__sync_lock_test_and_set_4:
397 case Builtin::BI__sync_lock_test_and_set_8:
398 case Builtin::BI__sync_lock_test_and_set_16:
399 case Builtin::BI__sync_lock_release:
400 case Builtin::BI__sync_lock_release_1:
401 case Builtin::BI__sync_lock_release_2:
402 case Builtin::BI__sync_lock_release_4:
403 case Builtin::BI__sync_lock_release_8:
404 case Builtin::BI__sync_lock_release_16:
405 case Builtin::BI__sync_swap:
406 case Builtin::BI__sync_swap_1:
407 case Builtin::BI__sync_swap_2:
408 case Builtin::BI__sync_swap_4:
409 case Builtin::BI__sync_swap_8:
410 case Builtin::BI__sync_swap_16:
411 return SemaBuiltinAtomicOverloaded(TheCallResult);
412 #define BUILTIN(ID, TYPE, ATTRS)
413 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
414 case Builtin::BI##ID: \
415 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
416 #include "clang/Basic/Builtins.def"
417 case Builtin::BI__builtin_annotation:
418 if (SemaBuiltinAnnotation(*this, TheCall))
421 case Builtin::BI__builtin_addressof:
422 if (SemaBuiltinAddressof(*this, TheCall))
425 case Builtin::BI__builtin_operator_new:
426 case Builtin::BI__builtin_operator_delete:
427 if (!getLangOpts().CPlusPlus) {
428 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
429 << (BuiltinID == Builtin::BI__builtin_operator_new
430 ? "__builtin_operator_new"
431 : "__builtin_operator_delete")
435 // CodeGen assumes it can find the global new and delete to call,
436 // so ensure that they are declared.
437 DeclareGlobalNewDelete();
440 // check secure string manipulation functions where overflows
441 // are detectable at compile time
442 case Builtin::BI__builtin___memcpy_chk:
443 case Builtin::BI__builtin___memmove_chk:
444 case Builtin::BI__builtin___memset_chk:
445 case Builtin::BI__builtin___strlcat_chk:
446 case Builtin::BI__builtin___strlcpy_chk:
447 case Builtin::BI__builtin___strncat_chk:
448 case Builtin::BI__builtin___strncpy_chk:
449 case Builtin::BI__builtin___stpncpy_chk:
450 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
452 case Builtin::BI__builtin___memccpy_chk:
453 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
455 case Builtin::BI__builtin___snprintf_chk:
456 case Builtin::BI__builtin___vsnprintf_chk:
457 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
460 case Builtin::BI__builtin_call_with_static_chain:
461 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
466 // Since the target specific builtins for each arch overlap, only check those
467 // of the arch we are compiling for.
468 if (BuiltinID >= Builtin::FirstTSBuiltin) {
469 switch (Context.getTargetInfo().getTriple().getArch()) {
470 case llvm::Triple::arm:
471 case llvm::Triple::armeb:
472 case llvm::Triple::thumb:
473 case llvm::Triple::thumbeb:
474 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
477 case llvm::Triple::aarch64:
478 case llvm::Triple::aarch64_be:
479 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
482 case llvm::Triple::mips:
483 case llvm::Triple::mipsel:
484 case llvm::Triple::mips64:
485 case llvm::Triple::mips64el:
486 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
489 case llvm::Triple::x86:
490 case llvm::Triple::x86_64:
491 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
499 return TheCallResult;
502 // Get the valid immediate range for the specified NEON type code.
503 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
504 NeonTypeFlags Type(t);
505 int IsQuad = ForceQuad ? true : Type.isQuad();
506 switch (Type.getEltType()) {
507 case NeonTypeFlags::Int8:
508 case NeonTypeFlags::Poly8:
509 return shift ? 7 : (8 << IsQuad) - 1;
510 case NeonTypeFlags::Int16:
511 case NeonTypeFlags::Poly16:
512 return shift ? 15 : (4 << IsQuad) - 1;
513 case NeonTypeFlags::Int32:
514 return shift ? 31 : (2 << IsQuad) - 1;
515 case NeonTypeFlags::Int64:
516 case NeonTypeFlags::Poly64:
517 return shift ? 63 : (1 << IsQuad) - 1;
518 case NeonTypeFlags::Poly128:
519 return shift ? 127 : (1 << IsQuad) - 1;
520 case NeonTypeFlags::Float16:
521 assert(!shift && "cannot shift float types!");
522 return (4 << IsQuad) - 1;
523 case NeonTypeFlags::Float32:
524 assert(!shift && "cannot shift float types!");
525 return (2 << IsQuad) - 1;
526 case NeonTypeFlags::Float64:
527 assert(!shift && "cannot shift float types!");
528 return (1 << IsQuad) - 1;
530 llvm_unreachable("Invalid NeonTypeFlag!");
533 /// getNeonEltType - Return the QualType corresponding to the elements of
534 /// the vector type specified by the NeonTypeFlags. This is used to check
535 /// the pointer arguments for Neon load/store intrinsics.
536 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
537 bool IsPolyUnsigned, bool IsInt64Long) {
538 switch (Flags.getEltType()) {
539 case NeonTypeFlags::Int8:
540 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
541 case NeonTypeFlags::Int16:
542 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
543 case NeonTypeFlags::Int32:
544 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
545 case NeonTypeFlags::Int64:
547 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
549 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
550 : Context.LongLongTy;
551 case NeonTypeFlags::Poly8:
552 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
553 case NeonTypeFlags::Poly16:
554 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
555 case NeonTypeFlags::Poly64:
556 return Context.UnsignedLongTy;
557 case NeonTypeFlags::Poly128:
559 case NeonTypeFlags::Float16:
560 return Context.HalfTy;
561 case NeonTypeFlags::Float32:
562 return Context.FloatTy;
563 case NeonTypeFlags::Float64:
564 return Context.DoubleTy;
566 llvm_unreachable("Invalid NeonTypeFlag!");
569 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
574 bool HasConstPtr = false;
576 #define GET_NEON_OVERLOAD_CHECK
577 #include "clang/Basic/arm_neon.inc"
578 #undef GET_NEON_OVERLOAD_CHECK
581 // For NEON intrinsics which are overloaded on vector element type, validate
582 // the immediate which specifies which variant to emit.
583 unsigned ImmArg = TheCall->getNumArgs()-1;
585 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
588 TV = Result.getLimitedValue(64);
589 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
590 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
591 << TheCall->getArg(ImmArg)->getSourceRange();
594 if (PtrArgNum >= 0) {
595 // Check that pointer arguments have the specified type.
596 Expr *Arg = TheCall->getArg(PtrArgNum);
597 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
598 Arg = ICE->getSubExpr();
599 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
600 QualType RHSTy = RHS.get()->getType();
602 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
603 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
605 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
607 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
609 EltTy = EltTy.withConst();
610 QualType LHSTy = Context.getPointerType(EltTy);
611 AssignConvertType ConvTy;
612 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
615 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
616 RHS.get(), AA_Assigning))
620 // For NEON intrinsics which take an immediate value as part of the
621 // instruction, range check them here.
622 unsigned i = 0, l = 0, u = 0;
626 #define GET_NEON_IMMEDIATE_CHECK
627 #include "clang/Basic/arm_neon.inc"
628 #undef GET_NEON_IMMEDIATE_CHECK
631 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
634 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
636 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
637 BuiltinID == ARM::BI__builtin_arm_ldaex ||
638 BuiltinID == ARM::BI__builtin_arm_strex ||
639 BuiltinID == ARM::BI__builtin_arm_stlex ||
640 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
641 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
642 BuiltinID == AArch64::BI__builtin_arm_strex ||
643 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
644 "unexpected ARM builtin");
645 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
646 BuiltinID == ARM::BI__builtin_arm_ldaex ||
647 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
648 BuiltinID == AArch64::BI__builtin_arm_ldaex;
650 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
652 // Ensure that we have the proper number of arguments.
653 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
656 // Inspect the pointer argument of the atomic builtin. This should always be
657 // a pointer type, whose element is an integral scalar or pointer type.
658 // Because it is a pointer type, we don't have to worry about any implicit
660 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
661 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
662 if (PointerArgRes.isInvalid())
664 PointerArg = PointerArgRes.get();
666 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
668 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
669 << PointerArg->getType() << PointerArg->getSourceRange();
673 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
674 // task is to insert the appropriate casts into the AST. First work out just
675 // what the appropriate type is.
676 QualType ValType = pointerType->getPointeeType();
677 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
681 // Issue a warning if the cast is dodgy.
682 CastKind CastNeeded = CK_NoOp;
683 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
684 CastNeeded = CK_BitCast;
685 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
686 << PointerArg->getType()
687 << Context.getPointerType(AddrType)
688 << AA_Passing << PointerArg->getSourceRange();
691 // Finally, do the cast and replace the argument with the corrected version.
692 AddrType = Context.getPointerType(AddrType);
693 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
694 if (PointerArgRes.isInvalid())
696 PointerArg = PointerArgRes.get();
698 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
700 // In general, we allow ints, floats and pointers to be loaded and stored.
701 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
702 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
703 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
704 << PointerArg->getType() << PointerArg->getSourceRange();
708 // But ARM doesn't have instructions to deal with 128-bit versions.
709 if (Context.getTypeSize(ValType) > MaxWidth) {
710 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
711 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
712 << PointerArg->getType() << PointerArg->getSourceRange();
716 switch (ValType.getObjCLifetime()) {
717 case Qualifiers::OCL_None:
718 case Qualifiers::OCL_ExplicitNone:
722 case Qualifiers::OCL_Weak:
723 case Qualifiers::OCL_Strong:
724 case Qualifiers::OCL_Autoreleasing:
725 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
726 << ValType << PointerArg->getSourceRange();
732 TheCall->setType(ValType);
736 // Initialize the argument to be stored.
737 ExprResult ValArg = TheCall->getArg(0);
738 InitializedEntity Entity = InitializedEntity::InitializeParameter(
739 Context, ValType, /*consume*/ false);
740 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
741 if (ValArg.isInvalid())
743 TheCall->setArg(0, ValArg.get());
745 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
746 // but the custom checker bypasses all default analysis.
747 TheCall->setType(Context.IntTy);
751 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
754 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
755 BuiltinID == ARM::BI__builtin_arm_ldaex ||
756 BuiltinID == ARM::BI__builtin_arm_strex ||
757 BuiltinID == ARM::BI__builtin_arm_stlex) {
758 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
761 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
762 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
763 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
766 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
769 // For intrinsics which take an immediate value as part of the instruction,
770 // range check them here.
771 unsigned i = 0, l = 0, u = 0;
773 default: return false;
774 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
775 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
776 case ARM::BI__builtin_arm_vcvtr_f:
777 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
778 case ARM::BI__builtin_arm_dmb:
779 case ARM::BI__builtin_arm_dsb:
780 case ARM::BI__builtin_arm_isb:
781 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
784 // FIXME: VFP Intrinsics should error if VFP not present.
785 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
788 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
792 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
793 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
794 BuiltinID == AArch64::BI__builtin_arm_strex ||
795 BuiltinID == AArch64::BI__builtin_arm_stlex) {
796 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
799 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
802 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
803 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
806 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
809 // For intrinsics which take an immediate value as part of the instruction,
810 // range check them here.
811 unsigned i = 0, l = 0, u = 0;
813 default: return false;
814 case AArch64::BI__builtin_arm_dmb:
815 case AArch64::BI__builtin_arm_dsb:
816 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
819 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
822 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
823 unsigned i = 0, l = 0, u = 0;
825 default: return false;
826 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
827 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
828 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
829 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
830 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
831 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
832 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
835 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
838 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
839 unsigned i = 0, l = 0, u = 0;
841 default: return false;
842 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
843 case X86::BI__builtin_ia32_cmpps:
844 case X86::BI__builtin_ia32_cmpss:
845 case X86::BI__builtin_ia32_cmppd:
846 case X86::BI__builtin_ia32_cmpsd: i = 2; l = 0; u = 31; break;
848 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
851 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
852 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
853 /// Returns true when the format fits the function and the FormatStringInfo has
855 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
856 FormatStringInfo *FSI) {
857 FSI->HasVAListArg = Format->getFirstArg() == 0;
858 FSI->FormatIdx = Format->getFormatIdx() - 1;
859 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
861 // The way the format attribute works in GCC, the implicit this argument
862 // of member functions is counted. However, it doesn't appear in our own
863 // lists, so decrement format_idx in that case.
865 if(FSI->FormatIdx == 0)
868 if (FSI->FirstDataArg != 0)
874 /// Checks if a the given expression evaluates to null.
876 /// \brief Returns true if the value evaluates to null.
877 static bool CheckNonNullExpr(Sema &S,
879 // As a special case, transparent unions initialized with zero are
880 // considered null for the purposes of the nonnull attribute.
881 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
882 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
883 if (const CompoundLiteralExpr *CLE =
884 dyn_cast<CompoundLiteralExpr>(Expr))
885 if (const InitListExpr *ILE =
886 dyn_cast<InitListExpr>(CLE->getInitializer()))
887 Expr = ILE->getInit(0);
891 return (!Expr->isValueDependent() &&
892 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
896 static void CheckNonNullArgument(Sema &S,
898 SourceLocation CallSiteLoc) {
899 if (CheckNonNullExpr(S, ArgExpr))
900 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
903 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
904 FormatStringInfo FSI;
905 if ((GetFormatStringType(Format) == FST_NSString) &&
906 getFormatStringInfo(Format, false, &FSI)) {
912 /// \brief Diagnose use of %s directive in an NSString which is being passed
913 /// as formatting string to formatting method.
915 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
916 const NamedDecl *FDecl,
921 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
922 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
927 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
928 if (S.GetFormatNSStringIdx(I, Idx)) {
933 if (!Format || NumArgs <= Idx)
935 const Expr *FormatExpr = Args[Idx];
936 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
937 FormatExpr = CSCE->getSubExpr();
938 const StringLiteral *FormatString;
939 if (const ObjCStringLiteral *OSL =
940 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
941 FormatString = OSL->getString();
943 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
946 if (S.FormatStringHasSArg(FormatString)) {
947 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
949 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
950 << FDecl->getDeclName();
954 static void CheckNonNullArguments(Sema &S,
955 const NamedDecl *FDecl,
956 ArrayRef<const Expr *> Args,
957 SourceLocation CallSiteLoc) {
958 // Check the attributes attached to the method/function itself.
959 llvm::SmallBitVector NonNullArgs;
960 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
961 if (!NonNull->args_size()) {
962 // Easy case: all pointer arguments are nonnull.
963 for (const auto *Arg : Args)
964 if (S.isValidPointerAttrType(Arg->getType()))
965 CheckNonNullArgument(S, Arg, CallSiteLoc);
969 for (unsigned Val : NonNull->args()) {
970 if (Val >= Args.size())
972 if (NonNullArgs.empty())
973 NonNullArgs.resize(Args.size());
974 NonNullArgs.set(Val);
978 // Check the attributes on the parameters.
979 ArrayRef<ParmVarDecl*> parms;
980 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
981 parms = FD->parameters();
982 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
983 parms = MD->parameters();
985 unsigned ArgIndex = 0;
986 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
987 I != E; ++I, ++ArgIndex) {
988 const ParmVarDecl *PVD = *I;
989 if (PVD->hasAttr<NonNullAttr>() ||
990 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
991 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
994 // In case this is a variadic call, check any remaining arguments.
995 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
996 if (NonNullArgs[ArgIndex])
997 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1000 /// Handles the checks for format strings, non-POD arguments to vararg
1001 /// functions, and NULL arguments passed to non-NULL parameters.
1002 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1003 unsigned NumParams, bool IsMemberFunction,
1004 SourceLocation Loc, SourceRange Range,
1005 VariadicCallType CallType) {
1006 // FIXME: We should check as much as we can in the template definition.
1007 if (CurContext->isDependentContext())
1010 // Printf and scanf checking.
1011 llvm::SmallBitVector CheckedVarArgs;
1013 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1014 // Only create vector if there are format attributes.
1015 CheckedVarArgs.resize(Args.size());
1017 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1022 // Refuse POD arguments that weren't caught by the format string
1024 if (CallType != VariadicDoesNotApply) {
1025 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1026 // Args[ArgIdx] can be null in malformed code.
1027 if (const Expr *Arg = Args[ArgIdx]) {
1028 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1029 checkVariadicArgument(Arg, CallType);
1035 CheckNonNullArguments(*this, FDecl, Args, Loc);
1037 // Type safety checking.
1038 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1039 CheckArgumentWithTypeTag(I, Args.data());
1043 /// CheckConstructorCall - Check a constructor call for correctness and safety
1044 /// properties not enforced by the C type system.
1045 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1046 ArrayRef<const Expr *> Args,
1047 const FunctionProtoType *Proto,
1048 SourceLocation Loc) {
1049 VariadicCallType CallType =
1050 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1051 checkCall(FDecl, Args, Proto->getNumParams(),
1052 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1055 /// CheckFunctionCall - Check a direct function call for various correctness
1056 /// and safety properties not strictly enforced by the C type system.
1057 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1058 const FunctionProtoType *Proto) {
1059 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1060 isa<CXXMethodDecl>(FDecl);
1061 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1062 IsMemberOperatorCall;
1063 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1064 TheCall->getCallee());
1065 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1066 Expr** Args = TheCall->getArgs();
1067 unsigned NumArgs = TheCall->getNumArgs();
1068 if (IsMemberOperatorCall) {
1069 // If this is a call to a member operator, hide the first argument
1071 // FIXME: Our choice of AST representation here is less than ideal.
1075 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
1076 IsMemberFunction, TheCall->getRParenLoc(),
1077 TheCall->getCallee()->getSourceRange(), CallType);
1079 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1080 // None of the checks below are needed for functions that don't have
1081 // simple names (e.g., C++ conversion functions).
1085 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1086 if (getLangOpts().ObjC1)
1087 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1089 unsigned CMId = FDecl->getMemoryFunctionKind();
1093 // Handle memory setting and copying functions.
1094 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1095 CheckStrlcpycatArguments(TheCall, FnInfo);
1096 else if (CMId == Builtin::BIstrncat)
1097 CheckStrncatArguments(TheCall, FnInfo);
1099 CheckMemaccessArguments(TheCall, CMId, FnInfo);
1104 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1105 ArrayRef<const Expr *> Args) {
1106 VariadicCallType CallType =
1107 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1109 checkCall(Method, Args, Method->param_size(),
1110 /*IsMemberFunction=*/false,
1111 lbrac, Method->getSourceRange(), CallType);
1116 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1117 const FunctionProtoType *Proto) {
1118 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1122 QualType Ty = V->getType();
1123 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
1126 VariadicCallType CallType;
1127 if (!Proto || !Proto->isVariadic()) {
1128 CallType = VariadicDoesNotApply;
1129 } else if (Ty->isBlockPointerType()) {
1130 CallType = VariadicBlock;
1131 } else { // Ty->isFunctionPointerType()
1132 CallType = VariadicFunction;
1134 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1136 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1137 TheCall->getNumArgs()),
1138 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1139 TheCall->getCallee()->getSourceRange(), CallType);
1144 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1145 /// such as function pointers returned from functions.
1146 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1147 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1148 TheCall->getCallee());
1149 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1151 checkCall(/*FDecl=*/nullptr,
1152 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1153 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1154 TheCall->getCallee()->getSourceRange(), CallType);
1159 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1160 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1161 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1165 case AtomicExpr::AO__c11_atomic_init:
1166 llvm_unreachable("There is no ordering argument for an init");
1168 case AtomicExpr::AO__c11_atomic_load:
1169 case AtomicExpr::AO__atomic_load_n:
1170 case AtomicExpr::AO__atomic_load:
1171 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1172 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1174 case AtomicExpr::AO__c11_atomic_store:
1175 case AtomicExpr::AO__atomic_store:
1176 case AtomicExpr::AO__atomic_store_n:
1177 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1178 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1179 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1186 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1187 AtomicExpr::AtomicOp Op) {
1188 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1189 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1191 // All these operations take one of the following forms:
1193 // C __c11_atomic_init(A *, C)
1195 // C __c11_atomic_load(A *, int)
1197 // void __atomic_load(A *, CP, int)
1199 // C __c11_atomic_add(A *, M, int)
1201 // C __atomic_exchange_n(A *, CP, int)
1203 // void __atomic_exchange(A *, C *, CP, int)
1205 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1207 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1210 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1211 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1213 // C is an appropriate type,
1214 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1215 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1216 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1217 // the int parameters are for orderings.
1219 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1220 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1221 && "need to update code for modified C11 atomics");
1222 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1223 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1224 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1225 Op == AtomicExpr::AO__atomic_store_n ||
1226 Op == AtomicExpr::AO__atomic_exchange_n ||
1227 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1228 bool IsAddSub = false;
1231 case AtomicExpr::AO__c11_atomic_init:
1235 case AtomicExpr::AO__c11_atomic_load:
1236 case AtomicExpr::AO__atomic_load_n:
1240 case AtomicExpr::AO__c11_atomic_store:
1241 case AtomicExpr::AO__atomic_load:
1242 case AtomicExpr::AO__atomic_store:
1243 case AtomicExpr::AO__atomic_store_n:
1247 case AtomicExpr::AO__c11_atomic_fetch_add:
1248 case AtomicExpr::AO__c11_atomic_fetch_sub:
1249 case AtomicExpr::AO__atomic_fetch_add:
1250 case AtomicExpr::AO__atomic_fetch_sub:
1251 case AtomicExpr::AO__atomic_add_fetch:
1252 case AtomicExpr::AO__atomic_sub_fetch:
1255 case AtomicExpr::AO__c11_atomic_fetch_and:
1256 case AtomicExpr::AO__c11_atomic_fetch_or:
1257 case AtomicExpr::AO__c11_atomic_fetch_xor:
1258 case AtomicExpr::AO__atomic_fetch_and:
1259 case AtomicExpr::AO__atomic_fetch_or:
1260 case AtomicExpr::AO__atomic_fetch_xor:
1261 case AtomicExpr::AO__atomic_fetch_nand:
1262 case AtomicExpr::AO__atomic_and_fetch:
1263 case AtomicExpr::AO__atomic_or_fetch:
1264 case AtomicExpr::AO__atomic_xor_fetch:
1265 case AtomicExpr::AO__atomic_nand_fetch:
1269 case AtomicExpr::AO__c11_atomic_exchange:
1270 case AtomicExpr::AO__atomic_exchange_n:
1274 case AtomicExpr::AO__atomic_exchange:
1278 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1279 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1283 case AtomicExpr::AO__atomic_compare_exchange:
1284 case AtomicExpr::AO__atomic_compare_exchange_n:
1289 // Check we have the right number of arguments.
1290 if (TheCall->getNumArgs() < NumArgs[Form]) {
1291 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1292 << 0 << NumArgs[Form] << TheCall->getNumArgs()
1293 << TheCall->getCallee()->getSourceRange();
1295 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1296 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1297 diag::err_typecheck_call_too_many_args)
1298 << 0 << NumArgs[Form] << TheCall->getNumArgs()
1299 << TheCall->getCallee()->getSourceRange();
1303 // Inspect the first argument of the atomic operation.
1304 Expr *Ptr = TheCall->getArg(0);
1305 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1306 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1308 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1309 << Ptr->getType() << Ptr->getSourceRange();
1313 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1314 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1315 QualType ValType = AtomTy; // 'C'
1317 if (!AtomTy->isAtomicType()) {
1318 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1319 << Ptr->getType() << Ptr->getSourceRange();
1322 if (AtomTy.isConstQualified()) {
1323 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1324 << Ptr->getType() << Ptr->getSourceRange();
1327 ValType = AtomTy->getAs<AtomicType>()->getValueType();
1330 // For an arithmetic operation, the implied arithmetic must be well-formed.
1331 if (Form == Arithmetic) {
1332 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1333 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1334 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1335 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1338 if (!IsAddSub && !ValType->isIntegerType()) {
1339 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1340 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1343 if (IsC11 && ValType->isPointerType() &&
1344 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1345 diag::err_incomplete_type)) {
1348 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1349 // For __atomic_*_n operations, the value type must be a scalar integral or
1350 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1351 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1352 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1356 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1357 !AtomTy->isScalarType()) {
1358 // For GNU atomics, require a trivially-copyable type. This is not part of
1359 // the GNU atomics specification, but we enforce it for sanity.
1360 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1361 << Ptr->getType() << Ptr->getSourceRange();
1365 // FIXME: For any builtin other than a load, the ValType must not be
1368 switch (ValType.getObjCLifetime()) {
1369 case Qualifiers::OCL_None:
1370 case Qualifiers::OCL_ExplicitNone:
1374 case Qualifiers::OCL_Weak:
1375 case Qualifiers::OCL_Strong:
1376 case Qualifiers::OCL_Autoreleasing:
1377 // FIXME: Can this happen? By this point, ValType should be known
1378 // to be trivially copyable.
1379 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1380 << ValType << Ptr->getSourceRange();
1384 QualType ResultType = ValType;
1385 if (Form == Copy || Form == GNUXchg || Form == Init)
1386 ResultType = Context.VoidTy;
1387 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1388 ResultType = Context.BoolTy;
1390 // The type of a parameter passed 'by value'. In the GNU atomics, such
1391 // arguments are actually passed as pointers.
1392 QualType ByValType = ValType; // 'CP'
1394 ByValType = Ptr->getType();
1396 // The first argument --- the pointer --- has a fixed type; we
1397 // deduce the types of the rest of the arguments accordingly. Walk
1398 // the remaining arguments, converting them to the deduced value type.
1399 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1401 if (i < NumVals[Form] + 1) {
1404 // The second argument is the non-atomic operand. For arithmetic, this
1405 // is always passed by value, and for a compare_exchange it is always
1406 // passed by address. For the rest, GNU uses by-address and C11 uses
1408 assert(Form != Load);
1409 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1411 else if (Form == Copy || Form == Xchg)
1413 else if (Form == Arithmetic)
1414 Ty = Context.getPointerDiffType();
1416 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1419 // The third argument to compare_exchange / GNU exchange is a
1420 // (pointer to a) desired value.
1424 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1425 Ty = Context.BoolTy;
1429 // The order(s) are always converted to int.
1433 InitializedEntity Entity =
1434 InitializedEntity::InitializeParameter(Context, Ty, false);
1435 ExprResult Arg = TheCall->getArg(i);
1436 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1437 if (Arg.isInvalid())
1439 TheCall->setArg(i, Arg.get());
1442 // Permute the arguments into a 'consistent' order.
1443 SmallVector<Expr*, 5> SubExprs;
1444 SubExprs.push_back(Ptr);
1447 // Note, AtomicExpr::getVal1() has a special case for this atomic.
1448 SubExprs.push_back(TheCall->getArg(1)); // Val1
1451 SubExprs.push_back(TheCall->getArg(1)); // Order
1456 SubExprs.push_back(TheCall->getArg(2)); // Order
1457 SubExprs.push_back(TheCall->getArg(1)); // Val1
1460 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1461 SubExprs.push_back(TheCall->getArg(3)); // Order
1462 SubExprs.push_back(TheCall->getArg(1)); // Val1
1463 SubExprs.push_back(TheCall->getArg(2)); // Val2
1466 SubExprs.push_back(TheCall->getArg(3)); // Order
1467 SubExprs.push_back(TheCall->getArg(1)); // Val1
1468 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1469 SubExprs.push_back(TheCall->getArg(2)); // Val2
1472 SubExprs.push_back(TheCall->getArg(4)); // Order
1473 SubExprs.push_back(TheCall->getArg(1)); // Val1
1474 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1475 SubExprs.push_back(TheCall->getArg(2)); // Val2
1476 SubExprs.push_back(TheCall->getArg(3)); // Weak
1480 if (SubExprs.size() >= 2 && Form != Init) {
1481 llvm::APSInt Result(32);
1482 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1483 !isValidOrderingForOp(Result.getSExtValue(), Op))
1484 Diag(SubExprs[1]->getLocStart(),
1485 diag::warn_atomic_op_has_invalid_memory_order)
1486 << SubExprs[1]->getSourceRange();
1489 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1490 SubExprs, ResultType, Op,
1491 TheCall->getRParenLoc());
1493 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1494 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1495 Context.AtomicUsesUnsupportedLibcall(AE))
1496 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1497 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1503 /// checkBuiltinArgument - Given a call to a builtin function, perform
1504 /// normal type-checking on the given argument, updating the call in
1505 /// place. This is useful when a builtin function requires custom
1506 /// type-checking for some of its arguments but not necessarily all of
1509 /// Returns true on error.
1510 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1511 FunctionDecl *Fn = E->getDirectCallee();
1512 assert(Fn && "builtin call without direct callee!");
1514 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1515 InitializedEntity Entity =
1516 InitializedEntity::InitializeParameter(S.Context, Param);
1518 ExprResult Arg = E->getArg(0);
1519 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1520 if (Arg.isInvalid())
1523 E->setArg(ArgIndex, Arg.get());
1527 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1528 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1529 /// type of its first argument. The main ActOnCallExpr routines have already
1530 /// promoted the types of arguments because all of these calls are prototyped as
1533 /// This function goes through and does final semantic checking for these
1536 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1537 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1538 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1539 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1541 // Ensure that we have at least one argument to do type inference from.
1542 if (TheCall->getNumArgs() < 1) {
1543 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1544 << 0 << 1 << TheCall->getNumArgs()
1545 << TheCall->getCallee()->getSourceRange();
1549 // Inspect the first argument of the atomic builtin. This should always be
1550 // a pointer type, whose element is an integral scalar or pointer type.
1551 // Because it is a pointer type, we don't have to worry about any implicit
1553 // FIXME: We don't allow floating point scalars as input.
1554 Expr *FirstArg = TheCall->getArg(0);
1555 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1556 if (FirstArgResult.isInvalid())
1558 FirstArg = FirstArgResult.get();
1559 TheCall->setArg(0, FirstArg);
1561 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1563 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1564 << FirstArg->getType() << FirstArg->getSourceRange();
1568 QualType ValType = pointerType->getPointeeType();
1569 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1570 !ValType->isBlockPointerType()) {
1571 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1572 << FirstArg->getType() << FirstArg->getSourceRange();
1576 switch (ValType.getObjCLifetime()) {
1577 case Qualifiers::OCL_None:
1578 case Qualifiers::OCL_ExplicitNone:
1582 case Qualifiers::OCL_Weak:
1583 case Qualifiers::OCL_Strong:
1584 case Qualifiers::OCL_Autoreleasing:
1585 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1586 << ValType << FirstArg->getSourceRange();
1590 // Strip any qualifiers off ValType.
1591 ValType = ValType.getUnqualifiedType();
1593 // The majority of builtins return a value, but a few have special return
1594 // types, so allow them to override appropriately below.
1595 QualType ResultType = ValType;
1597 // We need to figure out which concrete builtin this maps onto. For example,
1598 // __sync_fetch_and_add with a 2 byte object turns into
1599 // __sync_fetch_and_add_2.
1600 #define BUILTIN_ROW(x) \
1601 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1602 Builtin::BI##x##_8, Builtin::BI##x##_16 }
1604 static const unsigned BuiltinIndices[][5] = {
1605 BUILTIN_ROW(__sync_fetch_and_add),
1606 BUILTIN_ROW(__sync_fetch_and_sub),
1607 BUILTIN_ROW(__sync_fetch_and_or),
1608 BUILTIN_ROW(__sync_fetch_and_and),
1609 BUILTIN_ROW(__sync_fetch_and_xor),
1610 BUILTIN_ROW(__sync_fetch_and_nand),
1612 BUILTIN_ROW(__sync_add_and_fetch),
1613 BUILTIN_ROW(__sync_sub_and_fetch),
1614 BUILTIN_ROW(__sync_and_and_fetch),
1615 BUILTIN_ROW(__sync_or_and_fetch),
1616 BUILTIN_ROW(__sync_xor_and_fetch),
1617 BUILTIN_ROW(__sync_nand_and_fetch),
1619 BUILTIN_ROW(__sync_val_compare_and_swap),
1620 BUILTIN_ROW(__sync_bool_compare_and_swap),
1621 BUILTIN_ROW(__sync_lock_test_and_set),
1622 BUILTIN_ROW(__sync_lock_release),
1623 BUILTIN_ROW(__sync_swap)
1627 // Determine the index of the size.
1629 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1630 case 1: SizeIndex = 0; break;
1631 case 2: SizeIndex = 1; break;
1632 case 4: SizeIndex = 2; break;
1633 case 8: SizeIndex = 3; break;
1634 case 16: SizeIndex = 4; break;
1636 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1637 << FirstArg->getType() << FirstArg->getSourceRange();
1641 // Each of these builtins has one pointer argument, followed by some number of
1642 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1643 // that we ignore. Find out which row of BuiltinIndices to read from as well
1644 // as the number of fixed args.
1645 unsigned BuiltinID = FDecl->getBuiltinID();
1646 unsigned BuiltinIndex, NumFixed = 1;
1647 bool WarnAboutSemanticsChange = false;
1648 switch (BuiltinID) {
1649 default: llvm_unreachable("Unknown overloaded atomic builtin!");
1650 case Builtin::BI__sync_fetch_and_add:
1651 case Builtin::BI__sync_fetch_and_add_1:
1652 case Builtin::BI__sync_fetch_and_add_2:
1653 case Builtin::BI__sync_fetch_and_add_4:
1654 case Builtin::BI__sync_fetch_and_add_8:
1655 case Builtin::BI__sync_fetch_and_add_16:
1659 case Builtin::BI__sync_fetch_and_sub:
1660 case Builtin::BI__sync_fetch_and_sub_1:
1661 case Builtin::BI__sync_fetch_and_sub_2:
1662 case Builtin::BI__sync_fetch_and_sub_4:
1663 case Builtin::BI__sync_fetch_and_sub_8:
1664 case Builtin::BI__sync_fetch_and_sub_16:
1668 case Builtin::BI__sync_fetch_and_or:
1669 case Builtin::BI__sync_fetch_and_or_1:
1670 case Builtin::BI__sync_fetch_and_or_2:
1671 case Builtin::BI__sync_fetch_and_or_4:
1672 case Builtin::BI__sync_fetch_and_or_8:
1673 case Builtin::BI__sync_fetch_and_or_16:
1677 case Builtin::BI__sync_fetch_and_and:
1678 case Builtin::BI__sync_fetch_and_and_1:
1679 case Builtin::BI__sync_fetch_and_and_2:
1680 case Builtin::BI__sync_fetch_and_and_4:
1681 case Builtin::BI__sync_fetch_and_and_8:
1682 case Builtin::BI__sync_fetch_and_and_16:
1686 case Builtin::BI__sync_fetch_and_xor:
1687 case Builtin::BI__sync_fetch_and_xor_1:
1688 case Builtin::BI__sync_fetch_and_xor_2:
1689 case Builtin::BI__sync_fetch_and_xor_4:
1690 case Builtin::BI__sync_fetch_and_xor_8:
1691 case Builtin::BI__sync_fetch_and_xor_16:
1695 case Builtin::BI__sync_fetch_and_nand:
1696 case Builtin::BI__sync_fetch_and_nand_1:
1697 case Builtin::BI__sync_fetch_and_nand_2:
1698 case Builtin::BI__sync_fetch_and_nand_4:
1699 case Builtin::BI__sync_fetch_and_nand_8:
1700 case Builtin::BI__sync_fetch_and_nand_16:
1702 WarnAboutSemanticsChange = true;
1705 case Builtin::BI__sync_add_and_fetch:
1706 case Builtin::BI__sync_add_and_fetch_1:
1707 case Builtin::BI__sync_add_and_fetch_2:
1708 case Builtin::BI__sync_add_and_fetch_4:
1709 case Builtin::BI__sync_add_and_fetch_8:
1710 case Builtin::BI__sync_add_and_fetch_16:
1714 case Builtin::BI__sync_sub_and_fetch:
1715 case Builtin::BI__sync_sub_and_fetch_1:
1716 case Builtin::BI__sync_sub_and_fetch_2:
1717 case Builtin::BI__sync_sub_and_fetch_4:
1718 case Builtin::BI__sync_sub_and_fetch_8:
1719 case Builtin::BI__sync_sub_and_fetch_16:
1723 case Builtin::BI__sync_and_and_fetch:
1724 case Builtin::BI__sync_and_and_fetch_1:
1725 case Builtin::BI__sync_and_and_fetch_2:
1726 case Builtin::BI__sync_and_and_fetch_4:
1727 case Builtin::BI__sync_and_and_fetch_8:
1728 case Builtin::BI__sync_and_and_fetch_16:
1732 case Builtin::BI__sync_or_and_fetch:
1733 case Builtin::BI__sync_or_and_fetch_1:
1734 case Builtin::BI__sync_or_and_fetch_2:
1735 case Builtin::BI__sync_or_and_fetch_4:
1736 case Builtin::BI__sync_or_and_fetch_8:
1737 case Builtin::BI__sync_or_and_fetch_16:
1741 case Builtin::BI__sync_xor_and_fetch:
1742 case Builtin::BI__sync_xor_and_fetch_1:
1743 case Builtin::BI__sync_xor_and_fetch_2:
1744 case Builtin::BI__sync_xor_and_fetch_4:
1745 case Builtin::BI__sync_xor_and_fetch_8:
1746 case Builtin::BI__sync_xor_and_fetch_16:
1750 case Builtin::BI__sync_nand_and_fetch:
1751 case Builtin::BI__sync_nand_and_fetch_1:
1752 case Builtin::BI__sync_nand_and_fetch_2:
1753 case Builtin::BI__sync_nand_and_fetch_4:
1754 case Builtin::BI__sync_nand_and_fetch_8:
1755 case Builtin::BI__sync_nand_and_fetch_16:
1757 WarnAboutSemanticsChange = true;
1760 case Builtin::BI__sync_val_compare_and_swap:
1761 case Builtin::BI__sync_val_compare_and_swap_1:
1762 case Builtin::BI__sync_val_compare_and_swap_2:
1763 case Builtin::BI__sync_val_compare_and_swap_4:
1764 case Builtin::BI__sync_val_compare_and_swap_8:
1765 case Builtin::BI__sync_val_compare_and_swap_16:
1770 case Builtin::BI__sync_bool_compare_and_swap:
1771 case Builtin::BI__sync_bool_compare_and_swap_1:
1772 case Builtin::BI__sync_bool_compare_and_swap_2:
1773 case Builtin::BI__sync_bool_compare_and_swap_4:
1774 case Builtin::BI__sync_bool_compare_and_swap_8:
1775 case Builtin::BI__sync_bool_compare_and_swap_16:
1778 ResultType = Context.BoolTy;
1781 case Builtin::BI__sync_lock_test_and_set:
1782 case Builtin::BI__sync_lock_test_and_set_1:
1783 case Builtin::BI__sync_lock_test_and_set_2:
1784 case Builtin::BI__sync_lock_test_and_set_4:
1785 case Builtin::BI__sync_lock_test_and_set_8:
1786 case Builtin::BI__sync_lock_test_and_set_16:
1790 case Builtin::BI__sync_lock_release:
1791 case Builtin::BI__sync_lock_release_1:
1792 case Builtin::BI__sync_lock_release_2:
1793 case Builtin::BI__sync_lock_release_4:
1794 case Builtin::BI__sync_lock_release_8:
1795 case Builtin::BI__sync_lock_release_16:
1798 ResultType = Context.VoidTy;
1801 case Builtin::BI__sync_swap:
1802 case Builtin::BI__sync_swap_1:
1803 case Builtin::BI__sync_swap_2:
1804 case Builtin::BI__sync_swap_4:
1805 case Builtin::BI__sync_swap_8:
1806 case Builtin::BI__sync_swap_16:
1811 // Now that we know how many fixed arguments we expect, first check that we
1812 // have at least that many.
1813 if (TheCall->getNumArgs() < 1+NumFixed) {
1814 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1815 << 0 << 1+NumFixed << TheCall->getNumArgs()
1816 << TheCall->getCallee()->getSourceRange();
1820 if (WarnAboutSemanticsChange) {
1821 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1822 << TheCall->getCallee()->getSourceRange();
1825 // Get the decl for the concrete builtin from this, we can tell what the
1826 // concrete integer type we should convert to is.
1827 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1828 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1829 FunctionDecl *NewBuiltinDecl;
1830 if (NewBuiltinID == BuiltinID)
1831 NewBuiltinDecl = FDecl;
1833 // Perform builtin lookup to avoid redeclaring it.
1834 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1835 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1836 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1837 assert(Res.getFoundDecl());
1838 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1839 if (!NewBuiltinDecl)
1843 // The first argument --- the pointer --- has a fixed type; we
1844 // deduce the types of the rest of the arguments accordingly. Walk
1845 // the remaining arguments, converting them to the deduced value type.
1846 for (unsigned i = 0; i != NumFixed; ++i) {
1847 ExprResult Arg = TheCall->getArg(i+1);
1849 // GCC does an implicit conversion to the pointer or integer ValType. This
1850 // can fail in some cases (1i -> int**), check for this error case now.
1851 // Initialize the argument.
1852 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1853 ValType, /*consume*/ false);
1854 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1855 if (Arg.isInvalid())
1858 // Okay, we have something that *can* be converted to the right type. Check
1859 // to see if there is a potentially weird extension going on here. This can
1860 // happen when you do an atomic operation on something like an char* and
1861 // pass in 42. The 42 gets converted to char. This is even more strange
1862 // for things like 45.123 -> char, etc.
1863 // FIXME: Do this check.
1864 TheCall->setArg(i+1, Arg.get());
1867 ASTContext& Context = this->getASTContext();
1869 // Create a new DeclRefExpr to refer to the new decl.
1870 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1872 DRE->getQualifierLoc(),
1875 /*enclosing*/ false,
1877 Context.BuiltinFnTy,
1878 DRE->getValueKind());
1880 // Set the callee in the CallExpr.
1881 // FIXME: This loses syntactic information.
1882 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1883 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1884 CK_BuiltinFnToFnPtr);
1885 TheCall->setCallee(PromotedCall.get());
1887 // Change the result type of the call to match the original value type. This
1888 // is arbitrary, but the codegen for these builtins ins design to handle it
1890 TheCall->setType(ResultType);
1892 return TheCallResult;
1895 /// CheckObjCString - Checks that the argument to the builtin
1896 /// CFString constructor is correct
1897 /// Note: It might also make sense to do the UTF-16 conversion here (would
1898 /// simplify the backend).
1899 bool Sema::CheckObjCString(Expr *Arg) {
1900 Arg = Arg->IgnoreParenCasts();
1901 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1903 if (!Literal || !Literal->isAscii()) {
1904 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1905 << Arg->getSourceRange();
1909 if (Literal->containsNonAsciiOrNull()) {
1910 StringRef String = Literal->getString();
1911 unsigned NumBytes = String.size();
1912 SmallVector<UTF16, 128> ToBuf(NumBytes);
1913 const UTF8 *FromPtr = (const UTF8 *)String.data();
1914 UTF16 *ToPtr = &ToBuf[0];
1916 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1917 &ToPtr, ToPtr + NumBytes,
1919 // Check for conversion failure.
1920 if (Result != conversionOK)
1921 Diag(Arg->getLocStart(),
1922 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1927 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1928 /// Emit an error and return true on failure, return false on success.
1929 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1930 Expr *Fn = TheCall->getCallee();
1931 if (TheCall->getNumArgs() > 2) {
1932 Diag(TheCall->getArg(2)->getLocStart(),
1933 diag::err_typecheck_call_too_many_args)
1934 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1935 << Fn->getSourceRange()
1936 << SourceRange(TheCall->getArg(2)->getLocStart(),
1937 (*(TheCall->arg_end()-1))->getLocEnd());
1941 if (TheCall->getNumArgs() < 2) {
1942 return Diag(TheCall->getLocEnd(),
1943 diag::err_typecheck_call_too_few_args_at_least)
1944 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1947 // Type-check the first argument normally.
1948 if (checkBuiltinArgument(*this, TheCall, 0))
1951 // Determine whether the current function is variadic or not.
1952 BlockScopeInfo *CurBlock = getCurBlock();
1955 isVariadic = CurBlock->TheDecl->isVariadic();
1956 else if (FunctionDecl *FD = getCurFunctionDecl())
1957 isVariadic = FD->isVariadic();
1959 isVariadic = getCurMethodDecl()->isVariadic();
1962 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1966 // Verify that the second argument to the builtin is the last argument of the
1967 // current function or method.
1968 bool SecondArgIsLastNamedArgument = false;
1969 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1971 // These are valid if SecondArgIsLastNamedArgument is false after the next
1974 SourceLocation ParamLoc;
1976 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1977 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1978 // FIXME: This isn't correct for methods (results in bogus warning).
1979 // Get the last formal in the current function.
1980 const ParmVarDecl *LastArg;
1982 LastArg = *(CurBlock->TheDecl->param_end()-1);
1983 else if (FunctionDecl *FD = getCurFunctionDecl())
1984 LastArg = *(FD->param_end()-1);
1986 LastArg = *(getCurMethodDecl()->param_end()-1);
1987 SecondArgIsLastNamedArgument = PV == LastArg;
1989 Type = PV->getType();
1990 ParamLoc = PV->getLocation();
1994 if (!SecondArgIsLastNamedArgument)
1995 Diag(TheCall->getArg(1)->getLocStart(),
1996 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1997 else if (Type->isReferenceType()) {
1998 Diag(Arg->getLocStart(),
1999 diag::warn_va_start_of_reference_type_is_undefined);
2000 Diag(ParamLoc, diag::note_parameter_type) << Type;
2003 TheCall->setType(Context.VoidTy);
2007 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2008 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2009 // const char *named_addr);
2011 Expr *Func = Call->getCallee();
2013 if (Call->getNumArgs() < 3)
2014 return Diag(Call->getLocEnd(),
2015 diag::err_typecheck_call_too_few_args_at_least)
2016 << 0 /*function call*/ << 3 << Call->getNumArgs();
2018 // Determine whether the current function is variadic or not.
2020 if (BlockScopeInfo *CurBlock = getCurBlock())
2021 IsVariadic = CurBlock->TheDecl->isVariadic();
2022 else if (FunctionDecl *FD = getCurFunctionDecl())
2023 IsVariadic = FD->isVariadic();
2024 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2025 IsVariadic = MD->isVariadic();
2027 llvm_unreachable("unexpected statement type");
2030 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2034 // Type-check the first argument normally.
2035 if (checkBuiltinArgument(*this, Call, 0))
2038 static const struct {
2041 } ArgumentTypes[] = {
2042 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2043 { 2, Context.getSizeType() },
2046 for (const auto &AT : ArgumentTypes) {
2047 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2048 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2050 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2051 << Arg->getType() << AT.Type << 1 /* different class */
2052 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2053 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2059 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2060 /// friends. This is declared to take (...), so we have to check everything.
2061 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2062 if (TheCall->getNumArgs() < 2)
2063 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2064 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2065 if (TheCall->getNumArgs() > 2)
2066 return Diag(TheCall->getArg(2)->getLocStart(),
2067 diag::err_typecheck_call_too_many_args)
2068 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2069 << SourceRange(TheCall->getArg(2)->getLocStart(),
2070 (*(TheCall->arg_end()-1))->getLocEnd());
2072 ExprResult OrigArg0 = TheCall->getArg(0);
2073 ExprResult OrigArg1 = TheCall->getArg(1);
2075 // Do standard promotions between the two arguments, returning their common
2077 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2078 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2081 // Make sure any conversions are pushed back into the call; this is
2082 // type safe since unordered compare builtins are declared as "_Bool
2084 TheCall->setArg(0, OrigArg0.get());
2085 TheCall->setArg(1, OrigArg1.get());
2087 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2090 // If the common type isn't a real floating type, then the arguments were
2091 // invalid for this operation.
2092 if (Res.isNull() || !Res->isRealFloatingType())
2093 return Diag(OrigArg0.get()->getLocStart(),
2094 diag::err_typecheck_call_invalid_ordered_compare)
2095 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2096 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2101 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2102 /// __builtin_isnan and friends. This is declared to take (...), so we have
2103 /// to check everything. We expect the last argument to be a floating point
2105 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2106 if (TheCall->getNumArgs() < NumArgs)
2107 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2108 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2109 if (TheCall->getNumArgs() > NumArgs)
2110 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2111 diag::err_typecheck_call_too_many_args)
2112 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2113 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2114 (*(TheCall->arg_end()-1))->getLocEnd());
2116 Expr *OrigArg = TheCall->getArg(NumArgs-1);
2118 if (OrigArg->isTypeDependent())
2121 // This operation requires a non-_Complex floating-point number.
2122 if (!OrigArg->getType()->isRealFloatingType())
2123 return Diag(OrigArg->getLocStart(),
2124 diag::err_typecheck_call_invalid_unary_fp)
2125 << OrigArg->getType() << OrigArg->getSourceRange();
2127 // If this is an implicit conversion from float -> double, remove it.
2128 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2129 Expr *CastArg = Cast->getSubExpr();
2130 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2131 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2132 "promotion from float to double is the only expected cast here");
2133 Cast->setSubExpr(nullptr);
2134 TheCall->setArg(NumArgs-1, CastArg);
2141 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2142 // This is declared to take (...), so we have to check everything.
2143 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2144 if (TheCall->getNumArgs() < 2)
2145 return ExprError(Diag(TheCall->getLocEnd(),
2146 diag::err_typecheck_call_too_few_args_at_least)
2147 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2148 << TheCall->getSourceRange());
2150 // Determine which of the following types of shufflevector we're checking:
2151 // 1) unary, vector mask: (lhs, mask)
2152 // 2) binary, vector mask: (lhs, rhs, mask)
2153 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2154 QualType resType = TheCall->getArg(0)->getType();
2155 unsigned numElements = 0;
2157 if (!TheCall->getArg(0)->isTypeDependent() &&
2158 !TheCall->getArg(1)->isTypeDependent()) {
2159 QualType LHSType = TheCall->getArg(0)->getType();
2160 QualType RHSType = TheCall->getArg(1)->getType();
2162 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2163 return ExprError(Diag(TheCall->getLocStart(),
2164 diag::err_shufflevector_non_vector)
2165 << SourceRange(TheCall->getArg(0)->getLocStart(),
2166 TheCall->getArg(1)->getLocEnd()));
2168 numElements = LHSType->getAs<VectorType>()->getNumElements();
2169 unsigned numResElements = TheCall->getNumArgs() - 2;
2171 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2172 // with mask. If so, verify that RHS is an integer vector type with the
2173 // same number of elts as lhs.
2174 if (TheCall->getNumArgs() == 2) {
2175 if (!RHSType->hasIntegerRepresentation() ||
2176 RHSType->getAs<VectorType>()->getNumElements() != numElements)
2177 return ExprError(Diag(TheCall->getLocStart(),
2178 diag::err_shufflevector_incompatible_vector)
2179 << SourceRange(TheCall->getArg(1)->getLocStart(),
2180 TheCall->getArg(1)->getLocEnd()));
2181 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2182 return ExprError(Diag(TheCall->getLocStart(),
2183 diag::err_shufflevector_incompatible_vector)
2184 << SourceRange(TheCall->getArg(0)->getLocStart(),
2185 TheCall->getArg(1)->getLocEnd()));
2186 } else if (numElements != numResElements) {
2187 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2188 resType = Context.getVectorType(eltType, numResElements,
2189 VectorType::GenericVector);
2193 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2194 if (TheCall->getArg(i)->isTypeDependent() ||
2195 TheCall->getArg(i)->isValueDependent())
2198 llvm::APSInt Result(32);
2199 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2200 return ExprError(Diag(TheCall->getLocStart(),
2201 diag::err_shufflevector_nonconstant_argument)
2202 << TheCall->getArg(i)->getSourceRange());
2204 // Allow -1 which will be translated to undef in the IR.
2205 if (Result.isSigned() && Result.isAllOnesValue())
2208 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2209 return ExprError(Diag(TheCall->getLocStart(),
2210 diag::err_shufflevector_argument_too_large)
2211 << TheCall->getArg(i)->getSourceRange());
2214 SmallVector<Expr*, 32> exprs;
2216 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2217 exprs.push_back(TheCall->getArg(i));
2218 TheCall->setArg(i, nullptr);
2221 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2222 TheCall->getCallee()->getLocStart(),
2223 TheCall->getRParenLoc());
2226 /// SemaConvertVectorExpr - Handle __builtin_convertvector
2227 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2228 SourceLocation BuiltinLoc,
2229 SourceLocation RParenLoc) {
2230 ExprValueKind VK = VK_RValue;
2231 ExprObjectKind OK = OK_Ordinary;
2232 QualType DstTy = TInfo->getType();
2233 QualType SrcTy = E->getType();
2235 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2236 return ExprError(Diag(BuiltinLoc,
2237 diag::err_convertvector_non_vector)
2238 << E->getSourceRange());
2239 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2240 return ExprError(Diag(BuiltinLoc,
2241 diag::err_convertvector_non_vector_type));
2243 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2244 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2245 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2246 if (SrcElts != DstElts)
2247 return ExprError(Diag(BuiltinLoc,
2248 diag::err_convertvector_incompatible_vector)
2249 << E->getSourceRange());
2252 return new (Context)
2253 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
2256 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2257 // This is declared to take (const void*, ...) and can take two
2258 // optional constant int args.
2259 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
2260 unsigned NumArgs = TheCall->getNumArgs();
2263 return Diag(TheCall->getLocEnd(),
2264 diag::err_typecheck_call_too_many_args_at_most)
2265 << 0 /*function call*/ << 3 << NumArgs
2266 << TheCall->getSourceRange();
2268 // Argument 0 is checked for us and the remaining arguments must be
2269 // constant integers.
2270 for (unsigned i = 1; i != NumArgs; ++i)
2271 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2277 /// SemaBuiltinAssume - Handle __assume (MS Extension).
2278 // __assume does not evaluate its arguments, and should warn if its argument
2279 // has side effects.
2280 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2281 Expr *Arg = TheCall->getArg(0);
2282 if (Arg->isInstantiationDependent()) return false;
2284 if (Arg->HasSideEffects(Context))
2285 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2286 << Arg->getSourceRange()
2287 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2292 /// Handle __builtin_assume_aligned. This is declared
2293 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2294 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2295 unsigned NumArgs = TheCall->getNumArgs();
2298 return Diag(TheCall->getLocEnd(),
2299 diag::err_typecheck_call_too_many_args_at_most)
2300 << 0 /*function call*/ << 3 << NumArgs
2301 << TheCall->getSourceRange();
2303 // The alignment must be a constant integer.
2304 Expr *Arg = TheCall->getArg(1);
2306 // We can't check the value of a dependent argument.
2307 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2308 llvm::APSInt Result;
2309 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2312 if (!Result.isPowerOf2())
2313 return Diag(TheCall->getLocStart(),
2314 diag::err_alignment_not_power_of_two)
2315 << Arg->getSourceRange();
2319 ExprResult Arg(TheCall->getArg(2));
2320 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2321 Context.getSizeType(), false);
2322 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2323 if (Arg.isInvalid()) return true;
2324 TheCall->setArg(2, Arg.get());
2330 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2331 /// TheCall is a constant expression.
2332 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2333 llvm::APSInt &Result) {
2334 Expr *Arg = TheCall->getArg(ArgNum);
2335 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2336 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2338 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2340 if (!Arg->isIntegerConstantExpr(Result, Context))
2341 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
2342 << FDecl->getDeclName() << Arg->getSourceRange();
2347 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2348 /// TheCall is a constant expression in the range [Low, High].
2349 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2350 int Low, int High) {
2351 llvm::APSInt Result;
2353 // We can't check the value of a dependent argument.
2354 Expr *Arg = TheCall->getArg(ArgNum);
2355 if (Arg->isTypeDependent() || Arg->isValueDependent())
2358 // Check constant-ness first.
2359 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2362 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2363 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2364 << Low << High << Arg->getSourceRange();
2369 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2370 /// This checks that val is a constant 1.
2371 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2372 Expr *Arg = TheCall->getArg(1);
2373 llvm::APSInt Result;
2375 // TODO: This is less than ideal. Overload this to take a value.
2376 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2380 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2381 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2387 enum StringLiteralCheckType {
2389 SLCT_UncheckedLiteral,
2394 // Determine if an expression is a string literal or constant string.
2395 // If this function returns false on the arguments to a function expecting a
2396 // format string, we will usually need to emit a warning.
2397 // True string literals are then checked by CheckFormatString.
2398 static StringLiteralCheckType
2399 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2400 bool HasVAListArg, unsigned format_idx,
2401 unsigned firstDataArg, Sema::FormatStringType Type,
2402 Sema::VariadicCallType CallType, bool InFunctionCall,
2403 llvm::SmallBitVector &CheckedVarArgs) {
2405 if (E->isTypeDependent() || E->isValueDependent())
2406 return SLCT_NotALiteral;
2408 E = E->IgnoreParenCasts();
2410 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2411 // Technically -Wformat-nonliteral does not warn about this case.
2412 // The behavior of printf and friends in this case is implementation
2413 // dependent. Ideally if the format string cannot be null then
2414 // it should have a 'nonnull' attribute in the function prototype.
2415 return SLCT_UncheckedLiteral;
2417 switch (E->getStmtClass()) {
2418 case Stmt::BinaryConditionalOperatorClass:
2419 case Stmt::ConditionalOperatorClass: {
2420 // The expression is a literal if both sub-expressions were, and it was
2421 // completely checked only if both sub-expressions were checked.
2422 const AbstractConditionalOperator *C =
2423 cast<AbstractConditionalOperator>(E);
2424 StringLiteralCheckType Left =
2425 checkFormatStringExpr(S, C->getTrueExpr(), Args,
2426 HasVAListArg, format_idx, firstDataArg,
2427 Type, CallType, InFunctionCall, CheckedVarArgs);
2428 if (Left == SLCT_NotALiteral)
2429 return SLCT_NotALiteral;
2430 StringLiteralCheckType Right =
2431 checkFormatStringExpr(S, C->getFalseExpr(), Args,
2432 HasVAListArg, format_idx, firstDataArg,
2433 Type, CallType, InFunctionCall, CheckedVarArgs);
2434 return Left < Right ? Left : Right;
2437 case Stmt::ImplicitCastExprClass: {
2438 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2442 case Stmt::OpaqueValueExprClass:
2443 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2447 return SLCT_NotALiteral;
2449 case Stmt::PredefinedExprClass:
2450 // While __func__, etc., are technically not string literals, they
2451 // cannot contain format specifiers and thus are not a security
2453 return SLCT_UncheckedLiteral;
2455 case Stmt::DeclRefExprClass: {
2456 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2458 // As an exception, do not flag errors for variables binding to
2459 // const string literals.
2460 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2461 bool isConstant = false;
2462 QualType T = DR->getType();
2464 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2465 isConstant = AT->getElementType().isConstant(S.Context);
2466 } else if (const PointerType *PT = T->getAs<PointerType>()) {
2467 isConstant = T.isConstant(S.Context) &&
2468 PT->getPointeeType().isConstant(S.Context);
2469 } else if (T->isObjCObjectPointerType()) {
2470 // In ObjC, there is usually no "const ObjectPointer" type,
2471 // so don't check if the pointee type is constant.
2472 isConstant = T.isConstant(S.Context);
2476 if (const Expr *Init = VD->getAnyInitializer()) {
2477 // Look through initializers like const char c[] = { "foo" }
2478 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2479 if (InitList->isStringLiteralInit())
2480 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2482 return checkFormatStringExpr(S, Init, Args,
2483 HasVAListArg, format_idx,
2484 firstDataArg, Type, CallType,
2485 /*InFunctionCall*/false, CheckedVarArgs);
2489 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2490 // special check to see if the format string is a function parameter
2491 // of the function calling the printf function. If the function
2492 // has an attribute indicating it is a printf-like function, then we
2493 // should suppress warnings concerning non-literals being used in a call
2494 // to a vprintf function. For example:
2497 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2499 // va_start(ap, fmt);
2500 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2504 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2505 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2506 int PVIndex = PV->getFunctionScopeIndex() + 1;
2507 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2508 // adjust for implicit parameter
2509 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2510 if (MD->isInstance())
2512 // We also check if the formats are compatible.
2513 // We can't pass a 'scanf' string to a 'printf' function.
2514 if (PVIndex == PVFormat->getFormatIdx() &&
2515 Type == S.GetFormatStringType(PVFormat))
2516 return SLCT_UncheckedLiteral;
2523 return SLCT_NotALiteral;
2526 case Stmt::CallExprClass:
2527 case Stmt::CXXMemberCallExprClass: {
2528 const CallExpr *CE = cast<CallExpr>(E);
2529 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2530 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2531 unsigned ArgIndex = FA->getFormatIdx();
2532 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2533 if (MD->isInstance())
2535 const Expr *Arg = CE->getArg(ArgIndex - 1);
2537 return checkFormatStringExpr(S, Arg, Args,
2538 HasVAListArg, format_idx, firstDataArg,
2539 Type, CallType, InFunctionCall,
2541 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2542 unsigned BuiltinID = FD->getBuiltinID();
2543 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2544 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2545 const Expr *Arg = CE->getArg(0);
2546 return checkFormatStringExpr(S, Arg, Args,
2547 HasVAListArg, format_idx,
2548 firstDataArg, Type, CallType,
2549 InFunctionCall, CheckedVarArgs);
2554 return SLCT_NotALiteral;
2556 case Stmt::ObjCStringLiteralClass:
2557 case Stmt::StringLiteralClass: {
2558 const StringLiteral *StrE = nullptr;
2560 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2561 StrE = ObjCFExpr->getString();
2563 StrE = cast<StringLiteral>(E);
2566 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2567 Type, InFunctionCall, CallType, CheckedVarArgs);
2568 return SLCT_CheckedLiteral;
2571 return SLCT_NotALiteral;
2575 return SLCT_NotALiteral;
2579 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2580 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2581 .Case("scanf", FST_Scanf)
2582 .Cases("printf", "printf0", FST_Printf)
2583 .Cases("NSString", "CFString", FST_NSString)
2584 .Case("strftime", FST_Strftime)
2585 .Case("strfmon", FST_Strfmon)
2586 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2587 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
2588 .Default(FST_Unknown);
2591 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2592 /// functions) for correct use of format strings.
2593 /// Returns true if a format string has been fully checked.
2594 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2595 ArrayRef<const Expr *> Args,
2597 VariadicCallType CallType,
2598 SourceLocation Loc, SourceRange Range,
2599 llvm::SmallBitVector &CheckedVarArgs) {
2600 FormatStringInfo FSI;
2601 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2602 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2603 FSI.FirstDataArg, GetFormatStringType(Format),
2604 CallType, Loc, Range, CheckedVarArgs);
2608 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2609 bool HasVAListArg, unsigned format_idx,
2610 unsigned firstDataArg, FormatStringType Type,
2611 VariadicCallType CallType,
2612 SourceLocation Loc, SourceRange Range,
2613 llvm::SmallBitVector &CheckedVarArgs) {
2614 // CHECK: printf/scanf-like function is called with no format string.
2615 if (format_idx >= Args.size()) {
2616 Diag(Loc, diag::warn_missing_format_string) << Range;
2620 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2622 // CHECK: format string is not a string literal.
2624 // Dynamically generated format strings are difficult to
2625 // automatically vet at compile time. Requiring that format strings
2626 // are string literals: (1) permits the checking of format strings by
2627 // the compiler and thereby (2) can practically remove the source of
2628 // many format string exploits.
2630 // Format string can be either ObjC string (e.g. @"%d") or
2631 // C string (e.g. "%d")
2632 // ObjC string uses the same format specifiers as C string, so we can use
2633 // the same format string checking logic for both ObjC and C strings.
2634 StringLiteralCheckType CT =
2635 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2636 format_idx, firstDataArg, Type, CallType,
2637 /*IsFunctionCall*/true, CheckedVarArgs);
2638 if (CT != SLCT_NotALiteral)
2639 // Literal format string found, check done!
2640 return CT == SLCT_CheckedLiteral;
2642 // Strftime is particular as it always uses a single 'time' argument,
2643 // so it is safe to pass a non-literal string.
2644 if (Type == FST_Strftime)
2647 // Do not emit diag when the string param is a macro expansion and the
2648 // format is either NSString or CFString. This is a hack to prevent
2649 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2650 // which are usually used in place of NS and CF string literals.
2651 if (Type == FST_NSString &&
2652 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2655 // If there are no arguments specified, warn with -Wformat-security, otherwise
2656 // warn only with -Wformat-nonliteral.
2657 if (Args.size() == firstDataArg)
2658 Diag(Args[format_idx]->getLocStart(),
2659 diag::warn_format_nonliteral_noargs)
2660 << OrigFormatExpr->getSourceRange();
2662 Diag(Args[format_idx]->getLocStart(),
2663 diag::warn_format_nonliteral)
2664 << OrigFormatExpr->getSourceRange();
2669 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2672 const StringLiteral *FExpr;
2673 const Expr *OrigFormatExpr;
2674 const unsigned FirstDataArg;
2675 const unsigned NumDataArgs;
2676 const char *Beg; // Start of format string.
2677 const bool HasVAListArg;
2678 ArrayRef<const Expr *> Args;
2680 llvm::SmallBitVector CoveredArgs;
2681 bool usesPositionalArgs;
2683 bool inFunctionCall;
2684 Sema::VariadicCallType CallType;
2685 llvm::SmallBitVector &CheckedVarArgs;
2687 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2688 const Expr *origFormatExpr, unsigned firstDataArg,
2689 unsigned numDataArgs, const char *beg, bool hasVAListArg,
2690 ArrayRef<const Expr *> Args,
2691 unsigned formatIdx, bool inFunctionCall,
2692 Sema::VariadicCallType callType,
2693 llvm::SmallBitVector &CheckedVarArgs)
2694 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2695 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2696 Beg(beg), HasVAListArg(hasVAListArg),
2697 Args(Args), FormatIdx(formatIdx),
2698 usesPositionalArgs(false), atFirstArg(true),
2699 inFunctionCall(inFunctionCall), CallType(callType),
2700 CheckedVarArgs(CheckedVarArgs) {
2701 CoveredArgs.resize(numDataArgs);
2702 CoveredArgs.reset();
2705 void DoneProcessing();
2707 void HandleIncompleteSpecifier(const char *startSpecifier,
2708 unsigned specifierLen) override;
2710 void HandleInvalidLengthModifier(
2711 const analyze_format_string::FormatSpecifier &FS,
2712 const analyze_format_string::ConversionSpecifier &CS,
2713 const char *startSpecifier, unsigned specifierLen,
2716 void HandleNonStandardLengthModifier(
2717 const analyze_format_string::FormatSpecifier &FS,
2718 const char *startSpecifier, unsigned specifierLen);
2720 void HandleNonStandardConversionSpecifier(
2721 const analyze_format_string::ConversionSpecifier &CS,
2722 const char *startSpecifier, unsigned specifierLen);
2724 void HandlePosition(const char *startPos, unsigned posLen) override;
2726 void HandleInvalidPosition(const char *startSpecifier,
2727 unsigned specifierLen,
2728 analyze_format_string::PositionContext p) override;
2730 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
2732 void HandleNullChar(const char *nullCharacter) override;
2734 template <typename Range>
2735 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2736 const Expr *ArgumentExpr,
2737 PartialDiagnostic PDiag,
2738 SourceLocation StringLoc,
2739 bool IsStringLocation, Range StringRange,
2740 ArrayRef<FixItHint> Fixit = None);
2743 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2744 const char *startSpec,
2745 unsigned specifierLen,
2746 const char *csStart, unsigned csLen);
2748 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2749 const char *startSpec,
2750 unsigned specifierLen);
2752 SourceRange getFormatStringRange();
2753 CharSourceRange getSpecifierRange(const char *startSpecifier,
2754 unsigned specifierLen);
2755 SourceLocation getLocationOfByte(const char *x);
2757 const Expr *getDataArg(unsigned i) const;
2759 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2760 const analyze_format_string::ConversionSpecifier &CS,
2761 const char *startSpecifier, unsigned specifierLen,
2764 template <typename Range>
2765 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2766 bool IsStringLocation, Range StringRange,
2767 ArrayRef<FixItHint> Fixit = None);
2771 SourceRange CheckFormatHandler::getFormatStringRange() {
2772 return OrigFormatExpr->getSourceRange();
2775 CharSourceRange CheckFormatHandler::
2776 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2777 SourceLocation Start = getLocationOfByte(startSpecifier);
2778 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2780 // Advance the end SourceLocation by one due to half-open ranges.
2781 End = End.getLocWithOffset(1);
2783 return CharSourceRange::getCharRange(Start, End);
2786 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2787 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2790 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2791 unsigned specifierLen){
2792 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2793 getLocationOfByte(startSpecifier),
2794 /*IsStringLocation*/true,
2795 getSpecifierRange(startSpecifier, specifierLen));
2798 void CheckFormatHandler::HandleInvalidLengthModifier(
2799 const analyze_format_string::FormatSpecifier &FS,
2800 const analyze_format_string::ConversionSpecifier &CS,
2801 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2802 using namespace analyze_format_string;
2804 const LengthModifier &LM = FS.getLengthModifier();
2805 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2807 // See if we know how to fix this length modifier.
2808 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2810 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2811 getLocationOfByte(LM.getStart()),
2812 /*IsStringLocation*/true,
2813 getSpecifierRange(startSpecifier, specifierLen));
2815 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2816 << FixedLM->toString()
2817 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2821 if (DiagID == diag::warn_format_nonsensical_length)
2822 Hint = FixItHint::CreateRemoval(LMRange);
2824 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2825 getLocationOfByte(LM.getStart()),
2826 /*IsStringLocation*/true,
2827 getSpecifierRange(startSpecifier, specifierLen),
2832 void CheckFormatHandler::HandleNonStandardLengthModifier(
2833 const analyze_format_string::FormatSpecifier &FS,
2834 const char *startSpecifier, unsigned specifierLen) {
2835 using namespace analyze_format_string;
2837 const LengthModifier &LM = FS.getLengthModifier();
2838 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2840 // See if we know how to fix this length modifier.
2841 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2843 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2844 << LM.toString() << 0,
2845 getLocationOfByte(LM.getStart()),
2846 /*IsStringLocation*/true,
2847 getSpecifierRange(startSpecifier, specifierLen));
2849 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2850 << FixedLM->toString()
2851 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2854 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2855 << LM.toString() << 0,
2856 getLocationOfByte(LM.getStart()),
2857 /*IsStringLocation*/true,
2858 getSpecifierRange(startSpecifier, specifierLen));
2862 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2863 const analyze_format_string::ConversionSpecifier &CS,
2864 const char *startSpecifier, unsigned specifierLen) {
2865 using namespace analyze_format_string;
2867 // See if we know how to fix this conversion specifier.
2868 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2870 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2871 << CS.toString() << /*conversion specifier*/1,
2872 getLocationOfByte(CS.getStart()),
2873 /*IsStringLocation*/true,
2874 getSpecifierRange(startSpecifier, specifierLen));
2876 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2877 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2878 << FixedCS->toString()
2879 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2881 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2882 << CS.toString() << /*conversion specifier*/1,
2883 getLocationOfByte(CS.getStart()),
2884 /*IsStringLocation*/true,
2885 getSpecifierRange(startSpecifier, specifierLen));
2889 void CheckFormatHandler::HandlePosition(const char *startPos,
2891 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2892 getLocationOfByte(startPos),
2893 /*IsStringLocation*/true,
2894 getSpecifierRange(startPos, posLen));
2898 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2899 analyze_format_string::PositionContext p) {
2900 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2902 getLocationOfByte(startPos), /*IsStringLocation*/true,
2903 getSpecifierRange(startPos, posLen));
2906 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2908 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2909 getLocationOfByte(startPos),
2910 /*IsStringLocation*/true,
2911 getSpecifierRange(startPos, posLen));
2914 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2915 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2916 // The presence of a null character is likely an error.
2917 EmitFormatDiagnostic(
2918 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2919 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2920 getFormatStringRange());
2924 // Note that this may return NULL if there was an error parsing or building
2925 // one of the argument expressions.
2926 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2927 return Args[FirstDataArg + i];
2930 void CheckFormatHandler::DoneProcessing() {
2931 // Does the number of data arguments exceed the number of
2932 // format conversions in the format string?
2933 if (!HasVAListArg) {
2934 // Find any arguments that weren't covered.
2936 signed notCoveredArg = CoveredArgs.find_first();
2937 if (notCoveredArg >= 0) {
2938 assert((unsigned)notCoveredArg < NumDataArgs);
2939 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2940 SourceLocation Loc = E->getLocStart();
2941 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2942 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2943 Loc, /*IsStringLocation*/false,
2944 getFormatStringRange());
2952 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2954 const char *startSpec,
2955 unsigned specifierLen,
2956 const char *csStart,
2959 bool keepGoing = true;
2960 if (argIndex < NumDataArgs) {
2961 // Consider the argument coverered, even though the specifier doesn't
2963 CoveredArgs.set(argIndex);
2966 // If argIndex exceeds the number of data arguments we
2967 // don't issue a warning because that is just a cascade of warnings (and
2968 // they may have intended '%%' anyway). We don't want to continue processing
2969 // the format string after this point, however, as we will like just get
2970 // gibberish when trying to match arguments.
2974 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2975 << StringRef(csStart, csLen),
2976 Loc, /*IsStringLocation*/true,
2977 getSpecifierRange(startSpec, specifierLen));
2983 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2984 const char *startSpec,
2985 unsigned specifierLen) {
2986 EmitFormatDiagnostic(
2987 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2988 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2992 CheckFormatHandler::CheckNumArgs(
2993 const analyze_format_string::FormatSpecifier &FS,
2994 const analyze_format_string::ConversionSpecifier &CS,
2995 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2997 if (argIndex >= NumDataArgs) {
2998 PartialDiagnostic PDiag = FS.usesPositionalArg()
2999 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3000 << (argIndex+1) << NumDataArgs)
3001 : S.PDiag(diag::warn_printf_insufficient_data_args);
3002 EmitFormatDiagnostic(
3003 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3004 getSpecifierRange(startSpecifier, specifierLen));
3010 template<typename Range>
3011 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3013 bool IsStringLocation,
3015 ArrayRef<FixItHint> FixIt) {
3016 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
3017 Loc, IsStringLocation, StringRange, FixIt);
3020 /// \brief If the format string is not within the funcion call, emit a note
3021 /// so that the function call and string are in diagnostic messages.
3023 /// \param InFunctionCall if true, the format string is within the function
3024 /// call and only one diagnostic message will be produced. Otherwise, an
3025 /// extra note will be emitted pointing to location of the format string.
3027 /// \param ArgumentExpr the expression that is passed as the format string
3028 /// argument in the function call. Used for getting locations when two
3029 /// diagnostics are emitted.
3031 /// \param PDiag the callee should already have provided any strings for the
3032 /// diagnostic message. This function only adds locations and fixits
3035 /// \param Loc primary location for diagnostic. If two diagnostics are
3036 /// required, one will be at Loc and a new SourceLocation will be created for
3039 /// \param IsStringLocation if true, Loc points to the format string should be
3040 /// used for the note. Otherwise, Loc points to the argument list and will
3041 /// be used with PDiag.
3043 /// \param StringRange some or all of the string to highlight. This is
3044 /// templated so it can accept either a CharSourceRange or a SourceRange.
3046 /// \param FixIt optional fix it hint for the format string.
3047 template<typename Range>
3048 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3049 const Expr *ArgumentExpr,
3050 PartialDiagnostic PDiag,
3052 bool IsStringLocation,
3054 ArrayRef<FixItHint> FixIt) {
3055 if (InFunctionCall) {
3056 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3058 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3063 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3064 << ArgumentExpr->getSourceRange();
3066 const Sema::SemaDiagnosticBuilder &Note =
3067 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3068 diag::note_format_string_defined);
3070 Note << StringRange;
3071 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3078 //===--- CHECK: Printf format string checking ------------------------------===//
3081 class CheckPrintfHandler : public CheckFormatHandler {
3084 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3085 const Expr *origFormatExpr, unsigned firstDataArg,
3086 unsigned numDataArgs, bool isObjC,
3087 const char *beg, bool hasVAListArg,
3088 ArrayRef<const Expr *> Args,
3089 unsigned formatIdx, bool inFunctionCall,
3090 Sema::VariadicCallType CallType,
3091 llvm::SmallBitVector &CheckedVarArgs)
3092 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3093 numDataArgs, beg, hasVAListArg, Args,
3094 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3099 bool HandleInvalidPrintfConversionSpecifier(
3100 const analyze_printf::PrintfSpecifier &FS,
3101 const char *startSpecifier,
3102 unsigned specifierLen) override;
3104 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3105 const char *startSpecifier,
3106 unsigned specifierLen) override;
3107 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3108 const char *StartSpecifier,
3109 unsigned SpecifierLen,
3112 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3113 const char *startSpecifier, unsigned specifierLen);
3114 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3115 const analyze_printf::OptionalAmount &Amt,
3117 const char *startSpecifier, unsigned specifierLen);
3118 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3119 const analyze_printf::OptionalFlag &flag,
3120 const char *startSpecifier, unsigned specifierLen);
3121 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3122 const analyze_printf::OptionalFlag &ignoredFlag,
3123 const analyze_printf::OptionalFlag &flag,
3124 const char *startSpecifier, unsigned specifierLen);
3125 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
3131 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3132 const analyze_printf::PrintfSpecifier &FS,
3133 const char *startSpecifier,
3134 unsigned specifierLen) {
3135 const analyze_printf::PrintfConversionSpecifier &CS =
3136 FS.getConversionSpecifier();
3138 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3139 getLocationOfByte(CS.getStart()),
3140 startSpecifier, specifierLen,
3141 CS.getStart(), CS.getLength());
3144 bool CheckPrintfHandler::HandleAmount(
3145 const analyze_format_string::OptionalAmount &Amt,
3146 unsigned k, const char *startSpecifier,
3147 unsigned specifierLen) {
3149 if (Amt.hasDataArgument()) {
3150 if (!HasVAListArg) {
3151 unsigned argIndex = Amt.getArgIndex();
3152 if (argIndex >= NumDataArgs) {
3153 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3155 getLocationOfByte(Amt.getStart()),
3156 /*IsStringLocation*/true,
3157 getSpecifierRange(startSpecifier, specifierLen));
3158 // Don't do any more checking. We will just emit
3163 // Type check the data argument. It should be an 'int'.
3164 // Although not in conformance with C99, we also allow the argument to be
3165 // an 'unsigned int' as that is a reasonably safe case. GCC also
3166 // doesn't emit a warning for that case.
3167 CoveredArgs.set(argIndex);
3168 const Expr *Arg = getDataArg(argIndex);
3172 QualType T = Arg->getType();
3174 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3175 assert(AT.isValid());
3177 if (!AT.matchesType(S.Context, T)) {
3178 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
3179 << k << AT.getRepresentativeTypeName(S.Context)
3180 << T << Arg->getSourceRange(),
3181 getLocationOfByte(Amt.getStart()),
3182 /*IsStringLocation*/true,
3183 getSpecifierRange(startSpecifier, specifierLen));
3184 // Don't do any more checking. We will just emit
3193 void CheckPrintfHandler::HandleInvalidAmount(
3194 const analyze_printf::PrintfSpecifier &FS,
3195 const analyze_printf::OptionalAmount &Amt,
3197 const char *startSpecifier,
3198 unsigned specifierLen) {
3199 const analyze_printf::PrintfConversionSpecifier &CS =
3200 FS.getConversionSpecifier();
3203 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3204 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3205 Amt.getConstantLength()))
3208 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3209 << type << CS.toString(),
3210 getLocationOfByte(Amt.getStart()),
3211 /*IsStringLocation*/true,
3212 getSpecifierRange(startSpecifier, specifierLen),
3216 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3217 const analyze_printf::OptionalFlag &flag,
3218 const char *startSpecifier,
3219 unsigned specifierLen) {
3220 // Warn about pointless flag with a fixit removal.
3221 const analyze_printf::PrintfConversionSpecifier &CS =
3222 FS.getConversionSpecifier();
3223 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3224 << flag.toString() << CS.toString(),
3225 getLocationOfByte(flag.getPosition()),
3226 /*IsStringLocation*/true,
3227 getSpecifierRange(startSpecifier, specifierLen),
3228 FixItHint::CreateRemoval(
3229 getSpecifierRange(flag.getPosition(), 1)));
3232 void CheckPrintfHandler::HandleIgnoredFlag(
3233 const analyze_printf::PrintfSpecifier &FS,
3234 const analyze_printf::OptionalFlag &ignoredFlag,
3235 const analyze_printf::OptionalFlag &flag,
3236 const char *startSpecifier,
3237 unsigned specifierLen) {
3238 // Warn about ignored flag with a fixit removal.
3239 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3240 << ignoredFlag.toString() << flag.toString(),
3241 getLocationOfByte(ignoredFlag.getPosition()),
3242 /*IsStringLocation*/true,
3243 getSpecifierRange(startSpecifier, specifierLen),
3244 FixItHint::CreateRemoval(
3245 getSpecifierRange(ignoredFlag.getPosition(), 1)));
3248 // Determines if the specified is a C++ class or struct containing
3249 // a member with the specified name and kind (e.g. a CXXMethodDecl named
3251 template<typename MemberKind>
3252 static llvm::SmallPtrSet<MemberKind*, 1>
3253 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3254 const RecordType *RT = Ty->getAs<RecordType>();
3255 llvm::SmallPtrSet<MemberKind*, 1> Results;
3259 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3260 if (!RD || !RD->getDefinition())
3263 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
3264 Sema::LookupMemberName);
3265 R.suppressDiagnostics();
3267 // We just need to include all members of the right kind turned up by the
3268 // filter, at this point.
3269 if (S.LookupQualifiedName(R, RT->getDecl()))
3270 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3271 NamedDecl *decl = (*I)->getUnderlyingDecl();
3272 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3278 /// Check if we could call '.c_str()' on an object.
3280 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3281 /// allow the call, or if it would be ambiguous).
3282 bool Sema::hasCStrMethod(const Expr *E) {
3283 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3285 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3286 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3288 if ((*MI)->getMinRequiredArguments() == 0)
3293 // Check if a (w)string was passed when a (w)char* was needed, and offer a
3294 // better diagnostic if so. AT is assumed to be valid.
3295 // Returns true when a c_str() conversion method is found.
3296 bool CheckPrintfHandler::checkForCStrMembers(
3297 const analyze_printf::ArgType &AT, const Expr *E) {
3298 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3301 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3303 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3305 const CXXMethodDecl *Method = *MI;
3306 if (Method->getMinRequiredArguments() == 0 &&
3307 AT.matchesType(S.Context, Method->getReturnType())) {
3308 // FIXME: Suggest parens if the expression needs them.
3309 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
3310 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3312 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3321 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
3323 const char *startSpecifier,
3324 unsigned specifierLen) {
3326 using namespace analyze_format_string;
3327 using namespace analyze_printf;
3328 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
3330 if (FS.consumesDataArgument()) {
3333 usesPositionalArgs = FS.usesPositionalArg();
3335 else if (usesPositionalArgs != FS.usesPositionalArg()) {
3336 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3337 startSpecifier, specifierLen);
3342 // First check if the field width, precision, and conversion specifier
3343 // have matching data arguments.
3344 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3345 startSpecifier, specifierLen)) {
3349 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3350 startSpecifier, specifierLen)) {
3354 if (!CS.consumesDataArgument()) {
3355 // FIXME: Technically specifying a precision or field width here
3356 // makes no sense. Worth issuing a warning at some point.
3360 // Consume the argument.
3361 unsigned argIndex = FS.getArgIndex();
3362 if (argIndex < NumDataArgs) {
3363 // The check to see if the argIndex is valid will come later.
3364 // We set the bit here because we may exit early from this
3365 // function if we encounter some other error.
3366 CoveredArgs.set(argIndex);
3369 // FreeBSD kernel extensions.
3370 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3371 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3372 // We need at least two arguments.
3373 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3376 // Claim the second argument.
3377 CoveredArgs.set(argIndex + 1);
3379 // Type check the first argument (int for %b, pointer for %D)
3380 const Expr *Ex = getDataArg(argIndex);
3381 const analyze_printf::ArgType &AT =
3382 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3383 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3384 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3385 EmitFormatDiagnostic(
3386 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3387 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3388 << false << Ex->getSourceRange(),
3389 Ex->getLocStart(), /*IsStringLocation*/false,
3390 getSpecifierRange(startSpecifier, specifierLen));
3392 // Type check the second argument (char * for both %b and %D)
3393 Ex = getDataArg(argIndex + 1);
3394 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3395 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3396 EmitFormatDiagnostic(
3397 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3398 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3399 << false << Ex->getSourceRange(),
3400 Ex->getLocStart(), /*IsStringLocation*/false,
3401 getSpecifierRange(startSpecifier, specifierLen));
3406 // Check for using an Objective-C specific conversion specifier
3407 // in a non-ObjC literal.
3408 if (!ObjCContext && CS.isObjCArg()) {
3409 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3413 // Check for invalid use of field width
3414 if (!FS.hasValidFieldWidth()) {
3415 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3416 startSpecifier, specifierLen);
3419 // Check for invalid use of precision
3420 if (!FS.hasValidPrecision()) {
3421 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3422 startSpecifier, specifierLen);
3425 // Check each flag does not conflict with any other component.
3426 if (!FS.hasValidThousandsGroupingPrefix())
3427 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3428 if (!FS.hasValidLeadingZeros())
3429 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3430 if (!FS.hasValidPlusPrefix())
3431 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3432 if (!FS.hasValidSpacePrefix())
3433 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3434 if (!FS.hasValidAlternativeForm())
3435 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3436 if (!FS.hasValidLeftJustified())
3437 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3439 // Check that flags are not ignored by another flag
3440 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3441 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3442 startSpecifier, specifierLen);
3443 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3444 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3445 startSpecifier, specifierLen);
3447 // Check the length modifier is valid with the given conversion specifier.
3448 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3449 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3450 diag::warn_format_nonsensical_length);
3451 else if (!FS.hasStandardLengthModifier())
3452 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3453 else if (!FS.hasStandardLengthConversionCombination())
3454 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3455 diag::warn_format_non_standard_conversion_spec);
3457 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3458 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3460 // The remaining checks depend on the data arguments.
3464 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3467 const Expr *Arg = getDataArg(argIndex);
3471 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3474 static bool requiresParensToAddCast(const Expr *E) {
3475 // FIXME: We should have a general way to reason about operator
3476 // precedence and whether parens are actually needed here.
3477 // Take care of a few common cases where they aren't.
3478 const Expr *Inside = E->IgnoreImpCasts();
3479 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3480 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3482 switch (Inside->getStmtClass()) {
3483 case Stmt::ArraySubscriptExprClass:
3484 case Stmt::CallExprClass:
3485 case Stmt::CharacterLiteralClass:
3486 case Stmt::CXXBoolLiteralExprClass:
3487 case Stmt::DeclRefExprClass:
3488 case Stmt::FloatingLiteralClass:
3489 case Stmt::IntegerLiteralClass:
3490 case Stmt::MemberExprClass:
3491 case Stmt::ObjCArrayLiteralClass:
3492 case Stmt::ObjCBoolLiteralExprClass:
3493 case Stmt::ObjCBoxedExprClass:
3494 case Stmt::ObjCDictionaryLiteralClass:
3495 case Stmt::ObjCEncodeExprClass:
3496 case Stmt::ObjCIvarRefExprClass:
3497 case Stmt::ObjCMessageExprClass:
3498 case Stmt::ObjCPropertyRefExprClass:
3499 case Stmt::ObjCStringLiteralClass:
3500 case Stmt::ObjCSubscriptRefExprClass:
3501 case Stmt::ParenExprClass:
3502 case Stmt::StringLiteralClass:
3503 case Stmt::UnaryOperatorClass:
3510 static std::pair<QualType, StringRef>
3511 shouldNotPrintDirectly(const ASTContext &Context,
3512 QualType IntendedTy,
3514 // Use a 'while' to peel off layers of typedefs.
3515 QualType TyTy = IntendedTy;
3516 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3517 StringRef Name = UserTy->getDecl()->getName();
3518 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3519 .Case("NSInteger", Context.LongTy)
3520 .Case("NSUInteger", Context.UnsignedLongTy)
3521 .Case("SInt32", Context.IntTy)
3522 .Case("UInt32", Context.UnsignedIntTy)
3523 .Default(QualType());
3525 if (!CastTy.isNull())
3526 return std::make_pair(CastTy, Name);
3528 TyTy = UserTy->desugar();
3531 // Strip parens if necessary.
3532 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3533 return shouldNotPrintDirectly(Context,
3534 PE->getSubExpr()->getType(),
3537 // If this is a conditional expression, then its result type is constructed
3538 // via usual arithmetic conversions and thus there might be no necessary
3539 // typedef sugar there. Recurse to operands to check for NSInteger &
3540 // Co. usage condition.
3541 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3542 QualType TrueTy, FalseTy;
3543 StringRef TrueName, FalseName;
3545 std::tie(TrueTy, TrueName) =
3546 shouldNotPrintDirectly(Context,
3547 CO->getTrueExpr()->getType(),
3549 std::tie(FalseTy, FalseName) =
3550 shouldNotPrintDirectly(Context,
3551 CO->getFalseExpr()->getType(),
3552 CO->getFalseExpr());
3554 if (TrueTy == FalseTy)
3555 return std::make_pair(TrueTy, TrueName);
3556 else if (TrueTy.isNull())
3557 return std::make_pair(FalseTy, FalseName);
3558 else if (FalseTy.isNull())
3559 return std::make_pair(TrueTy, TrueName);
3562 return std::make_pair(QualType(), StringRef());
3566 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3567 const char *StartSpecifier,
3568 unsigned SpecifierLen,
3570 using namespace analyze_format_string;
3571 using namespace analyze_printf;
3572 // Now type check the data expression that matches the
3573 // format specifier.
3574 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3579 QualType ExprTy = E->getType();
3580 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3581 ExprTy = TET->getUnderlyingExpr()->getType();
3584 if (AT.matchesType(S.Context, ExprTy))
3587 // Look through argument promotions for our error message's reported type.
3588 // This includes the integral and floating promotions, but excludes array
3589 // and function pointer decay; seeing that an argument intended to be a
3590 // string has type 'char [6]' is probably more confusing than 'char *'.
3591 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3592 if (ICE->getCastKind() == CK_IntegralCast ||
3593 ICE->getCastKind() == CK_FloatingCast) {
3594 E = ICE->getSubExpr();
3595 ExprTy = E->getType();
3597 // Check if we didn't match because of an implicit cast from a 'char'
3598 // or 'short' to an 'int'. This is done because printf is a varargs
3600 if (ICE->getType() == S.Context.IntTy ||
3601 ICE->getType() == S.Context.UnsignedIntTy) {
3602 // All further checking is done on the subexpression.
3603 if (AT.matchesType(S.Context, ExprTy))
3607 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3608 // Special case for 'a', which has type 'int' in C.
3609 // Note, however, that we do /not/ want to treat multibyte constants like
3610 // 'MooV' as characters! This form is deprecated but still exists.
3611 if (ExprTy == S.Context.IntTy)
3612 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3613 ExprTy = S.Context.CharTy;
3616 // Look through enums to their underlying type.
3617 bool IsEnum = false;
3618 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3619 ExprTy = EnumTy->getDecl()->getIntegerType();
3623 // %C in an Objective-C context prints a unichar, not a wchar_t.
3624 // If the argument is an integer of some kind, believe the %C and suggest
3625 // a cast instead of changing the conversion specifier.
3626 QualType IntendedTy = ExprTy;
3628 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3629 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3630 !ExprTy->isCharType()) {
3631 // 'unichar' is defined as a typedef of unsigned short, but we should
3632 // prefer using the typedef if it is visible.
3633 IntendedTy = S.Context.UnsignedShortTy;
3635 // While we are here, check if the value is an IntegerLiteral that happens
3636 // to be within the valid range.
3637 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3638 const llvm::APInt &V = IL->getValue();
3639 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3643 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3644 Sema::LookupOrdinaryName);
3645 if (S.LookupName(Result, S.getCurScope())) {
3646 NamedDecl *ND = Result.getFoundDecl();
3647 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3648 if (TD->getUnderlyingType() == IntendedTy)
3649 IntendedTy = S.Context.getTypedefType(TD);
3654 // Special-case some of Darwin's platform-independence types by suggesting
3655 // casts to primitive types that are known to be large enough.
3656 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
3657 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3659 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3660 if (!CastTy.isNull()) {
3661 IntendedTy = CastTy;
3662 ShouldNotPrintDirectly = true;
3666 // We may be able to offer a FixItHint if it is a supported type.
3667 PrintfSpecifier fixedFS = FS;
3668 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3669 S.Context, ObjCContext);
3672 // Get the fix string from the fixed format specifier
3673 SmallString<16> buf;
3674 llvm::raw_svector_ostream os(buf);
3675 fixedFS.toString(os);
3677 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3679 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
3680 // In this case, the specifier is wrong and should be changed to match
3682 EmitFormatDiagnostic(
3683 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3684 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
3685 << E->getSourceRange(),
3687 /*IsStringLocation*/false,
3689 FixItHint::CreateReplacement(SpecRange, os.str()));
3692 // The canonical type for formatting this value is different from the
3693 // actual type of the expression. (This occurs, for example, with Darwin's
3694 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3695 // should be printed as 'long' for 64-bit compatibility.)
3696 // Rather than emitting a normal format/argument mismatch, we want to
3697 // add a cast to the recommended type (and correct the format string
3699 SmallString<16> CastBuf;
3700 llvm::raw_svector_ostream CastFix(CastBuf);
3702 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3705 SmallVector<FixItHint,4> Hints;
3706 if (!AT.matchesType(S.Context, IntendedTy))
3707 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3709 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3710 // If there's already a cast present, just replace it.
3711 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3712 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3714 } else if (!requiresParensToAddCast(E)) {
3715 // If the expression has high enough precedence,
3716 // just write the C-style cast.
3717 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3720 // Otherwise, add parens around the expression as well as the cast.
3722 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3725 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
3726 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3729 if (ShouldNotPrintDirectly) {
3730 // The expression has a type that should not be printed directly.
3731 // We extract the name from the typedef because we don't want to show
3732 // the underlying type in the diagnostic.
3734 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3735 Name = TypedefTy->getDecl()->getName();
3738 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3739 << Name << IntendedTy << IsEnum
3740 << E->getSourceRange(),
3741 E->getLocStart(), /*IsStringLocation=*/false,
3744 // In this case, the expression could be printed using a different
3745 // specifier, but we've decided that the specifier is probably correct
3746 // and we should cast instead. Just use the normal warning message.
3747 EmitFormatDiagnostic(
3748 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3749 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3750 << E->getSourceRange(),
3751 E->getLocStart(), /*IsStringLocation*/false,
3756 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3758 // Since the warning for passing non-POD types to variadic functions
3759 // was deferred until now, we emit a warning for non-POD
3761 switch (S.isValidVarArgType(ExprTy)) {
3762 case Sema::VAK_Valid:
3763 case Sema::VAK_ValidInCXX11:
3764 EmitFormatDiagnostic(
3765 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3766 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3768 << E->getSourceRange(),
3769 E->getLocStart(), /*IsStringLocation*/false, CSR);
3772 case Sema::VAK_Undefined:
3773 case Sema::VAK_MSVCUndefined:
3774 EmitFormatDiagnostic(
3775 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3776 << S.getLangOpts().CPlusPlus11
3779 << AT.getRepresentativeTypeName(S.Context)
3781 << E->getSourceRange(),
3782 E->getLocStart(), /*IsStringLocation*/false, CSR);
3783 checkForCStrMembers(AT, E);
3786 case Sema::VAK_Invalid:
3787 if (ExprTy->isObjCObjectType())
3788 EmitFormatDiagnostic(
3789 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3790 << S.getLangOpts().CPlusPlus11
3793 << AT.getRepresentativeTypeName(S.Context)
3795 << E->getSourceRange(),
3796 E->getLocStart(), /*IsStringLocation*/false, CSR);
3798 // FIXME: If this is an initializer list, suggest removing the braces
3799 // or inserting a cast to the target type.
3800 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3801 << isa<InitListExpr>(E) << ExprTy << CallType
3802 << AT.getRepresentativeTypeName(S.Context)
3803 << E->getSourceRange();
3807 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3808 "format string specifier index out of range");
3809 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3815 //===--- CHECK: Scanf format string checking ------------------------------===//
3818 class CheckScanfHandler : public CheckFormatHandler {
3820 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3821 const Expr *origFormatExpr, unsigned firstDataArg,
3822 unsigned numDataArgs, const char *beg, bool hasVAListArg,
3823 ArrayRef<const Expr *> Args,
3824 unsigned formatIdx, bool inFunctionCall,
3825 Sema::VariadicCallType CallType,
3826 llvm::SmallBitVector &CheckedVarArgs)
3827 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3828 numDataArgs, beg, hasVAListArg,
3829 Args, formatIdx, inFunctionCall, CallType,
3833 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3834 const char *startSpecifier,
3835 unsigned specifierLen) override;
3837 bool HandleInvalidScanfConversionSpecifier(
3838 const analyze_scanf::ScanfSpecifier &FS,
3839 const char *startSpecifier,
3840 unsigned specifierLen) override;
3842 void HandleIncompleteScanList(const char *start, const char *end) override;
3846 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3848 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3849 getLocationOfByte(end), /*IsStringLocation*/true,
3850 getSpecifierRange(start, end - start));
3853 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3854 const analyze_scanf::ScanfSpecifier &FS,
3855 const char *startSpecifier,
3856 unsigned specifierLen) {
3858 const analyze_scanf::ScanfConversionSpecifier &CS =
3859 FS.getConversionSpecifier();
3861 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3862 getLocationOfByte(CS.getStart()),
3863 startSpecifier, specifierLen,
3864 CS.getStart(), CS.getLength());
3867 bool CheckScanfHandler::HandleScanfSpecifier(
3868 const analyze_scanf::ScanfSpecifier &FS,
3869 const char *startSpecifier,
3870 unsigned specifierLen) {
3872 using namespace analyze_scanf;
3873 using namespace analyze_format_string;
3875 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3877 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3878 // be used to decide if we are using positional arguments consistently.
3879 if (FS.consumesDataArgument()) {
3882 usesPositionalArgs = FS.usesPositionalArg();
3884 else if (usesPositionalArgs != FS.usesPositionalArg()) {
3885 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3886 startSpecifier, specifierLen);
3891 // Check if the field with is non-zero.
3892 const OptionalAmount &Amt = FS.getFieldWidth();
3893 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3894 if (Amt.getConstantAmount() == 0) {
3895 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3896 Amt.getConstantLength());
3897 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3898 getLocationOfByte(Amt.getStart()),
3899 /*IsStringLocation*/true, R,
3900 FixItHint::CreateRemoval(R));
3904 if (!FS.consumesDataArgument()) {
3905 // FIXME: Technically specifying a precision or field width here
3906 // makes no sense. Worth issuing a warning at some point.
3910 // Consume the argument.
3911 unsigned argIndex = FS.getArgIndex();
3912 if (argIndex < NumDataArgs) {
3913 // The check to see if the argIndex is valid will come later.
3914 // We set the bit here because we may exit early from this
3915 // function if we encounter some other error.
3916 CoveredArgs.set(argIndex);
3919 // Check the length modifier is valid with the given conversion specifier.
3920 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3921 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3922 diag::warn_format_nonsensical_length);
3923 else if (!FS.hasStandardLengthModifier())
3924 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3925 else if (!FS.hasStandardLengthConversionCombination())
3926 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3927 diag::warn_format_non_standard_conversion_spec);
3929 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3930 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3932 // The remaining checks depend on the data arguments.
3936 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3939 // Check that the argument type matches the format specifier.
3940 const Expr *Ex = getDataArg(argIndex);
3944 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3945 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3946 ScanfSpecifier fixedFS = FS;
3947 bool success = fixedFS.fixType(Ex->getType(),
3948 Ex->IgnoreImpCasts()->getType(),
3949 S.getLangOpts(), S.Context);
3952 // Get the fix string from the fixed format specifier.
3953 SmallString<128> buf;
3954 llvm::raw_svector_ostream os(buf);
3955 fixedFS.toString(os);
3957 EmitFormatDiagnostic(
3958 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3959 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
3960 << Ex->getSourceRange(),
3962 /*IsStringLocation*/false,
3963 getSpecifierRange(startSpecifier, specifierLen),
3964 FixItHint::CreateReplacement(
3965 getSpecifierRange(startSpecifier, specifierLen),
3968 EmitFormatDiagnostic(
3969 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3970 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
3971 << Ex->getSourceRange(),
3973 /*IsStringLocation*/false,
3974 getSpecifierRange(startSpecifier, specifierLen));
3981 void Sema::CheckFormatString(const StringLiteral *FExpr,
3982 const Expr *OrigFormatExpr,
3983 ArrayRef<const Expr *> Args,
3984 bool HasVAListArg, unsigned format_idx,
3985 unsigned firstDataArg, FormatStringType Type,
3986 bool inFunctionCall, VariadicCallType CallType,
3987 llvm::SmallBitVector &CheckedVarArgs) {
3989 // CHECK: is the format string a wide literal?
3990 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3991 CheckFormatHandler::EmitFormatDiagnostic(
3992 *this, inFunctionCall, Args[format_idx],
3993 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3994 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3998 // Str - The format string. NOTE: this is NOT null-terminated!
3999 StringRef StrRef = FExpr->getString();
4000 const char *Str = StrRef.data();
4001 // Account for cases where the string literal is truncated in a declaration.
4002 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4003 assert(T && "String literal not of constant array type!");
4004 size_t TypeSize = T->getSize().getZExtValue();
4005 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4006 const unsigned numDataArgs = Args.size() - firstDataArg;
4008 // Emit a warning if the string literal is truncated and does not contain an
4009 // embedded null character.
4010 if (TypeSize <= StrRef.size() &&
4011 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4012 CheckFormatHandler::EmitFormatDiagnostic(
4013 *this, inFunctionCall, Args[format_idx],
4014 PDiag(diag::warn_printf_format_string_not_null_terminated),
4015 FExpr->getLocStart(),
4016 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4020 // CHECK: empty format string?
4021 if (StrLen == 0 && numDataArgs > 0) {
4022 CheckFormatHandler::EmitFormatDiagnostic(
4023 *this, inFunctionCall, Args[format_idx],
4024 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4025 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4029 if (Type == FST_Printf || Type == FST_NSString ||
4030 Type == FST_FreeBSDKPrintf) {
4031 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
4032 numDataArgs, (Type == FST_NSString),
4033 Str, HasVAListArg, Args, format_idx,
4034 inFunctionCall, CallType, CheckedVarArgs);
4036 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
4038 Context.getTargetInfo(),
4039 Type == FST_FreeBSDKPrintf))
4041 } else if (Type == FST_Scanf) {
4042 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
4043 Str, HasVAListArg, Args, format_idx,
4044 inFunctionCall, CallType, CheckedVarArgs);
4046 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
4048 Context.getTargetInfo()))
4050 } // TODO: handle other formats
4053 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4054 // Str - The format string. NOTE: this is NOT null-terminated!
4055 StringRef StrRef = FExpr->getString();
4056 const char *Str = StrRef.data();
4057 // Account for cases where the string literal is truncated in a declaration.
4058 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4059 assert(T && "String literal not of constant array type!");
4060 size_t TypeSize = T->getSize().getZExtValue();
4061 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4062 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4064 Context.getTargetInfo());
4067 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4069 // Returns the related absolute value function that is larger, of 0 if one
4071 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4072 switch (AbsFunction) {
4076 case Builtin::BI__builtin_abs:
4077 return Builtin::BI__builtin_labs;
4078 case Builtin::BI__builtin_labs:
4079 return Builtin::BI__builtin_llabs;
4080 case Builtin::BI__builtin_llabs:
4083 case Builtin::BI__builtin_fabsf:
4084 return Builtin::BI__builtin_fabs;
4085 case Builtin::BI__builtin_fabs:
4086 return Builtin::BI__builtin_fabsl;
4087 case Builtin::BI__builtin_fabsl:
4090 case Builtin::BI__builtin_cabsf:
4091 return Builtin::BI__builtin_cabs;
4092 case Builtin::BI__builtin_cabs:
4093 return Builtin::BI__builtin_cabsl;
4094 case Builtin::BI__builtin_cabsl:
4097 case Builtin::BIabs:
4098 return Builtin::BIlabs;
4099 case Builtin::BIlabs:
4100 return Builtin::BIllabs;
4101 case Builtin::BIllabs:
4104 case Builtin::BIfabsf:
4105 return Builtin::BIfabs;
4106 case Builtin::BIfabs:
4107 return Builtin::BIfabsl;
4108 case Builtin::BIfabsl:
4111 case Builtin::BIcabsf:
4112 return Builtin::BIcabs;
4113 case Builtin::BIcabs:
4114 return Builtin::BIcabsl;
4115 case Builtin::BIcabsl:
4120 // Returns the argument type of the absolute value function.
4121 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4126 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4127 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4128 if (Error != ASTContext::GE_None)
4131 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4135 if (FT->getNumParams() != 1)
4138 return FT->getParamType(0);
4141 // Returns the best absolute value function, or zero, based on type and
4142 // current absolute value function.
4143 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4144 unsigned AbsFunctionKind) {
4145 unsigned BestKind = 0;
4146 uint64_t ArgSize = Context.getTypeSize(ArgType);
4147 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4148 Kind = getLargerAbsoluteValueFunction(Kind)) {
4149 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4150 if (Context.getTypeSize(ParamType) >= ArgSize) {
4153 else if (Context.hasSameType(ParamType, ArgType)) {
4162 enum AbsoluteValueKind {
4168 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4169 if (T->isIntegralOrEnumerationType())
4171 if (T->isRealFloatingType())
4172 return AVK_Floating;
4173 if (T->isAnyComplexType())
4176 llvm_unreachable("Type not integer, floating, or complex");
4179 // Changes the absolute value function to a different type. Preserves whether
4180 // the function is a builtin.
4181 static unsigned changeAbsFunction(unsigned AbsKind,
4182 AbsoluteValueKind ValueKind) {
4183 switch (ValueKind) {
4188 case Builtin::BI__builtin_fabsf:
4189 case Builtin::BI__builtin_fabs:
4190 case Builtin::BI__builtin_fabsl:
4191 case Builtin::BI__builtin_cabsf:
4192 case Builtin::BI__builtin_cabs:
4193 case Builtin::BI__builtin_cabsl:
4194 return Builtin::BI__builtin_abs;
4195 case Builtin::BIfabsf:
4196 case Builtin::BIfabs:
4197 case Builtin::BIfabsl:
4198 case Builtin::BIcabsf:
4199 case Builtin::BIcabs:
4200 case Builtin::BIcabsl:
4201 return Builtin::BIabs;
4207 case Builtin::BI__builtin_abs:
4208 case Builtin::BI__builtin_labs:
4209 case Builtin::BI__builtin_llabs:
4210 case Builtin::BI__builtin_cabsf:
4211 case Builtin::BI__builtin_cabs:
4212 case Builtin::BI__builtin_cabsl:
4213 return Builtin::BI__builtin_fabsf;
4214 case Builtin::BIabs:
4215 case Builtin::BIlabs:
4216 case Builtin::BIllabs:
4217 case Builtin::BIcabsf:
4218 case Builtin::BIcabs:
4219 case Builtin::BIcabsl:
4220 return Builtin::BIfabsf;
4226 case Builtin::BI__builtin_abs:
4227 case Builtin::BI__builtin_labs:
4228 case Builtin::BI__builtin_llabs:
4229 case Builtin::BI__builtin_fabsf:
4230 case Builtin::BI__builtin_fabs:
4231 case Builtin::BI__builtin_fabsl:
4232 return Builtin::BI__builtin_cabsf;
4233 case Builtin::BIabs:
4234 case Builtin::BIlabs:
4235 case Builtin::BIllabs:
4236 case Builtin::BIfabsf:
4237 case Builtin::BIfabs:
4238 case Builtin::BIfabsl:
4239 return Builtin::BIcabsf;
4242 llvm_unreachable("Unable to convert function");
4245 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4246 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4250 switch (FDecl->getBuiltinID()) {
4253 case Builtin::BI__builtin_abs:
4254 case Builtin::BI__builtin_fabs:
4255 case Builtin::BI__builtin_fabsf:
4256 case Builtin::BI__builtin_fabsl:
4257 case Builtin::BI__builtin_labs:
4258 case Builtin::BI__builtin_llabs:
4259 case Builtin::BI__builtin_cabs:
4260 case Builtin::BI__builtin_cabsf:
4261 case Builtin::BI__builtin_cabsl:
4262 case Builtin::BIabs:
4263 case Builtin::BIlabs:
4264 case Builtin::BIllabs:
4265 case Builtin::BIfabs:
4266 case Builtin::BIfabsf:
4267 case Builtin::BIfabsl:
4268 case Builtin::BIcabs:
4269 case Builtin::BIcabsf:
4270 case Builtin::BIcabsl:
4271 return FDecl->getBuiltinID();
4273 llvm_unreachable("Unknown Builtin type");
4276 // If the replacement is valid, emit a note with replacement function.
4277 // Additionally, suggest including the proper header if not already included.
4278 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
4279 unsigned AbsKind, QualType ArgType) {
4280 bool EmitHeaderHint = true;
4281 const char *HeaderName = nullptr;
4282 const char *FunctionName = nullptr;
4283 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4284 FunctionName = "std::abs";
4285 if (ArgType->isIntegralOrEnumerationType()) {
4286 HeaderName = "cstdlib";
4287 } else if (ArgType->isRealFloatingType()) {
4288 HeaderName = "cmath";
4290 llvm_unreachable("Invalid Type");
4293 // Lookup all std::abs
4294 if (NamespaceDecl *Std = S.getStdNamespace()) {
4295 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4296 R.suppressDiagnostics();
4297 S.LookupQualifiedName(R, Std);
4299 for (const auto *I : R) {
4300 const FunctionDecl *FDecl = nullptr;
4301 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4302 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4304 FDecl = dyn_cast<FunctionDecl>(I);
4309 // Found std::abs(), check that they are the right ones.
4310 if (FDecl->getNumParams() != 1)
4313 // Check that the parameter type can handle the argument.
4314 QualType ParamType = FDecl->getParamDecl(0)->getType();
4315 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4316 S.Context.getTypeSize(ArgType) <=
4317 S.Context.getTypeSize(ParamType)) {
4318 // Found a function, don't need the header hint.
4319 EmitHeaderHint = false;
4325 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4326 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4329 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4330 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4331 R.suppressDiagnostics();
4332 S.LookupName(R, S.getCurScope());
4334 if (R.isSingleResult()) {
4335 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4336 if (FD && FD->getBuiltinID() == AbsKind) {
4337 EmitHeaderHint = false;
4341 } else if (!R.empty()) {
4347 S.Diag(Loc, diag::note_replace_abs_function)
4348 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
4353 if (!EmitHeaderHint)
4356 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4360 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4364 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4367 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4369 while (ND && ND->isInlineNamespace()) {
4370 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
4373 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4376 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4382 // Warn when using the wrong abs() function.
4383 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4384 const FunctionDecl *FDecl,
4385 IdentifierInfo *FnInfo) {
4386 if (Call->getNumArgs() != 1)
4389 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
4390 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4391 if (AbsKind == 0 && !IsStdAbs)
4394 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4395 QualType ParamType = Call->getArg(0)->getType();
4397 // Unsigned types cannot be negative. Suggest removing the absolute value
4399 if (ArgType->isUnsignedIntegerType()) {
4400 const char *FunctionName =
4401 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
4402 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4403 Diag(Call->getExprLoc(), diag::note_remove_abs)
4405 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4409 // std::abs has overloads which prevent most of the absolute value problems
4414 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4415 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4417 // The argument and parameter are the same kind. Check if they are the right
4419 if (ArgValueKind == ParamValueKind) {
4420 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4423 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4424 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4425 << FDecl << ArgType << ParamType;
4427 if (NewAbsKind == 0)
4430 emitReplacement(*this, Call->getExprLoc(),
4431 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4435 // ArgValueKind != ParamValueKind
4436 // The wrong type of absolute value function was used. Attempt to find the
4438 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4439 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4440 if (NewAbsKind == 0)
4443 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4444 << FDecl << ParamValueKind << ArgValueKind;
4446 emitReplacement(*this, Call->getExprLoc(),
4447 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4451 //===--- CHECK: Standard memory functions ---------------------------------===//
4453 /// \brief Takes the expression passed to the size_t parameter of functions
4454 /// such as memcmp, strncat, etc and warns if it's a comparison.
4456 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4457 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4458 IdentifierInfo *FnName,
4459 SourceLocation FnLoc,
4460 SourceLocation RParenLoc) {
4461 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4465 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4466 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4469 SourceRange SizeRange = Size->getSourceRange();
4470 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4471 << SizeRange << FnName;
4472 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4473 << FnName << FixItHint::CreateInsertion(
4474 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
4475 << FixItHint::CreateRemoval(RParenLoc);
4476 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
4477 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
4478 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4484 /// \brief Determine whether the given type is or contains a dynamic class type
4485 /// (e.g., whether it has a vtable).
4486 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4487 bool &IsContained) {
4488 // Look through array types while ignoring qualifiers.
4489 const Type *Ty = T->getBaseElementTypeUnsafe();
4490 IsContained = false;
4492 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4493 RD = RD ? RD->getDefinition() : nullptr;
4497 if (RD->isDynamicClass())
4500 // Check all the fields. If any bases were dynamic, the class is dynamic.
4501 // It's impossible for a class to transitively contain itself by value, so
4502 // infinite recursion is impossible.
4503 for (auto *FD : RD->fields()) {
4505 if (const CXXRecordDecl *ContainedRD =
4506 getContainedDynamicClass(FD->getType(), SubContained)) {
4515 /// \brief If E is a sizeof expression, returns its argument expression,
4516 /// otherwise returns NULL.
4517 static const Expr *getSizeOfExprArg(const Expr* E) {
4518 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4519 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4520 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4521 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
4526 /// \brief If E is a sizeof expression, returns its argument type.
4527 static QualType getSizeOfArgType(const Expr* E) {
4528 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4529 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4530 if (SizeOf->getKind() == clang::UETT_SizeOf)
4531 return SizeOf->getTypeOfArgument();
4536 /// \brief Check for dangerous or invalid arguments to memset().
4538 /// This issues warnings on known problematic, dangerous or unspecified
4539 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4542 /// \param Call The call expression to diagnose.
4543 void Sema::CheckMemaccessArguments(const CallExpr *Call,
4545 IdentifierInfo *FnName) {
4548 // It is possible to have a non-standard definition of memset. Validate
4549 // we have enough arguments, and if not, abort further checking.
4550 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4551 if (Call->getNumArgs() < ExpectedNumArgs)
4554 unsigned LastArg = (BId == Builtin::BImemset ||
4555 BId == Builtin::BIstrndup ? 1 : 2);
4556 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
4557 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4559 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4560 Call->getLocStart(), Call->getRParenLoc()))
4563 // We have special checking when the length is a sizeof expression.
4564 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4565 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4566 llvm::FoldingSetNodeID SizeOfArgID;
4568 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4569 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4570 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4572 QualType DestTy = Dest->getType();
4573 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4574 QualType PointeeTy = DestPtrTy->getPointeeType();
4576 // Never warn about void type pointers. This can be used to suppress
4578 if (PointeeTy->isVoidType())
4581 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4582 // actually comparing the expressions for equality. Because computing the
4583 // expression IDs can be expensive, we only do this if the diagnostic is
4586 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4587 SizeOfArg->getExprLoc())) {
4588 // We only compute IDs for expressions if the warning is enabled, and
4589 // cache the sizeof arg's ID.
4590 if (SizeOfArgID == llvm::FoldingSetNodeID())
4591 SizeOfArg->Profile(SizeOfArgID, Context, true);
4592 llvm::FoldingSetNodeID DestID;
4593 Dest->Profile(DestID, Context, true);
4594 if (DestID == SizeOfArgID) {
4595 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4596 // over sizeof(src) as well.
4597 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4598 StringRef ReadableName = FnName->getName();
4600 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4601 if (UnaryOp->getOpcode() == UO_AddrOf)
4602 ActionIdx = 1; // If its an address-of operator, just remove it.
4603 if (!PointeeTy->isIncompleteType() &&
4604 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4605 ActionIdx = 2; // If the pointee's size is sizeof(char),
4606 // suggest an explicit length.
4608 // If the function is defined as a builtin macro, do not show macro
4610 SourceLocation SL = SizeOfArg->getExprLoc();
4611 SourceRange DSR = Dest->getSourceRange();
4612 SourceRange SSR = SizeOfArg->getSourceRange();
4613 SourceManager &SM = getSourceManager();
4615 if (SM.isMacroArgExpansion(SL)) {
4616 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4617 SL = SM.getSpellingLoc(SL);
4618 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4619 SM.getSpellingLoc(DSR.getEnd()));
4620 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4621 SM.getSpellingLoc(SSR.getEnd()));
4624 DiagRuntimeBehavior(SL, SizeOfArg,
4625 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4631 DiagRuntimeBehavior(SL, SizeOfArg,
4632 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4640 // Also check for cases where the sizeof argument is the exact same
4641 // type as the memory argument, and where it points to a user-defined
4643 if (SizeOfArgTy != QualType()) {
4644 if (PointeeTy->isRecordType() &&
4645 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4646 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4647 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4648 << FnName << SizeOfArgTy << ArgIdx
4649 << PointeeTy << Dest->getSourceRange()
4650 << LenExpr->getSourceRange());
4655 // Always complain about dynamic classes.
4657 if (const CXXRecordDecl *ContainedRD =
4658 getContainedDynamicClass(PointeeTy, IsContained)) {
4660 unsigned OperationType = 0;
4661 // "overwritten" if we're warning about the destination for any call
4662 // but memcmp; otherwise a verb appropriate to the call.
4663 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4664 if (BId == Builtin::BImemcpy)
4666 else if(BId == Builtin::BImemmove)
4668 else if (BId == Builtin::BImemcmp)
4672 DiagRuntimeBehavior(
4673 Dest->getExprLoc(), Dest,
4674 PDiag(diag::warn_dyn_class_memaccess)
4675 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4676 << FnName << IsContained << ContainedRD << OperationType
4677 << Call->getCallee()->getSourceRange());
4678 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4679 BId != Builtin::BImemset)
4680 DiagRuntimeBehavior(
4681 Dest->getExprLoc(), Dest,
4682 PDiag(diag::warn_arc_object_memaccess)
4683 << ArgIdx << FnName << PointeeTy
4684 << Call->getCallee()->getSourceRange());
4688 DiagRuntimeBehavior(
4689 Dest->getExprLoc(), Dest,
4690 PDiag(diag::note_bad_memaccess_silence)
4691 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4697 // A little helper routine: ignore addition and subtraction of integer literals.
4698 // This intentionally does not ignore all integer constant expressions because
4699 // we don't want to remove sizeof().
4700 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4701 Ex = Ex->IgnoreParenCasts();
4704 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4705 if (!BO || !BO->isAdditiveOp())
4708 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4709 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4711 if (isa<IntegerLiteral>(RHS))
4713 else if (isa<IntegerLiteral>(LHS))
4722 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4723 ASTContext &Context) {
4724 // Only handle constant-sized or VLAs, but not flexible members.
4725 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4726 // Only issue the FIXIT for arrays of size > 1.
4727 if (CAT->getSize().getSExtValue() <= 1)
4729 } else if (!Ty->isVariableArrayType()) {
4735 // Warn if the user has made the 'size' argument to strlcpy or strlcat
4736 // be the size of the source, instead of the destination.
4737 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4738 IdentifierInfo *FnName) {
4740 // Don't crash if the user has the wrong number of arguments
4741 unsigned NumArgs = Call->getNumArgs();
4742 if ((NumArgs != 3) && (NumArgs != 4))
4745 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4746 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4747 const Expr *CompareWithSrc = nullptr;
4749 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4750 Call->getLocStart(), Call->getRParenLoc()))
4753 // Look for 'strlcpy(dst, x, sizeof(x))'
4754 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4755 CompareWithSrc = Ex;
4757 // Look for 'strlcpy(dst, x, strlen(x))'
4758 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
4759 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4760 SizeCall->getNumArgs() == 1)
4761 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4765 if (!CompareWithSrc)
4768 // Determine if the argument to sizeof/strlen is equal to the source
4769 // argument. In principle there's all kinds of things you could do
4770 // here, for instance creating an == expression and evaluating it with
4771 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4772 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4776 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4777 if (!CompareWithSrcDRE ||
4778 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4781 const Expr *OriginalSizeArg = Call->getArg(2);
4782 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4783 << OriginalSizeArg->getSourceRange() << FnName;
4785 // Output a FIXIT hint if the destination is an array (rather than a
4786 // pointer to an array). This could be enhanced to handle some
4787 // pointers if we know the actual size, like if DstArg is 'array+2'
4788 // we could say 'sizeof(array)-2'.
4789 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
4790 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
4793 SmallString<128> sizeString;
4794 llvm::raw_svector_ostream OS(sizeString);
4796 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4799 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4800 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4804 /// Check if two expressions refer to the same declaration.
4805 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4806 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4807 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4808 return D1->getDecl() == D2->getDecl();
4812 static const Expr *getStrlenExprArg(const Expr *E) {
4813 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4814 const FunctionDecl *FD = CE->getDirectCallee();
4815 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4817 return CE->getArg(0)->IgnoreParenCasts();
4822 // Warn on anti-patterns as the 'size' argument to strncat.
4823 // The correct size argument should look like following:
4824 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4825 void Sema::CheckStrncatArguments(const CallExpr *CE,
4826 IdentifierInfo *FnName) {
4827 // Don't crash if the user has the wrong number of arguments.
4828 if (CE->getNumArgs() < 3)
4830 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4831 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4832 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4834 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4835 CE->getRParenLoc()))
4838 // Identify common expressions, which are wrongly used as the size argument
4839 // to strncat and may lead to buffer overflows.
4840 unsigned PatternType = 0;
4841 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4843 if (referToTheSameDecl(SizeOfArg, DstArg))
4846 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4848 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4849 if (BE->getOpcode() == BO_Sub) {
4850 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4851 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4852 // - sizeof(dst) - strlen(dst)
4853 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4854 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4856 // - sizeof(src) - (anything)
4857 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4862 if (PatternType == 0)
4865 // Generate the diagnostic.
4866 SourceLocation SL = LenArg->getLocStart();
4867 SourceRange SR = LenArg->getSourceRange();
4868 SourceManager &SM = getSourceManager();
4870 // If the function is defined as a builtin macro, do not show macro expansion.
4871 if (SM.isMacroArgExpansion(SL)) {
4872 SL = SM.getSpellingLoc(SL);
4873 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4874 SM.getSpellingLoc(SR.getEnd()));
4877 // Check if the destination is an array (rather than a pointer to an array).
4878 QualType DstTy = DstArg->getType();
4879 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4881 if (!isKnownSizeArray) {
4882 if (PatternType == 1)
4883 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4885 Diag(SL, diag::warn_strncat_src_size) << SR;
4889 if (PatternType == 1)
4890 Diag(SL, diag::warn_strncat_large_size) << SR;
4892 Diag(SL, diag::warn_strncat_src_size) << SR;
4894 SmallString<128> sizeString;
4895 llvm::raw_svector_ostream OS(sizeString);
4897 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4900 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4903 Diag(SL, diag::note_strncat_wrong_size)
4904 << FixItHint::CreateReplacement(SR, OS.str());
4907 //===--- CHECK: Return Address of Stack Variable --------------------------===//
4909 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4911 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4914 /// CheckReturnStackAddr - Check if a return statement returns the address
4915 /// of a stack variable.
4917 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4918 SourceLocation ReturnLoc) {
4920 Expr *stackE = nullptr;
4921 SmallVector<DeclRefExpr *, 8> refVars;
4923 // Perform checking for returned stack addresses, local blocks,
4924 // label addresses or references to temporaries.
4925 if (lhsType->isPointerType() ||
4926 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4927 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
4928 } else if (lhsType->isReferenceType()) {
4929 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
4933 return; // Nothing suspicious was found.
4935 SourceLocation diagLoc;
4936 SourceRange diagRange;
4937 if (refVars.empty()) {
4938 diagLoc = stackE->getLocStart();
4939 diagRange = stackE->getSourceRange();
4941 // We followed through a reference variable. 'stackE' contains the
4942 // problematic expression but we will warn at the return statement pointing
4943 // at the reference variable. We will later display the "trail" of
4944 // reference variables using notes.
4945 diagLoc = refVars[0]->getLocStart();
4946 diagRange = refVars[0]->getSourceRange();
4949 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4950 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4951 : diag::warn_ret_stack_addr)
4952 << DR->getDecl()->getDeclName() << diagRange;
4953 } else if (isa<BlockExpr>(stackE)) { // local block.
4954 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4955 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4956 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4957 } else { // local temporary.
4958 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4959 : diag::warn_ret_local_temp_addr)
4963 // Display the "trail" of reference variables that we followed until we
4964 // found the problematic expression using notes.
4965 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4966 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4967 // If this var binds to another reference var, show the range of the next
4968 // var, otherwise the var binds to the problematic expression, in which case
4969 // show the range of the expression.
4970 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4971 : stackE->getSourceRange();
4972 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4973 << VD->getDeclName() << range;
4977 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4978 /// check if the expression in a return statement evaluates to an address
4979 /// to a location on the stack, a local block, an address of a label, or a
4980 /// reference to local temporary. The recursion is used to traverse the
4981 /// AST of the return expression, with recursion backtracking when we
4982 /// encounter a subexpression that (1) clearly does not lead to one of the
4983 /// above problematic expressions (2) is something we cannot determine leads to
4984 /// a problematic expression based on such local checking.
4986 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
4987 /// the expression that they point to. Such variables are added to the
4988 /// 'refVars' vector so that we know what the reference variable "trail" was.
4990 /// EvalAddr processes expressions that are pointers that are used as
4991 /// references (and not L-values). EvalVal handles all other values.
4992 /// At the base case of the recursion is a check for the above problematic
4995 /// This implementation handles:
4997 /// * pointer-to-pointer casts
4998 /// * implicit conversions from array references to pointers
4999 /// * taking the address of fields
5000 /// * arbitrary interplay between "&" and "*" operators
5001 /// * pointer arithmetic from an address of a stack variable
5002 /// * taking the address of an array element where the array is on the stack
5003 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5005 if (E->isTypeDependent())
5008 // We should only be called for evaluating pointer expressions.
5009 assert((E->getType()->isAnyPointerType() ||
5010 E->getType()->isBlockPointerType() ||
5011 E->getType()->isObjCQualifiedIdType()) &&
5012 "EvalAddr only works on pointers");
5014 E = E->IgnoreParens();
5016 // Our "symbolic interpreter" is just a dispatch off the currently
5017 // viewed AST node. We then recursively traverse the AST by calling
5018 // EvalAddr and EvalVal appropriately.
5019 switch (E->getStmtClass()) {
5020 case Stmt::DeclRefExprClass: {
5021 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5023 // If we leave the immediate function, the lifetime isn't about to end.
5024 if (DR->refersToEnclosingVariableOrCapture())
5027 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5028 // If this is a reference variable, follow through to the expression that
5030 if (V->hasLocalStorage() &&
5031 V->getType()->isReferenceType() && V->hasInit()) {
5032 // Add the reference variable to the "trail".
5033 refVars.push_back(DR);
5034 return EvalAddr(V->getInit(), refVars, ParentDecl);
5040 case Stmt::UnaryOperatorClass: {
5041 // The only unary operator that make sense to handle here
5042 // is AddrOf. All others don't make sense as pointers.
5043 UnaryOperator *U = cast<UnaryOperator>(E);
5045 if (U->getOpcode() == UO_AddrOf)
5046 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
5051 case Stmt::BinaryOperatorClass: {
5052 // Handle pointer arithmetic. All other binary operators are not valid
5054 BinaryOperator *B = cast<BinaryOperator>(E);
5055 BinaryOperatorKind op = B->getOpcode();
5057 if (op != BO_Add && op != BO_Sub)
5060 Expr *Base = B->getLHS();
5062 // Determine which argument is the real pointer base. It could be
5063 // the RHS argument instead of the LHS.
5064 if (!Base->getType()->isPointerType()) Base = B->getRHS();
5066 assert (Base->getType()->isPointerType());
5067 return EvalAddr(Base, refVars, ParentDecl);
5070 // For conditional operators we need to see if either the LHS or RHS are
5071 // valid DeclRefExpr*s. If one of them is valid, we return it.
5072 case Stmt::ConditionalOperatorClass: {
5073 ConditionalOperator *C = cast<ConditionalOperator>(E);
5075 // Handle the GNU extension for missing LHS.
5076 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5077 if (Expr *LHSExpr = C->getLHS()) {
5078 // In C++, we can have a throw-expression, which has 'void' type.
5079 if (!LHSExpr->getType()->isVoidType())
5080 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
5084 // In C++, we can have a throw-expression, which has 'void' type.
5085 if (C->getRHS()->getType()->isVoidType())
5088 return EvalAddr(C->getRHS(), refVars, ParentDecl);
5091 case Stmt::BlockExprClass:
5092 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5093 return E; // local block.
5096 case Stmt::AddrLabelExprClass:
5097 return E; // address of label.
5099 case Stmt::ExprWithCleanupsClass:
5100 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5103 // For casts, we need to handle conversions from arrays to
5104 // pointer values, and pointer-to-pointer conversions.
5105 case Stmt::ImplicitCastExprClass:
5106 case Stmt::CStyleCastExprClass:
5107 case Stmt::CXXFunctionalCastExprClass:
5108 case Stmt::ObjCBridgedCastExprClass:
5109 case Stmt::CXXStaticCastExprClass:
5110 case Stmt::CXXDynamicCastExprClass:
5111 case Stmt::CXXConstCastExprClass:
5112 case Stmt::CXXReinterpretCastExprClass: {
5113 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5114 switch (cast<CastExpr>(E)->getCastKind()) {
5115 case CK_LValueToRValue:
5117 case CK_BaseToDerived:
5118 case CK_DerivedToBase:
5119 case CK_UncheckedDerivedToBase:
5121 case CK_CPointerToObjCPointerCast:
5122 case CK_BlockPointerToObjCPointerCast:
5123 case CK_AnyPointerToBlockPointerCast:
5124 return EvalAddr(SubExpr, refVars, ParentDecl);
5126 case CK_ArrayToPointerDecay:
5127 return EvalVal(SubExpr, refVars, ParentDecl);
5130 if (SubExpr->getType()->isAnyPointerType() ||
5131 SubExpr->getType()->isBlockPointerType() ||
5132 SubExpr->getType()->isObjCQualifiedIdType())
5133 return EvalAddr(SubExpr, refVars, ParentDecl);
5142 case Stmt::MaterializeTemporaryExprClass:
5143 if (Expr *Result = EvalAddr(
5144 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5145 refVars, ParentDecl))
5150 // Everything else: we simply don't reason about them.
5157 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
5158 /// See the comments for EvalAddr for more details.
5159 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5162 // We should only be called for evaluating non-pointer expressions, or
5163 // expressions with a pointer type that are not used as references but instead
5164 // are l-values (e.g., DeclRefExpr with a pointer type).
5166 // Our "symbolic interpreter" is just a dispatch off the currently
5167 // viewed AST node. We then recursively traverse the AST by calling
5168 // EvalAddr and EvalVal appropriately.
5170 E = E->IgnoreParens();
5171 switch (E->getStmtClass()) {
5172 case Stmt::ImplicitCastExprClass: {
5173 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
5174 if (IE->getValueKind() == VK_LValue) {
5175 E = IE->getSubExpr();
5181 case Stmt::ExprWithCleanupsClass:
5182 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5184 case Stmt::DeclRefExprClass: {
5185 // When we hit a DeclRefExpr we are looking at code that refers to a
5186 // variable's name. If it's not a reference variable we check if it has
5187 // local storage within the function, and if so, return the expression.
5188 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5190 // If we leave the immediate function, the lifetime isn't about to end.
5191 if (DR->refersToEnclosingVariableOrCapture())
5194 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5195 // Check if it refers to itself, e.g. "int& i = i;".
5196 if (V == ParentDecl)
5199 if (V->hasLocalStorage()) {
5200 if (!V->getType()->isReferenceType())
5203 // Reference variable, follow through to the expression that
5206 // Add the reference variable to the "trail".
5207 refVars.push_back(DR);
5208 return EvalVal(V->getInit(), refVars, V);
5216 case Stmt::UnaryOperatorClass: {
5217 // The only unary operator that make sense to handle here
5218 // is Deref. All others don't resolve to a "name." This includes
5219 // handling all sorts of rvalues passed to a unary operator.
5220 UnaryOperator *U = cast<UnaryOperator>(E);
5222 if (U->getOpcode() == UO_Deref)
5223 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
5228 case Stmt::ArraySubscriptExprClass: {
5229 // Array subscripts are potential references to data on the stack. We
5230 // retrieve the DeclRefExpr* for the array variable if it indeed
5231 // has local storage.
5232 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5235 case Stmt::ConditionalOperatorClass: {
5236 // For conditional operators we need to see if either the LHS or RHS are
5237 // non-NULL Expr's. If one is non-NULL, we return it.
5238 ConditionalOperator *C = cast<ConditionalOperator>(E);
5240 // Handle the GNU extension for missing LHS.
5241 if (Expr *LHSExpr = C->getLHS()) {
5242 // In C++, we can have a throw-expression, which has 'void' type.
5243 if (!LHSExpr->getType()->isVoidType())
5244 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5248 // In C++, we can have a throw-expression, which has 'void' type.
5249 if (C->getRHS()->getType()->isVoidType())
5252 return EvalVal(C->getRHS(), refVars, ParentDecl);
5255 // Accesses to members are potential references to data on the stack.
5256 case Stmt::MemberExprClass: {
5257 MemberExpr *M = cast<MemberExpr>(E);
5259 // Check for indirect access. We only want direct field accesses.
5263 // Check whether the member type is itself a reference, in which case
5264 // we're not going to refer to the member, but to what the member refers to.
5265 if (M->getMemberDecl()->getType()->isReferenceType())
5268 return EvalVal(M->getBase(), refVars, ParentDecl);
5271 case Stmt::MaterializeTemporaryExprClass:
5272 if (Expr *Result = EvalVal(
5273 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5274 refVars, ParentDecl))
5280 // Check that we don't return or take the address of a reference to a
5281 // temporary. This is only useful in C++.
5282 if (!E->isTypeDependent() && E->isRValue())
5285 // Everything else: we simply don't reason about them.
5292 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5293 SourceLocation ReturnLoc,
5295 const AttrVec *Attrs,
5296 const FunctionDecl *FD) {
5297 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5299 // Check if the return value is null but should not be.
5300 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5301 CheckNonNullExpr(*this, RetValExp))
5302 Diag(ReturnLoc, diag::warn_null_ret)
5303 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5305 // C++11 [basic.stc.dynamic.allocation]p4:
5306 // If an allocation function declared with a non-throwing
5307 // exception-specification fails to allocate storage, it shall return
5308 // a null pointer. Any other allocation function that fails to allocate
5309 // storage shall indicate failure only by throwing an exception [...]
5311 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5312 if (Op == OO_New || Op == OO_Array_New) {
5313 const FunctionProtoType *Proto
5314 = FD->getType()->castAs<FunctionProtoType>();
5315 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5316 CheckNonNullExpr(*this, RetValExp))
5317 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5318 << FD << getLangOpts().CPlusPlus11;
5323 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5325 /// Check for comparisons of floating point operands using != and ==.
5326 /// Issue a warning if these are no self-comparisons, as they are not likely
5327 /// to do what the programmer intended.
5328 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
5329 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5330 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
5332 // Special case: check for x == x (which is OK).
5333 // Do not emit warnings for such cases.
5334 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5335 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5336 if (DRL->getDecl() == DRR->getDecl())
5340 // Special case: check for comparisons against literals that can be exactly
5341 // represented by APFloat. In such cases, do not emit a warning. This
5342 // is a heuristic: often comparison against such literals are used to
5343 // detect if a value in a variable has not changed. This clearly can
5344 // lead to false negatives.
5345 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5349 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5353 // Check for comparisons with builtin types.
5354 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
5355 if (CL->getBuiltinCallee())
5358 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
5359 if (CR->getBuiltinCallee())
5362 // Emit the diagnostic.
5363 Diag(Loc, diag::warn_floatingpoint_eq)
5364 << LHS->getSourceRange() << RHS->getSourceRange();
5367 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5368 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
5372 /// Structure recording the 'active' range of an integer-valued
5375 /// The number of bits active in the int.
5378 /// True if the int is known not to have negative values.
5381 IntRange(unsigned Width, bool NonNegative)
5382 : Width(Width), NonNegative(NonNegative)
5385 /// Returns the range of the bool type.
5386 static IntRange forBoolType() {
5387 return IntRange(1, true);
5390 /// Returns the range of an opaque value of the given integral type.
5391 static IntRange forValueOfType(ASTContext &C, QualType T) {
5392 return forValueOfCanonicalType(C,
5393 T->getCanonicalTypeInternal().getTypePtr());
5396 /// Returns the range of an opaque value of a canonical integral type.
5397 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
5398 assert(T->isCanonicalUnqualified());
5400 if (const VectorType *VT = dyn_cast<VectorType>(T))
5401 T = VT->getElementType().getTypePtr();
5402 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5403 T = CT->getElementType().getTypePtr();
5404 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5405 T = AT->getValueType().getTypePtr();
5407 // For enum types, use the known bit width of the enumerators.
5408 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
5409 EnumDecl *Enum = ET->getDecl();
5410 if (!Enum->isCompleteDefinition())
5411 return IntRange(C.getIntWidth(QualType(T, 0)), false);
5413 unsigned NumPositive = Enum->getNumPositiveBits();
5414 unsigned NumNegative = Enum->getNumNegativeBits();
5416 if (NumNegative == 0)
5417 return IntRange(NumPositive, true/*NonNegative*/);
5419 return IntRange(std::max(NumPositive + 1, NumNegative),
5420 false/*NonNegative*/);
5423 const BuiltinType *BT = cast<BuiltinType>(T);
5424 assert(BT->isInteger());
5426 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5429 /// Returns the "target" range of a canonical integral type, i.e.
5430 /// the range of values expressible in the type.
5432 /// This matches forValueOfCanonicalType except that enums have the
5433 /// full range of their type, not the range of their enumerators.
5434 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5435 assert(T->isCanonicalUnqualified());
5437 if (const VectorType *VT = dyn_cast<VectorType>(T))
5438 T = VT->getElementType().getTypePtr();
5439 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5440 T = CT->getElementType().getTypePtr();
5441 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5442 T = AT->getValueType().getTypePtr();
5443 if (const EnumType *ET = dyn_cast<EnumType>(T))
5444 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
5446 const BuiltinType *BT = cast<BuiltinType>(T);
5447 assert(BT->isInteger());
5449 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5452 /// Returns the supremum of two ranges: i.e. their conservative merge.
5453 static IntRange join(IntRange L, IntRange R) {
5454 return IntRange(std::max(L.Width, R.Width),
5455 L.NonNegative && R.NonNegative);
5458 /// Returns the infinum of two ranges: i.e. their aggressive merge.
5459 static IntRange meet(IntRange L, IntRange R) {
5460 return IntRange(std::min(L.Width, R.Width),
5461 L.NonNegative || R.NonNegative);
5465 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5466 unsigned MaxWidth) {
5467 if (value.isSigned() && value.isNegative())
5468 return IntRange(value.getMinSignedBits(), false);
5470 if (value.getBitWidth() > MaxWidth)
5471 value = value.trunc(MaxWidth);
5473 // isNonNegative() just checks the sign bit without considering
5475 return IntRange(value.getActiveBits(), true);
5478 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5479 unsigned MaxWidth) {
5481 return GetValueRange(C, result.getInt(), MaxWidth);
5483 if (result.isVector()) {
5484 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5485 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5486 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5487 R = IntRange::join(R, El);
5492 if (result.isComplexInt()) {
5493 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5494 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5495 return IntRange::join(R, I);
5498 // This can happen with lossless casts to intptr_t of "based" lvalues.
5499 // Assume it might use arbitrary bits.
5500 // FIXME: The only reason we need to pass the type in here is to get
5501 // the sign right on this one case. It would be nice if APValue
5503 assert(result.isLValue() || result.isAddrLabelDiff());
5504 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
5507 static QualType GetExprType(Expr *E) {
5508 QualType Ty = E->getType();
5509 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5510 Ty = AtomicRHS->getValueType();
5514 /// Pseudo-evaluate the given integer expression, estimating the
5515 /// range of values it might take.
5517 /// \param MaxWidth - the width to which the value will be truncated
5518 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
5519 E = E->IgnoreParens();
5521 // Try a full evaluation first.
5522 Expr::EvalResult result;
5523 if (E->EvaluateAsRValue(result, C))
5524 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
5526 // I think we only want to look through implicit casts here; if the
5527 // user has an explicit widening cast, we should treat the value as
5528 // being of the new, wider type.
5529 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
5530 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
5531 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5533 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
5535 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
5537 // Assume that non-integer casts can span the full range of the type.
5539 return OutputTypeRange;
5542 = GetExprRange(C, CE->getSubExpr(),
5543 std::min(MaxWidth, OutputTypeRange.Width));
5545 // Bail out if the subexpr's range is as wide as the cast type.
5546 if (SubRange.Width >= OutputTypeRange.Width)
5547 return OutputTypeRange;
5549 // Otherwise, we take the smaller width, and we're non-negative if
5550 // either the output type or the subexpr is.
5551 return IntRange(SubRange.Width,
5552 SubRange.NonNegative || OutputTypeRange.NonNegative);
5555 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5556 // If we can fold the condition, just take that operand.
5558 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5559 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5560 : CO->getFalseExpr(),
5563 // Otherwise, conservatively merge.
5564 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5565 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5566 return IntRange::join(L, R);
5569 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5570 switch (BO->getOpcode()) {
5572 // Boolean-valued operations are single-bit and positive.
5581 return IntRange::forBoolType();
5583 // The type of the assignments is the type of the LHS, so the RHS
5584 // is not necessarily the same type.
5593 return IntRange::forValueOfType(C, GetExprType(E));
5595 // Simple assignments just pass through the RHS, which will have
5596 // been coerced to the LHS type.
5599 return GetExprRange(C, BO->getRHS(), MaxWidth);
5601 // Operations with opaque sources are black-listed.
5604 return IntRange::forValueOfType(C, GetExprType(E));
5606 // Bitwise-and uses the *infinum* of the two source ranges.
5609 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5610 GetExprRange(C, BO->getRHS(), MaxWidth));
5612 // Left shift gets black-listed based on a judgement call.
5614 // ...except that we want to treat '1 << (blah)' as logically
5615 // positive. It's an important idiom.
5616 if (IntegerLiteral *I
5617 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5618 if (I->getValue() == 1) {
5619 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5620 return IntRange(R.Width, /*NonNegative*/ true);
5626 return IntRange::forValueOfType(C, GetExprType(E));
5628 // Right shift by a constant can narrow its left argument.
5630 case BO_ShrAssign: {
5631 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5633 // If the shift amount is a positive constant, drop the width by
5636 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5637 shift.isNonNegative()) {
5638 unsigned zext = shift.getZExtValue();
5639 if (zext >= L.Width)
5640 L.Width = (L.NonNegative ? 0 : 1);
5648 // Comma acts as its right operand.
5650 return GetExprRange(C, BO->getRHS(), MaxWidth);
5652 // Black-list pointer subtractions.
5654 if (BO->getLHS()->getType()->isPointerType())
5655 return IntRange::forValueOfType(C, GetExprType(E));
5658 // The width of a division result is mostly determined by the size
5661 // Don't 'pre-truncate' the operands.
5662 unsigned opWidth = C.getIntWidth(GetExprType(E));
5663 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5665 // If the divisor is constant, use that.
5666 llvm::APSInt divisor;
5667 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5668 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5669 if (log2 >= L.Width)
5670 L.Width = (L.NonNegative ? 0 : 1);
5672 L.Width = std::min(L.Width - log2, MaxWidth);
5676 // Otherwise, just use the LHS's width.
5677 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5678 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5681 // The result of a remainder can't be larger than the result of
5684 // Don't 'pre-truncate' the operands.
5685 unsigned opWidth = C.getIntWidth(GetExprType(E));
5686 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5687 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5689 IntRange meet = IntRange::meet(L, R);
5690 meet.Width = std::min(meet.Width, MaxWidth);
5694 // The default behavior is okay for these.
5702 // The default case is to treat the operation as if it were closed
5703 // on the narrowest type that encompasses both operands.
5704 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5705 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5706 return IntRange::join(L, R);
5709 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5710 switch (UO->getOpcode()) {
5711 // Boolean-valued operations are white-listed.
5713 return IntRange::forBoolType();
5715 // Operations with opaque sources are black-listed.
5717 case UO_AddrOf: // should be impossible
5718 return IntRange::forValueOfType(C, GetExprType(E));
5721 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5725 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5726 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5728 if (FieldDecl *BitField = E->getSourceBitField())
5729 return IntRange(BitField->getBitWidthValue(C),
5730 BitField->getType()->isUnsignedIntegerOrEnumerationType());
5732 return IntRange::forValueOfType(C, GetExprType(E));
5735 static IntRange GetExprRange(ASTContext &C, Expr *E) {
5736 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5739 /// Checks whether the given value, which currently has the given
5740 /// source semantics, has the same value when coerced through the
5741 /// target semantics.
5742 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5743 const llvm::fltSemantics &Src,
5744 const llvm::fltSemantics &Tgt) {
5745 llvm::APFloat truncated = value;
5748 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5749 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5751 return truncated.bitwiseIsEqual(value);
5754 /// Checks whether the given value, which currently has the given
5755 /// source semantics, has the same value when coerced through the
5756 /// target semantics.
5758 /// The value might be a vector of floats (or a complex number).
5759 static bool IsSameFloatAfterCast(const APValue &value,
5760 const llvm::fltSemantics &Src,
5761 const llvm::fltSemantics &Tgt) {
5762 if (value.isFloat())
5763 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5765 if (value.isVector()) {
5766 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5767 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5772 assert(value.isComplexFloat());
5773 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5774 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5777 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
5779 static bool IsZero(Sema &S, Expr *E) {
5780 // Suppress cases where we are comparing against an enum constant.
5781 if (const DeclRefExpr *DR =
5782 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5783 if (isa<EnumConstantDecl>(DR->getDecl()))
5786 // Suppress cases where the '0' value is expanded from a macro.
5787 if (E->getLocStart().isMacroID())
5791 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5794 static bool HasEnumType(Expr *E) {
5795 // Strip off implicit integral promotions.
5796 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5797 if (ICE->getCastKind() != CK_IntegralCast &&
5798 ICE->getCastKind() != CK_NoOp)
5800 E = ICE->getSubExpr();
5803 return E->getType()->isEnumeralType();
5806 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
5807 // Disable warning in template instantiations.
5808 if (!S.ActiveTemplateInstantiations.empty())
5811 BinaryOperatorKind op = E->getOpcode();
5812 if (E->isValueDependent())
5815 if (op == BO_LT && IsZero(S, E->getRHS())) {
5816 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5817 << "< 0" << "false" << HasEnumType(E->getLHS())
5818 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5819 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
5820 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5821 << ">= 0" << "true" << HasEnumType(E->getLHS())
5822 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5823 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
5824 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5825 << "0 >" << "false" << HasEnumType(E->getRHS())
5826 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5827 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
5828 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5829 << "0 <=" << "true" << HasEnumType(E->getRHS())
5830 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5834 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
5835 Expr *Constant, Expr *Other,
5838 // Disable warning in template instantiations.
5839 if (!S.ActiveTemplateInstantiations.empty())
5842 // TODO: Investigate using GetExprRange() to get tighter bounds
5843 // on the bit ranges.
5844 QualType OtherT = Other->getType();
5845 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5846 OtherT = AT->getValueType();
5847 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5848 unsigned OtherWidth = OtherRange.Width;
5850 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5852 // 0 values are handled later by CheckTrivialUnsignedComparison().
5853 if ((Value == 0) && (!OtherIsBooleanType))
5856 BinaryOperatorKind op = E->getOpcode();
5859 // Used for diagnostic printout.
5861 LiteralConstant = 0,
5864 } LiteralOrBoolConstant = LiteralConstant;
5866 if (!OtherIsBooleanType) {
5867 QualType ConstantT = Constant->getType();
5868 QualType CommonT = E->getLHS()->getType();
5870 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5872 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5873 "comparison with non-integer type");
5875 bool ConstantSigned = ConstantT->isSignedIntegerType();
5876 bool CommonSigned = CommonT->isSignedIntegerType();
5878 bool EqualityOnly = false;
5881 // The common type is signed, therefore no signed to unsigned conversion.
5882 if (!OtherRange.NonNegative) {
5883 // Check that the constant is representable in type OtherT.
5884 if (ConstantSigned) {
5885 if (OtherWidth >= Value.getMinSignedBits())
5887 } else { // !ConstantSigned
5888 if (OtherWidth >= Value.getActiveBits() + 1)
5891 } else { // !OtherSigned
5892 // Check that the constant is representable in type OtherT.
5893 // Negative values are out of range.
5894 if (ConstantSigned) {
5895 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5897 } else { // !ConstantSigned
5898 if (OtherWidth >= Value.getActiveBits())
5902 } else { // !CommonSigned
5903 if (OtherRange.NonNegative) {
5904 if (OtherWidth >= Value.getActiveBits())
5906 } else { // OtherSigned
5907 assert(!ConstantSigned &&
5908 "Two signed types converted to unsigned types.");
5909 // Check to see if the constant is representable in OtherT.
5910 if (OtherWidth > Value.getActiveBits())
5912 // Check to see if the constant is equivalent to a negative value
5914 if (S.Context.getIntWidth(ConstantT) ==
5915 S.Context.getIntWidth(CommonT) &&
5916 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5918 // The constant value rests between values that OtherT can represent
5919 // after conversion. Relational comparison still works, but equality
5920 // comparisons will be tautological.
5921 EqualityOnly = true;
5925 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5927 if (op == BO_EQ || op == BO_NE) {
5928 IsTrue = op == BO_NE;
5929 } else if (EqualityOnly) {
5931 } else if (RhsConstant) {
5932 if (op == BO_GT || op == BO_GE)
5933 IsTrue = !PositiveConstant;
5934 else // op == BO_LT || op == BO_LE
5935 IsTrue = PositiveConstant;
5937 if (op == BO_LT || op == BO_LE)
5938 IsTrue = !PositiveConstant;
5939 else // op == BO_GT || op == BO_GE
5940 IsTrue = PositiveConstant;
5943 // Other isKnownToHaveBooleanValue
5944 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5945 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5946 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5948 static const struct LinkedConditions {
5949 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5950 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5951 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5952 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5953 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5954 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5957 // Constant on LHS. | Constant on RHS. |
5958 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5959 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5960 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5961 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5962 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5963 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5964 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5967 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5969 enum ConstantValue ConstVal = Zero;
5970 if (Value.isUnsigned() || Value.isNonNegative()) {
5972 LiteralOrBoolConstant =
5973 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5975 } else if (Value == 1) {
5976 LiteralOrBoolConstant =
5977 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5980 LiteralOrBoolConstant = LiteralConstant;
5987 CompareBoolWithConstantResult CmpRes;
5991 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5994 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5997 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6000 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6003 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6006 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6013 if (CmpRes == AFals) {
6015 } else if (CmpRes == ATrue) {
6022 // If this is a comparison to an enum constant, include that
6023 // constant in the diagnostic.
6024 const EnumConstantDecl *ED = nullptr;
6025 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6026 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6028 SmallString<64> PrettySourceValue;
6029 llvm::raw_svector_ostream OS(PrettySourceValue);
6031 OS << '\'' << *ED << "' (" << Value << ")";
6035 S.DiagRuntimeBehavior(
6036 E->getOperatorLoc(), E,
6037 S.PDiag(diag::warn_out_of_range_compare)
6038 << OS.str() << LiteralOrBoolConstant
6039 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6040 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
6043 /// Analyze the operands of the given comparison. Implements the
6044 /// fallback case from AnalyzeComparison.
6045 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
6046 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6047 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6050 /// \brief Implements -Wsign-compare.
6052 /// \param E the binary operator to check for warnings
6053 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
6054 // The type the comparison is being performed in.
6055 QualType T = E->getLHS()->getType();
6057 // Only analyze comparison operators where both sides have been converted to
6059 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6060 return AnalyzeImpConvsInComparison(S, E);
6062 // Don't analyze value-dependent comparisons directly.
6063 if (E->isValueDependent())
6064 return AnalyzeImpConvsInComparison(S, E);
6066 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6067 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
6069 bool IsComparisonConstant = false;
6071 // Check whether an integer constant comparison results in a value
6072 // of 'true' or 'false'.
6073 if (T->isIntegralType(S.Context)) {
6074 llvm::APSInt RHSValue;
6075 bool IsRHSIntegralLiteral =
6076 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6077 llvm::APSInt LHSValue;
6078 bool IsLHSIntegralLiteral =
6079 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6080 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6081 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6082 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6083 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6085 IsComparisonConstant =
6086 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6087 } else if (!T->hasUnsignedIntegerRepresentation())
6088 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
6090 // We don't do anything special if this isn't an unsigned integral
6091 // comparison: we're only interested in integral comparisons, and
6092 // signed comparisons only happen in cases we don't care to warn about.
6094 // We also don't care about value-dependent expressions or expressions
6095 // whose result is a constant.
6096 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
6097 return AnalyzeImpConvsInComparison(S, E);
6099 // Check to see if one of the (unmodified) operands is of different
6101 Expr *signedOperand, *unsignedOperand;
6102 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6103 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
6104 "unsigned comparison between two signed integer expressions?");
6105 signedOperand = LHS;
6106 unsignedOperand = RHS;
6107 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6108 signedOperand = RHS;
6109 unsignedOperand = LHS;
6111 CheckTrivialUnsignedComparison(S, E);
6112 return AnalyzeImpConvsInComparison(S, E);
6115 // Otherwise, calculate the effective range of the signed operand.
6116 IntRange signedRange = GetExprRange(S.Context, signedOperand);
6118 // Go ahead and analyze implicit conversions in the operands. Note
6119 // that we skip the implicit conversions on both sides.
6120 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6121 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
6123 // If the signed range is non-negative, -Wsign-compare won't fire,
6124 // but we should still check for comparisons which are always true
6126 if (signedRange.NonNegative)
6127 return CheckTrivialUnsignedComparison(S, E);
6129 // For (in)equality comparisons, if the unsigned operand is a
6130 // constant which cannot collide with a overflowed signed operand,
6131 // then reinterpreting the signed operand as unsigned will not
6132 // change the result of the comparison.
6133 if (E->isEqualityOp()) {
6134 unsigned comparisonWidth = S.Context.getIntWidth(T);
6135 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
6137 // We should never be unable to prove that the unsigned operand is
6139 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6141 if (unsignedRange.Width < comparisonWidth)
6145 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6146 S.PDiag(diag::warn_mixed_sign_comparison)
6147 << LHS->getType() << RHS->getType()
6148 << LHS->getSourceRange() << RHS->getSourceRange());
6151 /// Analyzes an attempt to assign the given value to a bitfield.
6153 /// Returns true if there was something fishy about the attempt.
6154 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6155 SourceLocation InitLoc) {
6156 assert(Bitfield->isBitField());
6157 if (Bitfield->isInvalidDecl())
6160 // White-list bool bitfields.
6161 if (Bitfield->getType()->isBooleanType())
6164 // Ignore value- or type-dependent expressions.
6165 if (Bitfield->getBitWidth()->isValueDependent() ||
6166 Bitfield->getBitWidth()->isTypeDependent() ||
6167 Init->isValueDependent() ||
6168 Init->isTypeDependent())
6171 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6174 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
6177 unsigned OriginalWidth = Value.getBitWidth();
6178 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
6180 if (OriginalWidth <= FieldWidth)
6183 // Compute the value which the bitfield will contain.
6184 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6185 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
6187 // Check whether the stored value is equal to the original value.
6188 TruncatedValue = TruncatedValue.extend(OriginalWidth);
6189 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6192 // Special-case bitfields of width 1: booleans are naturally 0/1, and
6193 // therefore don't strictly fit into a signed bitfield of width 1.
6194 if (FieldWidth == 1 && Value == 1)
6197 std::string PrettyValue = Value.toString(10);
6198 std::string PrettyTrunc = TruncatedValue.toString(10);
6200 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6201 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6202 << Init->getSourceRange();
6207 /// Analyze the given simple or compound assignment for warning-worthy
6209 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
6210 // Just recurse on the LHS.
6211 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6213 // We want to recurse on the RHS as normal unless we're assigning to
6215 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
6216 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
6217 E->getOperatorLoc())) {
6218 // Recurse, ignoring any implicit conversions on the RHS.
6219 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6220 E->getOperatorLoc());
6224 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6227 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
6228 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
6229 SourceLocation CContext, unsigned diag,
6230 bool pruneControlFlow = false) {
6231 if (pruneControlFlow) {
6232 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6234 << SourceType << T << E->getSourceRange()
6235 << SourceRange(CContext));
6238 S.Diag(E->getExprLoc(), diag)
6239 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6242 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
6243 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
6244 SourceLocation CContext, unsigned diag,
6245 bool pruneControlFlow = false) {
6246 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
6249 /// Diagnose an implicit cast from a literal expression. Does not warn when the
6250 /// cast wouldn't lose information.
6251 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6252 SourceLocation CContext) {
6253 // Try to convert the literal exactly to an integer. If we can, don't warn.
6254 bool isExact = false;
6255 const llvm::APFloat &Value = FL->getValue();
6256 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6257 T->hasUnsignedIntegerRepresentation());
6258 if (Value.convertToInteger(IntegerValue,
6259 llvm::APFloat::rmTowardZero, &isExact)
6260 == llvm::APFloat::opOK && isExact)
6263 // FIXME: Force the precision of the source value down so we don't print
6264 // digits which are usually useless (we don't really care here if we
6265 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6266 // would automatically print the shortest representation, but it's a bit
6267 // tricky to implement.
6268 SmallString<16> PrettySourceValue;
6269 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6270 precision = (precision * 59 + 195) / 196;
6271 Value.toString(PrettySourceValue, precision);
6273 SmallString<16> PrettyTargetValue;
6274 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6275 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6277 IntegerValue.toString(PrettyTargetValue);
6279 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6280 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6281 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
6284 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6285 if (!Range.Width) return "0";
6287 llvm::APSInt ValueInRange = Value;
6288 ValueInRange.setIsSigned(!Range.NonNegative);
6289 ValueInRange = ValueInRange.trunc(Range.Width);
6290 return ValueInRange.toString(10);
6293 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6294 if (!isa<ImplicitCastExpr>(Ex))
6297 Expr *InnerE = Ex->IgnoreParenImpCasts();
6298 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6299 const Type *Source =
6300 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6301 if (Target->isDependentType())
6304 const BuiltinType *FloatCandidateBT =
6305 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6306 const Type *BoolCandidateType = ToBool ? Target : Source;
6308 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6309 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6312 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6313 SourceLocation CC) {
6314 unsigned NumArgs = TheCall->getNumArgs();
6315 for (unsigned i = 0; i < NumArgs; ++i) {
6316 Expr *CurrA = TheCall->getArg(i);
6317 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6320 bool IsSwapped = ((i > 0) &&
6321 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6322 IsSwapped |= ((i < (NumArgs - 1)) &&
6323 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6325 // Warn on this floating-point to bool conversion.
6326 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6327 CurrA->getType(), CC,
6328 diag::warn_impcast_floating_point_to_bool);
6333 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6334 SourceLocation CC) {
6335 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6339 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6340 const Expr::NullPointerConstantKind NullKind =
6341 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6342 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6345 // Return if target type is a safe conversion.
6346 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6347 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6350 SourceLocation Loc = E->getSourceRange().getBegin();
6352 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6353 if (NullKind == Expr::NPCK_GNUNull) {
6354 if (Loc.isMacroID())
6355 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6358 // Only warn if the null and context location are in the same macro expansion.
6359 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6362 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6363 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6364 << FixItHint::CreateReplacement(Loc,
6365 S.getFixItZeroLiteralForType(T, Loc));
6368 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
6369 SourceLocation CC, bool *ICContext = nullptr) {
6370 if (E->isTypeDependent() || E->isValueDependent()) return;
6372 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6373 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6374 if (Source == Target) return;
6375 if (Target->isDependentType()) return;
6377 // If the conversion context location is invalid don't complain. We also
6378 // don't want to emit a warning if the issue occurs from the expansion of
6379 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6380 // delay this check as long as possible. Once we detect we are in that
6381 // scenario, we just return.
6385 // Diagnose implicit casts to bool.
6386 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6387 if (isa<StringLiteral>(E))
6388 // Warn on string literal to bool. Checks for string literals in logical
6389 // and expressions, for instance, assert(0 && "error here"), are
6390 // prevented by a check in AnalyzeImplicitConversions().
6391 return DiagnoseImpCast(S, E, T, CC,
6392 diag::warn_impcast_string_literal_to_bool);
6393 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6394 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6395 // This covers the literal expressions that evaluate to Objective-C
6397 return DiagnoseImpCast(S, E, T, CC,
6398 diag::warn_impcast_objective_c_literal_to_bool);
6400 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6401 // Warn on pointer to bool conversion that is always true.
6402 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6407 // Strip vector types.
6408 if (isa<VectorType>(Source)) {
6409 if (!isa<VectorType>(Target)) {
6410 if (S.SourceMgr.isInSystemMacro(CC))
6412 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
6415 // If the vector cast is cast between two vectors of the same size, it is
6416 // a bitcast, not a conversion.
6417 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6420 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6421 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6423 if (auto VecTy = dyn_cast<VectorType>(Target))
6424 Target = VecTy->getElementType().getTypePtr();
6426 // Strip complex types.
6427 if (isa<ComplexType>(Source)) {
6428 if (!isa<ComplexType>(Target)) {
6429 if (S.SourceMgr.isInSystemMacro(CC))
6432 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
6435 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6436 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6439 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6440 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6442 // If the source is floating point...
6443 if (SourceBT && SourceBT->isFloatingPoint()) {
6444 // ...and the target is floating point...
6445 if (TargetBT && TargetBT->isFloatingPoint()) {
6446 // ...then warn if we're dropping FP rank.
6448 // Builtin FP kinds are ordered by increasing FP rank.
6449 if (SourceBT->getKind() > TargetBT->getKind()) {
6450 // Don't warn about float constants that are precisely
6451 // representable in the target type.
6452 Expr::EvalResult result;
6453 if (E->EvaluateAsRValue(result, S.Context)) {
6454 // Value might be a float, a float vector, or a float complex.
6455 if (IsSameFloatAfterCast(result.Val,
6456 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6457 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
6461 if (S.SourceMgr.isInSystemMacro(CC))
6464 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
6469 // If the target is integral, always warn.
6470 if (TargetBT && TargetBT->isInteger()) {
6471 if (S.SourceMgr.isInSystemMacro(CC))
6474 Expr *InnerE = E->IgnoreParenImpCasts();
6475 // We also want to warn on, e.g., "int i = -1.234"
6476 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6477 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6478 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6480 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6481 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
6483 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6487 // If the target is bool, warn if expr is a function or method call.
6488 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6490 // Check last argument of function call to see if it is an
6491 // implicit cast from a type matching the type the result
6492 // is being cast to.
6493 CallExpr *CEx = cast<CallExpr>(E);
6494 unsigned NumArgs = CEx->getNumArgs();
6496 Expr *LastA = CEx->getArg(NumArgs - 1);
6497 Expr *InnerE = LastA->IgnoreParenImpCasts();
6498 const Type *InnerType =
6499 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6500 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6501 // Warn on this floating-point to bool conversion
6502 DiagnoseImpCast(S, E, T, CC,
6503 diag::warn_impcast_floating_point_to_bool);
6510 DiagnoseNullConversion(S, E, T, CC);
6512 if (!Source->isIntegerType() || !Target->isIntegerType())
6515 // TODO: remove this early return once the false positives for constant->bool
6516 // in templates, macros, etc, are reduced or removed.
6517 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6520 IntRange SourceRange = GetExprRange(S.Context, E);
6521 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
6523 if (SourceRange.Width > TargetRange.Width) {
6524 // If the source is a constant, use a default-on diagnostic.
6525 // TODO: this should happen for bitfield stores, too.
6526 llvm::APSInt Value(32);
6527 if (E->isIntegerConstantExpr(Value, S.Context)) {
6528 if (S.SourceMgr.isInSystemMacro(CC))
6531 std::string PrettySourceValue = Value.toString(10);
6532 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
6534 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6535 S.PDiag(diag::warn_impcast_integer_precision_constant)
6536 << PrettySourceValue << PrettyTargetValue
6537 << E->getType() << T << E->getSourceRange()
6538 << clang::SourceRange(CC));
6542 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6543 if (S.SourceMgr.isInSystemMacro(CC))
6546 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
6547 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6548 /* pruneControlFlow */ true);
6549 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
6552 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6553 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6554 SourceRange.Width == TargetRange.Width)) {
6556 if (S.SourceMgr.isInSystemMacro(CC))
6559 unsigned DiagID = diag::warn_impcast_integer_sign;
6561 // Traditionally, gcc has warned about this under -Wsign-compare.
6562 // We also want to warn about it in -Wconversion.
6563 // So if -Wconversion is off, use a completely identical diagnostic
6564 // in the sign-compare group.
6565 // The conditional-checking code will
6567 DiagID = diag::warn_impcast_integer_sign_conditional;
6571 return DiagnoseImpCast(S, E, T, CC, DiagID);
6574 // Diagnose conversions between different enumeration types.
6575 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6576 // type, to give us better diagnostics.
6577 QualType SourceType = E->getType();
6578 if (!S.getLangOpts().CPlusPlus) {
6579 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6580 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6581 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6582 SourceType = S.Context.getTypeDeclType(Enum);
6583 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6587 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6588 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
6589 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6590 TargetEnum->getDecl()->hasNameForLinkage() &&
6591 SourceEnum != TargetEnum) {
6592 if (S.SourceMgr.isInSystemMacro(CC))
6595 return DiagnoseImpCast(S, E, SourceType, T, CC,
6596 diag::warn_impcast_different_enum_types);
6602 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6603 SourceLocation CC, QualType T);
6605 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
6606 SourceLocation CC, bool &ICContext) {
6607 E = E->IgnoreParenImpCasts();
6609 if (isa<ConditionalOperator>(E))
6610 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
6612 AnalyzeImplicitConversions(S, E, CC);
6613 if (E->getType() != T)
6614 return CheckImplicitConversion(S, E, T, CC, &ICContext);
6618 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6619 SourceLocation CC, QualType T) {
6620 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
6622 bool Suspicious = false;
6623 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6624 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
6626 // If -Wconversion would have warned about either of the candidates
6627 // for a signedness conversion to the context type...
6628 if (!Suspicious) return;
6630 // ...but it's currently ignored...
6631 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
6634 // ...then check whether it would have warned about either of the
6635 // candidates for a signedness conversion to the condition type.
6636 if (E->getType() == T) return;
6639 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6640 E->getType(), CC, &Suspicious);
6642 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
6643 E->getType(), CC, &Suspicious);
6646 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6647 /// Input argument E is a logical expression.
6648 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6649 if (S.getLangOpts().Bool)
6651 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6654 /// AnalyzeImplicitConversions - Find and report any interesting
6655 /// implicit conversions in the given expression. There are a couple
6656 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
6657 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
6658 QualType T = OrigE->getType();
6659 Expr *E = OrigE->IgnoreParenImpCasts();
6661 if (E->isTypeDependent() || E->isValueDependent())
6664 // For conditional operators, we analyze the arguments as if they
6665 // were being fed directly into the output.
6666 if (isa<ConditionalOperator>(E)) {
6667 ConditionalOperator *CO = cast<ConditionalOperator>(E);
6668 CheckConditionalOperator(S, CO, CC, T);
6672 // Check implicit argument conversions for function calls.
6673 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6674 CheckImplicitArgumentConversions(S, Call, CC);
6676 // Go ahead and check any implicit conversions we might have skipped.
6677 // The non-canonical typecheck is just an optimization;
6678 // CheckImplicitConversion will filter out dead implicit conversions.
6679 if (E->getType() != T)
6680 CheckImplicitConversion(S, E, T, CC);
6682 // Now continue drilling into this expression.
6684 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
6685 if (POE->getResultExpr())
6686 E = POE->getResultExpr();
6689 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6690 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6692 // Skip past explicit casts.
6693 if (isa<ExplicitCastExpr>(E)) {
6694 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
6695 return AnalyzeImplicitConversions(S, E, CC);
6698 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6699 // Do a somewhat different check with comparison operators.
6700 if (BO->isComparisonOp())
6701 return AnalyzeComparison(S, BO);
6703 // And with simple assignments.
6704 if (BO->getOpcode() == BO_Assign)
6705 return AnalyzeAssignment(S, BO);
6708 // These break the otherwise-useful invariant below. Fortunately,
6709 // we don't really need to recurse into them, because any internal
6710 // expressions should have been analyzed already when they were
6711 // built into statements.
6712 if (isa<StmtExpr>(E)) return;
6714 // Don't descend into unevaluated contexts.
6715 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6717 // Now just recurse over the expression's children.
6718 CC = E->getExprLoc();
6719 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6720 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6721 for (Stmt::child_range I = E->children(); I; ++I) {
6722 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6726 if (IsLogicalAndOperator &&
6727 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6728 // Ignore checking string literals that are in logical and operators.
6729 // This is a common pattern for asserts.
6731 AnalyzeImplicitConversions(S, ChildExpr, CC);
6734 if (BO && BO->isLogicalOp()) {
6735 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6736 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6737 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
6739 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6740 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6741 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
6744 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6745 if (U->getOpcode() == UO_LNot)
6746 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
6749 } // end anonymous namespace
6757 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6758 // Returns true when emitting a warning about taking the address of a reference.
6759 static bool CheckForReference(Sema &SemaRef, const Expr *E,
6760 PartialDiagnostic PD) {
6761 E = E->IgnoreParenImpCasts();
6763 const FunctionDecl *FD = nullptr;
6765 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6766 if (!DRE->getDecl()->getType()->isReferenceType())
6768 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6769 if (!M->getMemberDecl()->getType()->isReferenceType())
6771 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6772 if (!Call->getCallReturnType()->isReferenceType())
6774 FD = Call->getDirectCallee();
6779 SemaRef.Diag(E->getExprLoc(), PD);
6781 // If possible, point to location of function.
6783 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6789 // Returns true if the SourceLocation is expanded from any macro body.
6790 // Returns false if the SourceLocation is invalid, is from not in a macro
6791 // expansion, or is from expanded from a top-level macro argument.
6792 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6793 if (Loc.isInvalid())
6796 while (Loc.isMacroID()) {
6797 if (SM.isMacroBodyExpansion(Loc))
6799 Loc = SM.getImmediateMacroCallerLoc(Loc);
6805 /// \brief Diagnose pointers that are always non-null.
6806 /// \param E the expression containing the pointer
6807 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6808 /// compared to a null pointer
6809 /// \param IsEqual True when the comparison is equal to a null pointer
6810 /// \param Range Extra SourceRange to highlight in the diagnostic
6811 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6812 Expr::NullPointerConstantKind NullKind,
6813 bool IsEqual, SourceRange Range) {
6817 // Don't warn inside macros.
6818 if (E->getExprLoc().isMacroID()) {
6819 const SourceManager &SM = getSourceManager();
6820 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6821 IsInAnyMacroBody(SM, Range.getBegin()))
6824 E = E->IgnoreImpCasts();
6826 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6828 if (isa<CXXThisExpr>(E)) {
6829 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6830 : diag::warn_this_bool_conversion;
6831 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6835 bool IsAddressOf = false;
6837 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6838 if (UO->getOpcode() != UO_AddrOf)
6841 E = UO->getSubExpr();
6845 unsigned DiagID = IsCompare
6846 ? diag::warn_address_of_reference_null_compare
6847 : diag::warn_address_of_reference_bool_conversion;
6848 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6850 if (CheckForReference(*this, E, PD)) {
6855 // Expect to find a single Decl. Skip anything more complicated.
6856 ValueDecl *D = nullptr;
6857 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6859 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6860 D = M->getMemberDecl();
6863 // Weak Decls can be null.
6864 if (!D || D->isWeak())
6867 // Check for parameter decl with nonnull attribute
6868 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6869 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6870 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6871 unsigned NumArgs = FD->getNumParams();
6872 llvm::SmallBitVector AttrNonNull(NumArgs);
6873 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6874 if (!NonNull->args_size()) {
6875 AttrNonNull.set(0, NumArgs);
6878 for (unsigned Val : NonNull->args()) {
6881 AttrNonNull.set(Val);
6884 if (!AttrNonNull.empty())
6885 for (unsigned i = 0; i < NumArgs; ++i)
6886 if (FD->getParamDecl(i) == PV &&
6887 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
6889 llvm::raw_string_ostream S(Str);
6890 E->printPretty(S, nullptr, getPrintingPolicy());
6891 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6892 : diag::warn_cast_nonnull_to_bool;
6893 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6894 << Range << IsEqual;
6900 QualType T = D->getType();
6901 const bool IsArray = T->isArrayType();
6902 const bool IsFunction = T->isFunctionType();
6904 // Address of function is used to silence the function warning.
6905 if (IsAddressOf && IsFunction) {
6910 if (!IsAddressOf && !IsFunction && !IsArray)
6913 // Pretty print the expression for the diagnostic.
6915 llvm::raw_string_ostream S(Str);
6916 E->printPretty(S, nullptr, getPrintingPolicy());
6918 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6919 : diag::warn_impcast_pointer_to_bool;
6922 DiagType = AddressOf;
6923 else if (IsFunction)
6924 DiagType = FunctionPointer;
6926 DiagType = ArrayPointer;
6928 llvm_unreachable("Could not determine diagnostic.");
6929 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6930 << Range << IsEqual;
6935 // Suggest '&' to silence the function warning.
6936 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6937 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6939 // Check to see if '()' fixit should be emitted.
6940 QualType ReturnType;
6941 UnresolvedSet<4> NonTemplateOverloads;
6942 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6943 if (ReturnType.isNull())
6947 // There are two cases here. If there is null constant, the only suggest
6948 // for a pointer return type. If the null is 0, then suggest if the return
6949 // type is a pointer or an integer type.
6950 if (!ReturnType->isPointerType()) {
6951 if (NullKind == Expr::NPCK_ZeroExpression ||
6952 NullKind == Expr::NPCK_ZeroLiteral) {
6953 if (!ReturnType->isIntegerType())
6959 } else { // !IsCompare
6960 // For function to bool, only suggest if the function pointer has bool
6962 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6965 Diag(E->getExprLoc(), diag::note_function_to_function_call)
6966 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
6970 /// Diagnoses "dangerous" implicit conversions within the given
6971 /// expression (which is a full expression). Implements -Wconversion
6972 /// and -Wsign-compare.
6974 /// \param CC the "context" location of the implicit conversion, i.e.
6975 /// the most location of the syntactic entity requiring the implicit
6977 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
6978 // Don't diagnose in unevaluated contexts.
6979 if (isUnevaluatedContext())
6982 // Don't diagnose for value- or type-dependent expressions.
6983 if (E->isTypeDependent() || E->isValueDependent())
6986 // Check for array bounds violations in cases where the check isn't triggered
6987 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6988 // ArraySubscriptExpr is on the RHS of a variable initialization.
6989 CheckArrayAccess(E);
6991 // This is not the right CC for (e.g.) a variable initialization.
6992 AnalyzeImplicitConversions(*this, E, CC);
6995 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6996 /// Input argument E is a logical expression.
6997 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
6998 ::CheckBoolLikeConversion(*this, E, CC);
7001 /// Diagnose when expression is an integer constant expression and its evaluation
7002 /// results in integer overflow
7003 void Sema::CheckForIntOverflow (Expr *E) {
7004 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7005 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
7009 /// \brief Visitor for expressions which looks for unsequenced operations on the
7011 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
7012 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7014 /// \brief A tree of sequenced regions within an expression. Two regions are
7015 /// unsequenced if one is an ancestor or a descendent of the other. When we
7016 /// finish processing an expression with sequencing, such as a comma
7017 /// expression, we fold its tree nodes into its parent, since they are
7018 /// unsequenced with respect to nodes we will visit later.
7019 class SequenceTree {
7021 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7022 unsigned Parent : 31;
7025 SmallVector<Value, 8> Values;
7028 /// \brief A region within an expression which may be sequenced with respect
7029 /// to some other region.
7031 explicit Seq(unsigned N) : Index(N) {}
7033 friend class SequenceTree;
7038 SequenceTree() { Values.push_back(Value(0)); }
7039 Seq root() const { return Seq(0); }
7041 /// \brief Create a new sequence of operations, which is an unsequenced
7042 /// subset of \p Parent. This sequence of operations is sequenced with
7043 /// respect to other children of \p Parent.
7044 Seq allocate(Seq Parent) {
7045 Values.push_back(Value(Parent.Index));
7046 return Seq(Values.size() - 1);
7049 /// \brief Merge a sequence of operations into its parent.
7051 Values[S.Index].Merged = true;
7054 /// \brief Determine whether two operations are unsequenced. This operation
7055 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7056 /// should have been merged into its parent as appropriate.
7057 bool isUnsequenced(Seq Cur, Seq Old) {
7058 unsigned C = representative(Cur.Index);
7059 unsigned Target = representative(Old.Index);
7060 while (C >= Target) {
7063 C = Values[C].Parent;
7069 /// \brief Pick a representative for a sequence.
7070 unsigned representative(unsigned K) {
7071 if (Values[K].Merged)
7072 // Perform path compression as we go.
7073 return Values[K].Parent = representative(Values[K].Parent);
7078 /// An object for which we can track unsequenced uses.
7079 typedef NamedDecl *Object;
7081 /// Different flavors of object usage which we track. We only track the
7082 /// least-sequenced usage of each kind.
7084 /// A read of an object. Multiple unsequenced reads are OK.
7086 /// A modification of an object which is sequenced before the value
7087 /// computation of the expression, such as ++n in C++.
7089 /// A modification of an object which is not sequenced before the value
7090 /// computation of the expression, such as n++.
7093 UK_Count = UK_ModAsSideEffect + 1
7097 Usage() : Use(nullptr), Seq() {}
7099 SequenceTree::Seq Seq;
7103 UsageInfo() : Diagnosed(false) {}
7104 Usage Uses[UK_Count];
7105 /// Have we issued a diagnostic for this variable already?
7108 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7111 /// Sequenced regions within the expression.
7113 /// Declaration modifications and references which we have seen.
7114 UsageInfoMap UsageMap;
7115 /// The region we are currently within.
7116 SequenceTree::Seq Region;
7117 /// Filled in with declarations which were modified as a side-effect
7118 /// (that is, post-increment operations).
7119 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7120 /// Expressions to check later. We defer checking these to reduce
7122 SmallVectorImpl<Expr *> &WorkList;
7124 /// RAII object wrapping the visitation of a sequenced subexpression of an
7125 /// expression. At the end of this process, the side-effects of the evaluation
7126 /// become sequenced with respect to the value computation of the result, so
7127 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7129 struct SequencedSubexpression {
7130 SequencedSubexpression(SequenceChecker &Self)
7131 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7132 Self.ModAsSideEffect = &ModAsSideEffect;
7134 ~SequencedSubexpression() {
7135 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7137 UsageInfo &U = Self.UsageMap[MI->first];
7138 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7139 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7140 SideEffectUsage = MI->second;
7142 Self.ModAsSideEffect = OldModAsSideEffect;
7145 SequenceChecker &Self;
7146 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7147 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
7150 /// RAII object wrapping the visitation of a subexpression which we might
7151 /// choose to evaluate as a constant. If any subexpression is evaluated and
7152 /// found to be non-constant, this allows us to suppress the evaluation of
7153 /// the outer expression.
7154 class EvaluationTracker {
7156 EvaluationTracker(SequenceChecker &Self)
7157 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7158 Self.EvalTracker = this;
7160 ~EvaluationTracker() {
7161 Self.EvalTracker = Prev;
7163 Prev->EvalOK &= EvalOK;
7166 bool evaluate(const Expr *E, bool &Result) {
7167 if (!EvalOK || E->isValueDependent())
7169 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7174 SequenceChecker &Self;
7175 EvaluationTracker *Prev;
7179 /// \brief Find the object which is produced by the specified expression,
7181 Object getObject(Expr *E, bool Mod) const {
7182 E = E->IgnoreParenCasts();
7183 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7184 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7185 return getObject(UO->getSubExpr(), Mod);
7186 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7187 if (BO->getOpcode() == BO_Comma)
7188 return getObject(BO->getRHS(), Mod);
7189 if (Mod && BO->isAssignmentOp())
7190 return getObject(BO->getLHS(), Mod);
7191 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7192 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7193 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7194 return ME->getMemberDecl();
7195 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7196 // FIXME: If this is a reference, map through to its value.
7197 return DRE->getDecl();
7201 /// \brief Note that an object was modified or used by an expression.
7202 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7203 Usage &U = UI.Uses[UK];
7204 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7205 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7206 ModAsSideEffect->push_back(std::make_pair(O, U));
7211 /// \brief Check whether a modification or use conflicts with a prior usage.
7212 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7217 const Usage &U = UI.Uses[OtherKind];
7218 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7222 Expr *ModOrUse = Ref;
7223 if (OtherKind == UK_Use)
7224 std::swap(Mod, ModOrUse);
7226 SemaRef.Diag(Mod->getExprLoc(),
7227 IsModMod ? diag::warn_unsequenced_mod_mod
7228 : diag::warn_unsequenced_mod_use)
7229 << O << SourceRange(ModOrUse->getExprLoc());
7230 UI.Diagnosed = true;
7233 void notePreUse(Object O, Expr *Use) {
7234 UsageInfo &U = UsageMap[O];
7235 // Uses conflict with other modifications.
7236 checkUsage(O, U, Use, UK_ModAsValue, false);
7238 void notePostUse(Object O, Expr *Use) {
7239 UsageInfo &U = UsageMap[O];
7240 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7241 addUsage(U, O, Use, UK_Use);
7244 void notePreMod(Object O, Expr *Mod) {
7245 UsageInfo &U = UsageMap[O];
7246 // Modifications conflict with other modifications and with uses.
7247 checkUsage(O, U, Mod, UK_ModAsValue, true);
7248 checkUsage(O, U, Mod, UK_Use, false);
7250 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7251 UsageInfo &U = UsageMap[O];
7252 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7253 addUsage(U, O, Use, UK);
7257 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
7258 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7259 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
7263 void VisitStmt(Stmt *S) {
7264 // Skip all statements which aren't expressions for now.
7267 void VisitExpr(Expr *E) {
7268 // By default, just recurse to evaluated subexpressions.
7272 void VisitCastExpr(CastExpr *E) {
7273 Object O = Object();
7274 if (E->getCastKind() == CK_LValueToRValue)
7275 O = getObject(E->getSubExpr(), false);
7284 void VisitBinComma(BinaryOperator *BO) {
7285 // C++11 [expr.comma]p1:
7286 // Every value computation and side effect associated with the left
7287 // expression is sequenced before every value computation and side
7288 // effect associated with the right expression.
7289 SequenceTree::Seq LHS = Tree.allocate(Region);
7290 SequenceTree::Seq RHS = Tree.allocate(Region);
7291 SequenceTree::Seq OldRegion = Region;
7294 SequencedSubexpression SeqLHS(*this);
7296 Visit(BO->getLHS());
7300 Visit(BO->getRHS());
7304 // Forget that LHS and RHS are sequenced. They are both unsequenced
7305 // with respect to other stuff.
7310 void VisitBinAssign(BinaryOperator *BO) {
7311 // The modification is sequenced after the value computation of the LHS
7312 // and RHS, so check it before inspecting the operands and update the
7314 Object O = getObject(BO->getLHS(), true);
7316 return VisitExpr(BO);
7320 // C++11 [expr.ass]p7:
7321 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7324 // Therefore, for a compound assignment operator, O is considered used
7325 // everywhere except within the evaluation of E1 itself.
7326 if (isa<CompoundAssignOperator>(BO))
7329 Visit(BO->getLHS());
7331 if (isa<CompoundAssignOperator>(BO))
7334 Visit(BO->getRHS());
7336 // C++11 [expr.ass]p1:
7337 // the assignment is sequenced [...] before the value computation of the
7338 // assignment expression.
7339 // C11 6.5.16/3 has no such rule.
7340 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7341 : UK_ModAsSideEffect);
7343 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7344 VisitBinAssign(CAO);
7347 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7348 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7349 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7350 Object O = getObject(UO->getSubExpr(), true);
7352 return VisitExpr(UO);
7355 Visit(UO->getSubExpr());
7356 // C++11 [expr.pre.incr]p1:
7357 // the expression ++x is equivalent to x+=1
7358 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7359 : UK_ModAsSideEffect);
7362 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7363 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7364 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7365 Object O = getObject(UO->getSubExpr(), true);
7367 return VisitExpr(UO);
7370 Visit(UO->getSubExpr());
7371 notePostMod(O, UO, UK_ModAsSideEffect);
7374 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7375 void VisitBinLOr(BinaryOperator *BO) {
7376 // The side-effects of the LHS of an '&&' are sequenced before the
7377 // value computation of the RHS, and hence before the value computation
7378 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7379 // as if they were unconditionally sequenced.
7380 EvaluationTracker Eval(*this);
7382 SequencedSubexpression Sequenced(*this);
7383 Visit(BO->getLHS());
7387 if (Eval.evaluate(BO->getLHS(), Result)) {
7389 Visit(BO->getRHS());
7391 // Check for unsequenced operations in the RHS, treating it as an
7392 // entirely separate evaluation.
7394 // FIXME: If there are operations in the RHS which are unsequenced
7395 // with respect to operations outside the RHS, and those operations
7396 // are unconditionally evaluated, diagnose them.
7397 WorkList.push_back(BO->getRHS());
7400 void VisitBinLAnd(BinaryOperator *BO) {
7401 EvaluationTracker Eval(*this);
7403 SequencedSubexpression Sequenced(*this);
7404 Visit(BO->getLHS());
7408 if (Eval.evaluate(BO->getLHS(), Result)) {
7410 Visit(BO->getRHS());
7412 WorkList.push_back(BO->getRHS());
7416 // Only visit the condition, unless we can be sure which subexpression will
7418 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
7419 EvaluationTracker Eval(*this);
7421 SequencedSubexpression Sequenced(*this);
7422 Visit(CO->getCond());
7426 if (Eval.evaluate(CO->getCond(), Result))
7427 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
7429 WorkList.push_back(CO->getTrueExpr());
7430 WorkList.push_back(CO->getFalseExpr());
7434 void VisitCallExpr(CallExpr *CE) {
7435 // C++11 [intro.execution]p15:
7436 // When calling a function [...], every value computation and side effect
7437 // associated with any argument expression, or with the postfix expression
7438 // designating the called function, is sequenced before execution of every
7439 // expression or statement in the body of the function [and thus before
7440 // the value computation of its result].
7441 SequencedSubexpression Sequenced(*this);
7442 Base::VisitCallExpr(CE);
7444 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7447 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
7448 // This is a call, so all subexpressions are sequenced before the result.
7449 SequencedSubexpression Sequenced(*this);
7451 if (!CCE->isListInitialization())
7452 return VisitExpr(CCE);
7454 // In C++11, list initializations are sequenced.
7455 SmallVector<SequenceTree::Seq, 32> Elts;
7456 SequenceTree::Seq Parent = Region;
7457 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7460 Region = Tree.allocate(Parent);
7461 Elts.push_back(Region);
7465 // Forget that the initializers are sequenced.
7467 for (unsigned I = 0; I < Elts.size(); ++I)
7468 Tree.merge(Elts[I]);
7471 void VisitInitListExpr(InitListExpr *ILE) {
7472 if (!SemaRef.getLangOpts().CPlusPlus11)
7473 return VisitExpr(ILE);
7475 // In C++11, list initializations are sequenced.
7476 SmallVector<SequenceTree::Seq, 32> Elts;
7477 SequenceTree::Seq Parent = Region;
7478 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7479 Expr *E = ILE->getInit(I);
7481 Region = Tree.allocate(Parent);
7482 Elts.push_back(Region);
7486 // Forget that the initializers are sequenced.
7488 for (unsigned I = 0; I < Elts.size(); ++I)
7489 Tree.merge(Elts[I]);
7494 void Sema::CheckUnsequencedOperations(Expr *E) {
7495 SmallVector<Expr *, 8> WorkList;
7496 WorkList.push_back(E);
7497 while (!WorkList.empty()) {
7498 Expr *Item = WorkList.pop_back_val();
7499 SequenceChecker(*this, Item, WorkList);
7503 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7505 CheckImplicitConversions(E, CheckLoc);
7506 CheckUnsequencedOperations(E);
7507 if (!IsConstexpr && !E->isValueDependent())
7508 CheckForIntOverflow(E);
7511 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7512 FieldDecl *BitField,
7514 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7517 /// CheckParmsForFunctionDef - Check that the parameters of the given
7518 /// function are appropriate for the definition of a function. This
7519 /// takes care of any checks that cannot be performed on the
7520 /// declaration itself, e.g., that the types of each of the function
7521 /// parameters are complete.
7522 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7523 ParmVarDecl *const *PEnd,
7524 bool CheckParameterNames) {
7525 bool HasInvalidParm = false;
7526 for (; P != PEnd; ++P) {
7527 ParmVarDecl *Param = *P;
7529 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7530 // function declarator that is part of a function definition of
7531 // that function shall not have incomplete type.
7533 // This is also C++ [dcl.fct]p6.
7534 if (!Param->isInvalidDecl() &&
7535 RequireCompleteType(Param->getLocation(), Param->getType(),
7536 diag::err_typecheck_decl_incomplete_type)) {
7537 Param->setInvalidDecl();
7538 HasInvalidParm = true;
7541 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7542 // declaration of each parameter shall include an identifier.
7543 if (CheckParameterNames &&
7544 Param->getIdentifier() == nullptr &&
7545 !Param->isImplicit() &&
7546 !getLangOpts().CPlusPlus)
7547 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
7550 // If the function declarator is not part of a definition of that
7551 // function, parameters may have incomplete type and may use the [*]
7552 // notation in their sequences of declarator specifiers to specify
7553 // variable length array types.
7554 QualType PType = Param->getOriginalType();
7555 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
7556 if (AT->getSizeModifier() == ArrayType::Star) {
7557 // FIXME: This diagnostic should point the '[*]' if source-location
7558 // information is added for it.
7559 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
7562 PType= AT->getElementType();
7565 // MSVC destroys objects passed by value in the callee. Therefore a
7566 // function definition which takes such a parameter must be able to call the
7567 // object's destructor. However, we don't perform any direct access check
7569 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7571 .areArgsDestroyedLeftToRightInCallee()) {
7572 if (!Param->isInvalidDecl()) {
7573 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7574 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7575 if (!ClassDecl->isInvalidDecl() &&
7576 !ClassDecl->hasIrrelevantDestructor() &&
7577 !ClassDecl->isDependentContext()) {
7578 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7579 MarkFunctionReferenced(Param->getLocation(), Destructor);
7580 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7587 return HasInvalidParm;
7590 /// CheckCastAlign - Implements -Wcast-align, which warns when a
7591 /// pointer cast increases the alignment requirements.
7592 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7593 // This is actually a lot of work to potentially be doing on every
7594 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
7595 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
7598 // Ignore dependent types.
7599 if (T->isDependentType() || Op->getType()->isDependentType())
7602 // Require that the destination be a pointer type.
7603 const PointerType *DestPtr = T->getAs<PointerType>();
7604 if (!DestPtr) return;
7606 // If the destination has alignment 1, we're done.
7607 QualType DestPointee = DestPtr->getPointeeType();
7608 if (DestPointee->isIncompleteType()) return;
7609 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7610 if (DestAlign.isOne()) return;
7612 // Require that the source be a pointer type.
7613 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7614 if (!SrcPtr) return;
7615 QualType SrcPointee = SrcPtr->getPointeeType();
7617 // Whitelist casts from cv void*. We already implicitly
7618 // whitelisted casts to cv void*, since they have alignment 1.
7619 // Also whitelist casts involving incomplete types, which implicitly
7621 if (SrcPointee->isIncompleteType()) return;
7623 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7624 if (SrcAlign >= DestAlign) return;
7626 Diag(TRange.getBegin(), diag::warn_cast_align)
7627 << Op->getType() << T
7628 << static_cast<unsigned>(SrcAlign.getQuantity())
7629 << static_cast<unsigned>(DestAlign.getQuantity())
7630 << TRange << Op->getSourceRange();
7633 static const Type* getElementType(const Expr *BaseExpr) {
7634 const Type* EltType = BaseExpr->getType().getTypePtr();
7635 if (EltType->isAnyPointerType())
7636 return EltType->getPointeeType().getTypePtr();
7637 else if (EltType->isArrayType())
7638 return EltType->getBaseElementTypeUnsafe();
7642 /// \brief Check whether this array fits the idiom of a size-one tail padded
7643 /// array member of a struct.
7645 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
7646 /// commonly used to emulate flexible arrays in C89 code.
7647 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7648 const NamedDecl *ND) {
7649 if (Size != 1 || !ND) return false;
7651 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7652 if (!FD) return false;
7654 // Don't consider sizes resulting from macro expansions or template argument
7655 // substitution to form C89 tail-padded arrays.
7657 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
7659 TypeLoc TL = TInfo->getTypeLoc();
7660 // Look through typedefs.
7661 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7662 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
7663 TInfo = TDL->getTypeSourceInfo();
7666 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7667 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
7668 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7674 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
7675 if (!RD) return false;
7676 if (RD->isUnion()) return false;
7677 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7678 if (!CRD->isStandardLayout()) return false;
7681 // See if this is the last field decl in the record.
7683 while ((D = D->getNextDeclInContext()))
7684 if (isa<FieldDecl>(D))
7689 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7690 const ArraySubscriptExpr *ASE,
7691 bool AllowOnePastEnd, bool IndexNegated) {
7692 IndexExpr = IndexExpr->IgnoreParenImpCasts();
7693 if (IndexExpr->isValueDependent())
7696 const Type *EffectiveType = getElementType(BaseExpr);
7697 BaseExpr = BaseExpr->IgnoreParenCasts();
7698 const ConstantArrayType *ArrayTy =
7699 Context.getAsConstantArrayType(BaseExpr->getType());
7704 if (!IndexExpr->EvaluateAsInt(index, Context))
7709 const NamedDecl *ND = nullptr;
7710 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7711 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7712 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7713 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7715 if (index.isUnsigned() || !index.isNegative()) {
7716 llvm::APInt size = ArrayTy->getSize();
7717 if (!size.isStrictlyPositive())
7720 const Type* BaseType = getElementType(BaseExpr);
7721 if (BaseType != EffectiveType) {
7722 // Make sure we're comparing apples to apples when comparing index to size
7723 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7724 uint64_t array_typesize = Context.getTypeSize(BaseType);
7725 // Handle ptrarith_typesize being zero, such as when casting to void*
7726 if (!ptrarith_typesize) ptrarith_typesize = 1;
7727 if (ptrarith_typesize != array_typesize) {
7728 // There's a cast to a different size type involved
7729 uint64_t ratio = array_typesize / ptrarith_typesize;
7730 // TODO: Be smarter about handling cases where array_typesize is not a
7731 // multiple of ptrarith_typesize
7732 if (ptrarith_typesize * ratio == array_typesize)
7733 size *= llvm::APInt(size.getBitWidth(), ratio);
7737 if (size.getBitWidth() > index.getBitWidth())
7738 index = index.zext(size.getBitWidth());
7739 else if (size.getBitWidth() < index.getBitWidth())
7740 size = size.zext(index.getBitWidth());
7742 // For array subscripting the index must be less than size, but for pointer
7743 // arithmetic also allow the index (offset) to be equal to size since
7744 // computing the next address after the end of the array is legal and
7745 // commonly done e.g. in C++ iterators and range-based for loops.
7746 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
7749 // Also don't warn for arrays of size 1 which are members of some
7750 // structure. These are often used to approximate flexible arrays in C89
7752 if (IsTailPaddedMemberArray(*this, size, ND))
7755 // Suppress the warning if the subscript expression (as identified by the
7756 // ']' location) and the index expression are both from macro expansions
7757 // within a system header.
7759 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7760 ASE->getRBracketLoc());
7761 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7762 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7763 IndexExpr->getLocStart());
7764 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
7769 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
7771 DiagID = diag::warn_array_index_exceeds_bounds;
7773 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7774 PDiag(DiagID) << index.toString(10, true)
7775 << size.toString(10, true)
7776 << (unsigned)size.getLimitedValue(~0U)
7777 << IndexExpr->getSourceRange());
7779 unsigned DiagID = diag::warn_array_index_precedes_bounds;
7781 DiagID = diag::warn_ptr_arith_precedes_bounds;
7782 if (index.isNegative()) index = -index;
7785 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7786 PDiag(DiagID) << index.toString(10, true)
7787 << IndexExpr->getSourceRange());
7791 // Try harder to find a NamedDecl to point at in the note.
7792 while (const ArraySubscriptExpr *ASE =
7793 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7794 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7795 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7796 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7797 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7798 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7802 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7803 PDiag(diag::note_array_index_out_of_bounds)
7804 << ND->getDeclName());
7807 void Sema::CheckArrayAccess(const Expr *expr) {
7808 int AllowOnePastEnd = 0;
7810 expr = expr->IgnoreParenImpCasts();
7811 switch (expr->getStmtClass()) {
7812 case Stmt::ArraySubscriptExprClass: {
7813 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
7814 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
7815 AllowOnePastEnd > 0);
7818 case Stmt::UnaryOperatorClass: {
7819 // Only unwrap the * and & unary operators
7820 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7821 expr = UO->getSubExpr();
7822 switch (UO->getOpcode()) {
7834 case Stmt::ConditionalOperatorClass: {
7835 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7836 if (const Expr *lhs = cond->getLHS())
7837 CheckArrayAccess(lhs);
7838 if (const Expr *rhs = cond->getRHS())
7839 CheckArrayAccess(rhs);
7848 //===--- CHECK: Objective-C retain cycles ----------------------------------//
7851 struct RetainCycleOwner {
7852 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
7858 void setLocsFrom(Expr *e) {
7859 Loc = e->getExprLoc();
7860 Range = e->getSourceRange();
7865 /// Consider whether capturing the given variable can possibly lead to
7867 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
7868 // In ARC, it's captured strongly iff the variable has __strong
7869 // lifetime. In MRR, it's captured strongly if the variable is
7870 // __block and has an appropriate type.
7871 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7874 owner.Variable = var;
7876 owner.setLocsFrom(ref);
7880 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
7882 e = e->IgnoreParens();
7883 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7884 switch (cast->getCastKind()) {
7886 case CK_LValueBitCast:
7887 case CK_LValueToRValue:
7888 case CK_ARCReclaimReturnedObject:
7889 e = cast->getSubExpr();
7897 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7898 ObjCIvarDecl *ivar = ref->getDecl();
7899 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7902 // Try to find a retain cycle in the base.
7903 if (!findRetainCycleOwner(S, ref->getBase(), owner))
7906 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7907 owner.Indirect = true;
7911 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7912 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7913 if (!var) return false;
7914 return considerVariable(var, ref, owner);
7917 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7918 if (member->isArrow()) return false;
7920 // Don't count this as an indirect ownership.
7921 e = member->getBase();
7925 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7926 // Only pay attention to pseudo-objects on property references.
7927 ObjCPropertyRefExpr *pre
7928 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7930 if (!pre) return false;
7931 if (pre->isImplicitProperty()) return false;
7932 ObjCPropertyDecl *property = pre->getExplicitProperty();
7933 if (!property->isRetaining() &&
7934 !(property->getPropertyIvarDecl() &&
7935 property->getPropertyIvarDecl()->getType()
7936 .getObjCLifetime() == Qualifiers::OCL_Strong))
7939 owner.Indirect = true;
7940 if (pre->isSuperReceiver()) {
7941 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7942 if (!owner.Variable)
7944 owner.Loc = pre->getLocation();
7945 owner.Range = pre->getSourceRange();
7948 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7960 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7961 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7962 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7963 Context(Context), Variable(variable), Capturer(nullptr),
7964 VarWillBeReased(false) {}
7965 ASTContext &Context;
7968 bool VarWillBeReased;
7970 void VisitDeclRefExpr(DeclRefExpr *ref) {
7971 if (ref->getDecl() == Variable && !Capturer)
7975 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7976 if (Capturer) return;
7977 Visit(ref->getBase());
7978 if (Capturer && ref->isFreeIvar())
7982 void VisitBlockExpr(BlockExpr *block) {
7983 // Look inside nested blocks
7984 if (block->getBlockDecl()->capturesVariable(Variable))
7985 Visit(block->getBlockDecl()->getBody());
7988 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7989 if (Capturer) return;
7990 if (OVE->getSourceExpr())
7991 Visit(OVE->getSourceExpr());
7993 void VisitBinaryOperator(BinaryOperator *BinOp) {
7994 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7996 Expr *LHS = BinOp->getLHS();
7997 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7998 if (DRE->getDecl() != Variable)
8000 if (Expr *RHS = BinOp->getRHS()) {
8001 RHS = RHS->IgnoreParenCasts();
8004 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8011 /// Check whether the given argument is a block which captures a
8013 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8014 assert(owner.Variable && owner.Loc.isValid());
8016 e = e->IgnoreParenCasts();
8018 // Look through [^{...} copy] and Block_copy(^{...}).
8019 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8020 Selector Cmd = ME->getSelector();
8021 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8022 e = ME->getInstanceReceiver();
8025 e = e->IgnoreParenCasts();
8027 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8028 if (CE->getNumArgs() == 1) {
8029 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
8031 const IdentifierInfo *FnI = Fn->getIdentifier();
8032 if (FnI && FnI->isStr("_Block_copy")) {
8033 e = CE->getArg(0)->IgnoreParenCasts();
8039 BlockExpr *block = dyn_cast<BlockExpr>(e);
8040 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
8043 FindCaptureVisitor visitor(S.Context, owner.Variable);
8044 visitor.Visit(block->getBlockDecl()->getBody());
8045 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
8048 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8049 RetainCycleOwner &owner) {
8051 assert(owner.Variable && owner.Loc.isValid());
8053 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8054 << owner.Variable << capturer->getSourceRange();
8055 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8056 << owner.Indirect << owner.Range;
8059 /// Check for a keyword selector that starts with the word 'add' or
8061 static bool isSetterLikeSelector(Selector sel) {
8062 if (sel.isUnarySelector()) return false;
8064 StringRef str = sel.getNameForSlot(0);
8065 while (!str.empty() && str.front() == '_') str = str.substr(1);
8066 if (str.startswith("set"))
8067 str = str.substr(3);
8068 else if (str.startswith("add")) {
8069 // Specially whitelist 'addOperationWithBlock:'.
8070 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8072 str = str.substr(3);
8077 if (str.empty()) return true;
8078 return !isLowercase(str.front());
8081 /// Check a message send to see if it's likely to cause a retain cycle.
8082 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8083 // Only check instance methods whose selector looks like a setter.
8084 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8087 // Try to find a variable that the receiver is strongly owned by.
8088 RetainCycleOwner owner;
8089 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
8090 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
8093 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8094 owner.Variable = getCurMethodDecl()->getSelfDecl();
8095 owner.Loc = msg->getSuperLoc();
8096 owner.Range = msg->getSuperLoc();
8099 // Check whether the receiver is captured by any of the arguments.
8100 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8101 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8102 return diagnoseRetainCycle(*this, capturer, owner);
8105 /// Check a property assign to see if it's likely to cause a retain cycle.
8106 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8107 RetainCycleOwner owner;
8108 if (!findRetainCycleOwner(*this, receiver, owner))
8111 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8112 diagnoseRetainCycle(*this, capturer, owner);
8115 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8116 RetainCycleOwner Owner;
8117 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
8120 // Because we don't have an expression for the variable, we have to set the
8121 // location explicitly here.
8122 Owner.Loc = Var->getLocation();
8123 Owner.Range = Var->getSourceRange();
8125 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8126 diagnoseRetainCycle(*this, Capturer, Owner);
8129 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8130 Expr *RHS, bool isProperty) {
8131 // Check if RHS is an Objective-C object literal, which also can get
8132 // immediately zapped in a weak reference. Note that we explicitly
8133 // allow ObjCStringLiterals, since those are designed to never really die.
8134 RHS = RHS->IgnoreParenImpCasts();
8136 // This enum needs to match with the 'select' in
8137 // warn_objc_arc_literal_assign (off-by-1).
8138 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8139 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8142 S.Diag(Loc, diag::warn_arc_literal_assign)
8144 << (isProperty ? 0 : 1)
8145 << RHS->getSourceRange();
8150 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8151 Qualifiers::ObjCLifetime LT,
8152 Expr *RHS, bool isProperty) {
8153 // Strip off any implicit cast added to get to the one ARC-specific.
8154 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8155 if (cast->getCastKind() == CK_ARCConsumeObject) {
8156 S.Diag(Loc, diag::warn_arc_retained_assign)
8157 << (LT == Qualifiers::OCL_ExplicitNone)
8158 << (isProperty ? 0 : 1)
8159 << RHS->getSourceRange();
8162 RHS = cast->getSubExpr();
8165 if (LT == Qualifiers::OCL_Weak &&
8166 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8172 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8173 QualType LHS, Expr *RHS) {
8174 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8176 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8179 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8185 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8186 Expr *LHS, Expr *RHS) {
8188 // PropertyRef on LHS type need be directly obtained from
8189 // its declaration as it has a PseudoType.
8190 ObjCPropertyRefExpr *PRE
8191 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8192 if (PRE && !PRE->isImplicitProperty()) {
8193 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8195 LHSType = PD->getType();
8198 if (LHSType.isNull())
8199 LHSType = LHS->getType();
8201 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8203 if (LT == Qualifiers::OCL_Weak) {
8204 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
8205 getCurFunction()->markSafeWeakUse(LHS);
8208 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8211 // FIXME. Check for other life times.
8212 if (LT != Qualifiers::OCL_None)
8216 if (PRE->isImplicitProperty())
8218 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8222 unsigned Attributes = PD->getPropertyAttributes();
8223 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
8224 // when 'assign' attribute was not explicitly specified
8225 // by user, ignore it and rely on property type itself
8226 // for lifetime info.
8227 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8228 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8229 LHSType->isObjCRetainableType())
8232 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8233 if (cast->getCastKind() == CK_ARCConsumeObject) {
8234 Diag(Loc, diag::warn_arc_retained_property_assign)
8235 << RHS->getSourceRange();
8238 RHS = cast->getSubExpr();
8241 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
8242 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8248 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8251 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8252 SourceLocation StmtLoc,
8253 const NullStmt *Body) {
8254 // Do not warn if the body is a macro that expands to nothing, e.g:
8260 if (Body->hasLeadingEmptyMacro())
8263 // Get line numbers of statement and body.
8264 bool StmtLineInvalid;
8265 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8267 if (StmtLineInvalid)
8270 bool BodyLineInvalid;
8271 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8273 if (BodyLineInvalid)
8276 // Warn if null statement and body are on the same line.
8277 if (StmtLine != BodyLine)
8282 } // Unnamed namespace
8284 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8287 // Since this is a syntactic check, don't emit diagnostic for template
8288 // instantiations, this just adds noise.
8289 if (CurrentInstantiationScope)
8292 // The body should be a null statement.
8293 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8297 // Do the usual checks.
8298 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8301 Diag(NBody->getSemiLoc(), DiagID);
8302 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8305 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8306 const Stmt *PossibleBody) {
8307 assert(!CurrentInstantiationScope); // Ensured by caller
8309 SourceLocation StmtLoc;
8312 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8313 StmtLoc = FS->getRParenLoc();
8314 Body = FS->getBody();
8315 DiagID = diag::warn_empty_for_body;
8316 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8317 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8318 Body = WS->getBody();
8319 DiagID = diag::warn_empty_while_body;
8321 return; // Neither `for' nor `while'.
8323 // The body should be a null statement.
8324 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8328 // Skip expensive checks if diagnostic is disabled.
8329 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
8332 // Do the usual checks.
8333 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8336 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8337 // noise level low, emit diagnostics only if for/while is followed by a
8338 // CompoundStmt, e.g.:
8339 // for (int i = 0; i < n; i++);
8343 // or if for/while is followed by a statement with more indentation
8344 // than for/while itself:
8345 // for (int i = 0; i < n; i++);
8347 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8348 if (!ProbableTypo) {
8349 bool BodyColInvalid;
8350 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8351 PossibleBody->getLocStart(),
8356 bool StmtColInvalid;
8357 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8363 if (BodyCol > StmtCol)
8364 ProbableTypo = true;
8368 Diag(NBody->getSemiLoc(), DiagID);
8369 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8373 //===--- CHECK: Warn on self move with std::move. -------------------------===//
8375 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8376 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8377 SourceLocation OpLoc) {
8379 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8382 if (!ActiveTemplateInstantiations.empty())
8385 // Strip parens and casts away.
8386 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8387 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8389 // Check for a call expression
8390 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8391 if (!CE || CE->getNumArgs() != 1)
8394 // Check for a call to std::move
8395 const FunctionDecl *FD = CE->getDirectCallee();
8396 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8397 !FD->getIdentifier()->isStr("move"))
8400 // Get argument from std::move
8401 RHSExpr = CE->getArg(0);
8403 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8404 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8406 // Two DeclRefExpr's, check that the decls are the same.
8407 if (LHSDeclRef && RHSDeclRef) {
8408 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8410 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8411 RHSDeclRef->getDecl()->getCanonicalDecl())
8414 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8415 << LHSExpr->getSourceRange()
8416 << RHSExpr->getSourceRange();
8420 // Member variables require a different approach to check for self moves.
8421 // MemberExpr's are the same if every nested MemberExpr refers to the same
8422 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8423 // the base Expr's are CXXThisExpr's.
8424 const Expr *LHSBase = LHSExpr;
8425 const Expr *RHSBase = RHSExpr;
8426 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8427 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8428 if (!LHSME || !RHSME)
8431 while (LHSME && RHSME) {
8432 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8433 RHSME->getMemberDecl()->getCanonicalDecl())
8436 LHSBase = LHSME->getBase();
8437 RHSBase = RHSME->getBase();
8438 LHSME = dyn_cast<MemberExpr>(LHSBase);
8439 RHSME = dyn_cast<MemberExpr>(RHSBase);
8442 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8443 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8444 if (LHSDeclRef && RHSDeclRef) {
8445 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8447 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8448 RHSDeclRef->getDecl()->getCanonicalDecl())
8451 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8452 << LHSExpr->getSourceRange()
8453 << RHSExpr->getSourceRange();
8457 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8458 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8459 << LHSExpr->getSourceRange()
8460 << RHSExpr->getSourceRange();
8463 //===--- Layout compatibility ----------------------------------------------//
8467 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8469 /// \brief Check if two enumeration types are layout-compatible.
8470 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8471 // C++11 [dcl.enum] p8:
8472 // Two enumeration types are layout-compatible if they have the same
8474 return ED1->isComplete() && ED2->isComplete() &&
8475 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8478 /// \brief Check if two fields are layout-compatible.
8479 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8480 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8483 if (Field1->isBitField() != Field2->isBitField())
8486 if (Field1->isBitField()) {
8487 // Make sure that the bit-fields are the same length.
8488 unsigned Bits1 = Field1->getBitWidthValue(C);
8489 unsigned Bits2 = Field2->getBitWidthValue(C);
8498 /// \brief Check if two standard-layout structs are layout-compatible.
8499 /// (C++11 [class.mem] p17)
8500 bool isLayoutCompatibleStruct(ASTContext &C,
8503 // If both records are C++ classes, check that base classes match.
8504 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8505 // If one of records is a CXXRecordDecl we are in C++ mode,
8506 // thus the other one is a CXXRecordDecl, too.
8507 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8508 // Check number of base classes.
8509 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8512 // Check the base classes.
8513 for (CXXRecordDecl::base_class_const_iterator
8514 Base1 = D1CXX->bases_begin(),
8515 BaseEnd1 = D1CXX->bases_end(),
8516 Base2 = D2CXX->bases_begin();
8519 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8522 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8523 // If only RD2 is a C++ class, it should have zero base classes.
8524 if (D2CXX->getNumBases() > 0)
8528 // Check the fields.
8529 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8530 Field2End = RD2->field_end(),
8531 Field1 = RD1->field_begin(),
8532 Field1End = RD1->field_end();
8533 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8534 if (!isLayoutCompatible(C, *Field1, *Field2))
8537 if (Field1 != Field1End || Field2 != Field2End)
8543 /// \brief Check if two standard-layout unions are layout-compatible.
8544 /// (C++11 [class.mem] p18)
8545 bool isLayoutCompatibleUnion(ASTContext &C,
8548 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
8549 for (auto *Field2 : RD2->fields())
8550 UnmatchedFields.insert(Field2);
8552 for (auto *Field1 : RD1->fields()) {
8553 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8554 I = UnmatchedFields.begin(),
8555 E = UnmatchedFields.end();
8557 for ( ; I != E; ++I) {
8558 if (isLayoutCompatible(C, Field1, *I)) {
8559 bool Result = UnmatchedFields.erase(*I);
8569 return UnmatchedFields.empty();
8572 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8573 if (RD1->isUnion() != RD2->isUnion())
8577 return isLayoutCompatibleUnion(C, RD1, RD2);
8579 return isLayoutCompatibleStruct(C, RD1, RD2);
8582 /// \brief Check if two types are layout-compatible in C++11 sense.
8583 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8584 if (T1.isNull() || T2.isNull())
8587 // C++11 [basic.types] p11:
8588 // If two types T1 and T2 are the same type, then T1 and T2 are
8589 // layout-compatible types.
8590 if (C.hasSameType(T1, T2))
8593 T1 = T1.getCanonicalType().getUnqualifiedType();
8594 T2 = T2.getCanonicalType().getUnqualifiedType();
8596 const Type::TypeClass TC1 = T1->getTypeClass();
8597 const Type::TypeClass TC2 = T2->getTypeClass();
8602 if (TC1 == Type::Enum) {
8603 return isLayoutCompatible(C,
8604 cast<EnumType>(T1)->getDecl(),
8605 cast<EnumType>(T2)->getDecl());
8606 } else if (TC1 == Type::Record) {
8607 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8610 return isLayoutCompatible(C,
8611 cast<RecordType>(T1)->getDecl(),
8612 cast<RecordType>(T2)->getDecl());
8619 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8622 /// \brief Given a type tag expression find the type tag itself.
8624 /// \param TypeExpr Type tag expression, as it appears in user's code.
8626 /// \param VD Declaration of an identifier that appears in a type tag.
8628 /// \param MagicValue Type tag magic value.
8629 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8630 const ValueDecl **VD, uint64_t *MagicValue) {
8635 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8637 switch (TypeExpr->getStmtClass()) {
8638 case Stmt::UnaryOperatorClass: {
8639 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8640 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8641 TypeExpr = UO->getSubExpr();
8647 case Stmt::DeclRefExprClass: {
8648 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8649 *VD = DRE->getDecl();
8653 case Stmt::IntegerLiteralClass: {
8654 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8655 llvm::APInt MagicValueAPInt = IL->getValue();
8656 if (MagicValueAPInt.getActiveBits() <= 64) {
8657 *MagicValue = MagicValueAPInt.getZExtValue();
8663 case Stmt::BinaryConditionalOperatorClass:
8664 case Stmt::ConditionalOperatorClass: {
8665 const AbstractConditionalOperator *ACO =
8666 cast<AbstractConditionalOperator>(TypeExpr);
8668 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8670 TypeExpr = ACO->getTrueExpr();
8672 TypeExpr = ACO->getFalseExpr();
8678 case Stmt::BinaryOperatorClass: {
8679 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8680 if (BO->getOpcode() == BO_Comma) {
8681 TypeExpr = BO->getRHS();
8693 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
8695 /// \param TypeExpr Expression that specifies a type tag.
8697 /// \param MagicValues Registered magic values.
8699 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8702 /// \param TypeInfo Information about the corresponding C type.
8704 /// \returns true if the corresponding C type was found.
8705 bool GetMatchingCType(
8706 const IdentifierInfo *ArgumentKind,
8707 const Expr *TypeExpr, const ASTContext &Ctx,
8708 const llvm::DenseMap<Sema::TypeTagMagicValue,
8709 Sema::TypeTagData> *MagicValues,
8710 bool &FoundWrongKind,
8711 Sema::TypeTagData &TypeInfo) {
8712 FoundWrongKind = false;
8714 // Variable declaration that has type_tag_for_datatype attribute.
8715 const ValueDecl *VD = nullptr;
8717 uint64_t MagicValue;
8719 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8723 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
8724 if (I->getArgumentKind() != ArgumentKind) {
8725 FoundWrongKind = true;
8728 TypeInfo.Type = I->getMatchingCType();
8729 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8730 TypeInfo.MustBeNull = I->getMustBeNull();
8739 llvm::DenseMap<Sema::TypeTagMagicValue,
8740 Sema::TypeTagData>::const_iterator I =
8741 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8742 if (I == MagicValues->end())
8745 TypeInfo = I->second;
8748 } // unnamed namespace
8750 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8751 uint64_t MagicValue, QualType Type,
8752 bool LayoutCompatible,
8754 if (!TypeTagForDatatypeMagicValues)
8755 TypeTagForDatatypeMagicValues.reset(
8756 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8758 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8759 (*TypeTagForDatatypeMagicValues)[Magic] =
8760 TypeTagData(Type, LayoutCompatible, MustBeNull);
8764 bool IsSameCharType(QualType T1, QualType T2) {
8765 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8769 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8773 BuiltinType::Kind T1Kind = BT1->getKind();
8774 BuiltinType::Kind T2Kind = BT2->getKind();
8776 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8777 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8778 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8779 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8781 } // unnamed namespace
8783 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8784 const Expr * const *ExprArgs) {
8785 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8786 bool IsPointerAttr = Attr->getIsPointer();
8788 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8789 bool FoundWrongKind;
8790 TypeTagData TypeInfo;
8791 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8792 TypeTagForDatatypeMagicValues.get(),
8793 FoundWrongKind, TypeInfo)) {
8795 Diag(TypeTagExpr->getExprLoc(),
8796 diag::warn_type_tag_for_datatype_wrong_kind)
8797 << TypeTagExpr->getSourceRange();
8801 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8802 if (IsPointerAttr) {
8803 // Skip implicit cast of pointer to `void *' (as a function argument).
8804 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
8805 if (ICE->getType()->isVoidPointerType() &&
8806 ICE->getCastKind() == CK_BitCast)
8807 ArgumentExpr = ICE->getSubExpr();
8809 QualType ArgumentType = ArgumentExpr->getType();
8811 // Passing a `void*' pointer shouldn't trigger a warning.
8812 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8815 if (TypeInfo.MustBeNull) {
8816 // Type tag with matching void type requires a null pointer.
8817 if (!ArgumentExpr->isNullPointerConstant(Context,
8818 Expr::NPC_ValueDependentIsNotNull)) {
8819 Diag(ArgumentExpr->getExprLoc(),
8820 diag::warn_type_safety_null_pointer_required)
8821 << ArgumentKind->getName()
8822 << ArgumentExpr->getSourceRange()
8823 << TypeTagExpr->getSourceRange();
8828 QualType RequiredType = TypeInfo.Type;
8830 RequiredType = Context.getPointerType(RequiredType);
8832 bool mismatch = false;
8833 if (!TypeInfo.LayoutCompatible) {
8834 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8836 // C++11 [basic.fundamental] p1:
8837 // Plain char, signed char, and unsigned char are three distinct types.
8839 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8840 // char' depending on the current char signedness mode.
8842 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8843 RequiredType->getPointeeType())) ||
8844 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8848 mismatch = !isLayoutCompatible(Context,
8849 ArgumentType->getPointeeType(),
8850 RequiredType->getPointeeType());
8852 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8855 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
8856 << ArgumentType << ArgumentKind
8857 << TypeInfo.LayoutCompatible << RequiredType
8858 << ArgumentExpr->getSourceRange()
8859 << TypeTagExpr->getSourceRange();