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(S.Context);
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());
205 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
228 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
230 ExprResult TheCallResult(TheCall);
232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
247 ICEArguments &= ~(1 << ArgNo);
251 case Builtin::BI__builtin___CFStringMakeConstantString:
252 assert(TheCall->getNumArgs() == 1 &&
253 "Wrong # arguments to builtin CFStringMakeConstantString");
254 if (CheckObjCString(TheCall->getArg(0)))
257 case Builtin::BI__builtin_stdarg_start:
258 case Builtin::BI__builtin_va_start:
259 if (SemaBuiltinVAStart(TheCall))
262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
270 if (SemaBuiltinVAStart(TheCall))
276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
282 if (SemaBuiltinUnorderedCompare(TheCall))
285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
294 if (SemaBuiltinFPClassification(TheCall, 1))
297 case Builtin::BI__builtin_shufflevector:
298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
301 case Builtin::BI__builtin_prefetch:
302 if (SemaBuiltinPrefetch(TheCall))
305 case Builtin::BI__assume:
306 case Builtin::BI__builtin_assume:
307 if (SemaBuiltinAssume(TheCall))
310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
314 case Builtin::BI__builtin_object_size:
315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
322 case Builtin::BI__builtin_setjmp:
323 if (SemaBuiltinSetjmp(TheCall))
326 case Builtin::BI_setjmp:
327 case Builtin::BI_setjmpex:
328 if (checkArgCount(*this, TheCall, 1))
332 case Builtin::BI__builtin_classify_type:
333 if (checkArgCount(*this, TheCall, 1)) return true;
334 TheCall->setType(Context.IntTy);
336 case Builtin::BI__builtin_constant_p:
337 if (checkArgCount(*this, TheCall, 1)) return true;
338 TheCall->setType(Context.IntTy);
340 case Builtin::BI__sync_fetch_and_add:
341 case Builtin::BI__sync_fetch_and_add_1:
342 case Builtin::BI__sync_fetch_and_add_2:
343 case Builtin::BI__sync_fetch_and_add_4:
344 case Builtin::BI__sync_fetch_and_add_8:
345 case Builtin::BI__sync_fetch_and_add_16:
346 case Builtin::BI__sync_fetch_and_sub:
347 case Builtin::BI__sync_fetch_and_sub_1:
348 case Builtin::BI__sync_fetch_and_sub_2:
349 case Builtin::BI__sync_fetch_and_sub_4:
350 case Builtin::BI__sync_fetch_and_sub_8:
351 case Builtin::BI__sync_fetch_and_sub_16:
352 case Builtin::BI__sync_fetch_and_or:
353 case Builtin::BI__sync_fetch_and_or_1:
354 case Builtin::BI__sync_fetch_and_or_2:
355 case Builtin::BI__sync_fetch_and_or_4:
356 case Builtin::BI__sync_fetch_and_or_8:
357 case Builtin::BI__sync_fetch_and_or_16:
358 case Builtin::BI__sync_fetch_and_and:
359 case Builtin::BI__sync_fetch_and_and_1:
360 case Builtin::BI__sync_fetch_and_and_2:
361 case Builtin::BI__sync_fetch_and_and_4:
362 case Builtin::BI__sync_fetch_and_and_8:
363 case Builtin::BI__sync_fetch_and_and_16:
364 case Builtin::BI__sync_fetch_and_xor:
365 case Builtin::BI__sync_fetch_and_xor_1:
366 case Builtin::BI__sync_fetch_and_xor_2:
367 case Builtin::BI__sync_fetch_and_xor_4:
368 case Builtin::BI__sync_fetch_and_xor_8:
369 case Builtin::BI__sync_fetch_and_xor_16:
370 case Builtin::BI__sync_fetch_and_nand:
371 case Builtin::BI__sync_fetch_and_nand_1:
372 case Builtin::BI__sync_fetch_and_nand_2:
373 case Builtin::BI__sync_fetch_and_nand_4:
374 case Builtin::BI__sync_fetch_and_nand_8:
375 case Builtin::BI__sync_fetch_and_nand_16:
376 case Builtin::BI__sync_add_and_fetch:
377 case Builtin::BI__sync_add_and_fetch_1:
378 case Builtin::BI__sync_add_and_fetch_2:
379 case Builtin::BI__sync_add_and_fetch_4:
380 case Builtin::BI__sync_add_and_fetch_8:
381 case Builtin::BI__sync_add_and_fetch_16:
382 case Builtin::BI__sync_sub_and_fetch:
383 case Builtin::BI__sync_sub_and_fetch_1:
384 case Builtin::BI__sync_sub_and_fetch_2:
385 case Builtin::BI__sync_sub_and_fetch_4:
386 case Builtin::BI__sync_sub_and_fetch_8:
387 case Builtin::BI__sync_sub_and_fetch_16:
388 case Builtin::BI__sync_and_and_fetch:
389 case Builtin::BI__sync_and_and_fetch_1:
390 case Builtin::BI__sync_and_and_fetch_2:
391 case Builtin::BI__sync_and_and_fetch_4:
392 case Builtin::BI__sync_and_and_fetch_8:
393 case Builtin::BI__sync_and_and_fetch_16:
394 case Builtin::BI__sync_or_and_fetch:
395 case Builtin::BI__sync_or_and_fetch_1:
396 case Builtin::BI__sync_or_and_fetch_2:
397 case Builtin::BI__sync_or_and_fetch_4:
398 case Builtin::BI__sync_or_and_fetch_8:
399 case Builtin::BI__sync_or_and_fetch_16:
400 case Builtin::BI__sync_xor_and_fetch:
401 case Builtin::BI__sync_xor_and_fetch_1:
402 case Builtin::BI__sync_xor_and_fetch_2:
403 case Builtin::BI__sync_xor_and_fetch_4:
404 case Builtin::BI__sync_xor_and_fetch_8:
405 case Builtin::BI__sync_xor_and_fetch_16:
406 case Builtin::BI__sync_nand_and_fetch:
407 case Builtin::BI__sync_nand_and_fetch_1:
408 case Builtin::BI__sync_nand_and_fetch_2:
409 case Builtin::BI__sync_nand_and_fetch_4:
410 case Builtin::BI__sync_nand_and_fetch_8:
411 case Builtin::BI__sync_nand_and_fetch_16:
412 case Builtin::BI__sync_val_compare_and_swap:
413 case Builtin::BI__sync_val_compare_and_swap_1:
414 case Builtin::BI__sync_val_compare_and_swap_2:
415 case Builtin::BI__sync_val_compare_and_swap_4:
416 case Builtin::BI__sync_val_compare_and_swap_8:
417 case Builtin::BI__sync_val_compare_and_swap_16:
418 case Builtin::BI__sync_bool_compare_and_swap:
419 case Builtin::BI__sync_bool_compare_and_swap_1:
420 case Builtin::BI__sync_bool_compare_and_swap_2:
421 case Builtin::BI__sync_bool_compare_and_swap_4:
422 case Builtin::BI__sync_bool_compare_and_swap_8:
423 case Builtin::BI__sync_bool_compare_and_swap_16:
424 case Builtin::BI__sync_lock_test_and_set:
425 case Builtin::BI__sync_lock_test_and_set_1:
426 case Builtin::BI__sync_lock_test_and_set_2:
427 case Builtin::BI__sync_lock_test_and_set_4:
428 case Builtin::BI__sync_lock_test_and_set_8:
429 case Builtin::BI__sync_lock_test_and_set_16:
430 case Builtin::BI__sync_lock_release:
431 case Builtin::BI__sync_lock_release_1:
432 case Builtin::BI__sync_lock_release_2:
433 case Builtin::BI__sync_lock_release_4:
434 case Builtin::BI__sync_lock_release_8:
435 case Builtin::BI__sync_lock_release_16:
436 case Builtin::BI__sync_swap:
437 case Builtin::BI__sync_swap_1:
438 case Builtin::BI__sync_swap_2:
439 case Builtin::BI__sync_swap_4:
440 case Builtin::BI__sync_swap_8:
441 case Builtin::BI__sync_swap_16:
442 return SemaBuiltinAtomicOverloaded(TheCallResult);
443 #define BUILTIN(ID, TYPE, ATTRS)
444 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
445 case Builtin::BI##ID: \
446 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
447 #include "clang/Basic/Builtins.def"
448 case Builtin::BI__builtin_annotation:
449 if (SemaBuiltinAnnotation(*this, TheCall))
452 case Builtin::BI__builtin_addressof:
453 if (SemaBuiltinAddressof(*this, TheCall))
456 case Builtin::BI__builtin_operator_new:
457 case Builtin::BI__builtin_operator_delete:
458 if (!getLangOpts().CPlusPlus) {
459 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
460 << (BuiltinID == Builtin::BI__builtin_operator_new
461 ? "__builtin_operator_new"
462 : "__builtin_operator_delete")
466 // CodeGen assumes it can find the global new and delete to call,
467 // so ensure that they are declared.
468 DeclareGlobalNewDelete();
471 // check secure string manipulation functions where overflows
472 // are detectable at compile time
473 case Builtin::BI__builtin___memcpy_chk:
474 case Builtin::BI__builtin___memmove_chk:
475 case Builtin::BI__builtin___memset_chk:
476 case Builtin::BI__builtin___strlcat_chk:
477 case Builtin::BI__builtin___strlcpy_chk:
478 case Builtin::BI__builtin___strncat_chk:
479 case Builtin::BI__builtin___strncpy_chk:
480 case Builtin::BI__builtin___stpncpy_chk:
481 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
483 case Builtin::BI__builtin___memccpy_chk:
484 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
486 case Builtin::BI__builtin___snprintf_chk:
487 case Builtin::BI__builtin___vsnprintf_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
491 case Builtin::BI__builtin_call_with_static_chain:
492 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
496 case Builtin::BI__exception_code:
497 case Builtin::BI_exception_code: {
498 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
499 diag::err_seh___except_block))
503 case Builtin::BI__exception_info:
504 case Builtin::BI_exception_info: {
505 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
506 diag::err_seh___except_filter))
511 case Builtin::BI__GetExceptionInfo:
512 if (checkArgCount(*this, TheCall, 1))
515 if (CheckCXXThrowOperand(
516 TheCall->getLocStart(),
517 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
521 TheCall->setType(Context.VoidPtrTy);
526 // Since the target specific builtins for each arch overlap, only check those
527 // of the arch we are compiling for.
528 if (BuiltinID >= Builtin::FirstTSBuiltin) {
529 switch (Context.getTargetInfo().getTriple().getArch()) {
530 case llvm::Triple::arm:
531 case llvm::Triple::armeb:
532 case llvm::Triple::thumb:
533 case llvm::Triple::thumbeb:
534 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
537 case llvm::Triple::aarch64:
538 case llvm::Triple::aarch64_be:
539 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
542 case llvm::Triple::mips:
543 case llvm::Triple::mipsel:
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
549 case llvm::Triple::systemz:
550 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
558 case llvm::Triple::ppc:
559 case llvm::Triple::ppc64:
560 case llvm::Triple::ppc64le:
561 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
569 return TheCallResult;
572 // Get the valid immediate range for the specified NEON type code.
573 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
574 NeonTypeFlags Type(t);
575 int IsQuad = ForceQuad ? true : Type.isQuad();
576 switch (Type.getEltType()) {
577 case NeonTypeFlags::Int8:
578 case NeonTypeFlags::Poly8:
579 return shift ? 7 : (8 << IsQuad) - 1;
580 case NeonTypeFlags::Int16:
581 case NeonTypeFlags::Poly16:
582 return shift ? 15 : (4 << IsQuad) - 1;
583 case NeonTypeFlags::Int32:
584 return shift ? 31 : (2 << IsQuad) - 1;
585 case NeonTypeFlags::Int64:
586 case NeonTypeFlags::Poly64:
587 return shift ? 63 : (1 << IsQuad) - 1;
588 case NeonTypeFlags::Poly128:
589 return shift ? 127 : (1 << IsQuad) - 1;
590 case NeonTypeFlags::Float16:
591 assert(!shift && "cannot shift float types!");
592 return (4 << IsQuad) - 1;
593 case NeonTypeFlags::Float32:
594 assert(!shift && "cannot shift float types!");
595 return (2 << IsQuad) - 1;
596 case NeonTypeFlags::Float64:
597 assert(!shift && "cannot shift float types!");
598 return (1 << IsQuad) - 1;
600 llvm_unreachable("Invalid NeonTypeFlag!");
603 /// getNeonEltType - Return the QualType corresponding to the elements of
604 /// the vector type specified by the NeonTypeFlags. This is used to check
605 /// the pointer arguments for Neon load/store intrinsics.
606 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
607 bool IsPolyUnsigned, bool IsInt64Long) {
608 switch (Flags.getEltType()) {
609 case NeonTypeFlags::Int8:
610 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
611 case NeonTypeFlags::Int16:
612 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
613 case NeonTypeFlags::Int32:
614 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
615 case NeonTypeFlags::Int64:
617 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
619 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
620 : Context.LongLongTy;
621 case NeonTypeFlags::Poly8:
622 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
623 case NeonTypeFlags::Poly16:
624 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
625 case NeonTypeFlags::Poly64:
627 return Context.UnsignedLongTy;
629 return Context.UnsignedLongLongTy;
630 case NeonTypeFlags::Poly128:
632 case NeonTypeFlags::Float16:
633 return Context.HalfTy;
634 case NeonTypeFlags::Float32:
635 return Context.FloatTy;
636 case NeonTypeFlags::Float64:
637 return Context.DoubleTy;
639 llvm_unreachable("Invalid NeonTypeFlag!");
642 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
647 bool HasConstPtr = false;
649 #define GET_NEON_OVERLOAD_CHECK
650 #include "clang/Basic/arm_neon.inc"
651 #undef GET_NEON_OVERLOAD_CHECK
654 // For NEON intrinsics which are overloaded on vector element type, validate
655 // the immediate which specifies which variant to emit.
656 unsigned ImmArg = TheCall->getNumArgs()-1;
658 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
661 TV = Result.getLimitedValue(64);
662 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
663 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
664 << TheCall->getArg(ImmArg)->getSourceRange();
667 if (PtrArgNum >= 0) {
668 // Check that pointer arguments have the specified type.
669 Expr *Arg = TheCall->getArg(PtrArgNum);
670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
671 Arg = ICE->getSubExpr();
672 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
673 QualType RHSTy = RHS.get()->getType();
675 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
676 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
678 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
680 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
682 EltTy = EltTy.withConst();
683 QualType LHSTy = Context.getPointerType(EltTy);
684 AssignConvertType ConvTy;
685 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
688 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
689 RHS.get(), AA_Assigning))
693 // For NEON intrinsics which take an immediate value as part of the
694 // instruction, range check them here.
695 unsigned i = 0, l = 0, u = 0;
699 #define GET_NEON_IMMEDIATE_CHECK
700 #include "clang/Basic/arm_neon.inc"
701 #undef GET_NEON_IMMEDIATE_CHECK
704 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
707 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
709 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
710 BuiltinID == ARM::BI__builtin_arm_ldaex ||
711 BuiltinID == ARM::BI__builtin_arm_strex ||
712 BuiltinID == ARM::BI__builtin_arm_stlex ||
713 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
714 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
715 BuiltinID == AArch64::BI__builtin_arm_strex ||
716 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
717 "unexpected ARM builtin");
718 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
719 BuiltinID == ARM::BI__builtin_arm_ldaex ||
720 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
721 BuiltinID == AArch64::BI__builtin_arm_ldaex;
723 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
725 // Ensure that we have the proper number of arguments.
726 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
729 // Inspect the pointer argument of the atomic builtin. This should always be
730 // a pointer type, whose element is an integral scalar or pointer type.
731 // Because it is a pointer type, we don't have to worry about any implicit
733 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
734 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
735 if (PointerArgRes.isInvalid())
737 PointerArg = PointerArgRes.get();
739 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
742 << PointerArg->getType() << PointerArg->getSourceRange();
746 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
747 // task is to insert the appropriate casts into the AST. First work out just
748 // what the appropriate type is.
749 QualType ValType = pointerType->getPointeeType();
750 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
754 // Issue a warning if the cast is dodgy.
755 CastKind CastNeeded = CK_NoOp;
756 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
757 CastNeeded = CK_BitCast;
758 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
759 << PointerArg->getType()
760 << Context.getPointerType(AddrType)
761 << AA_Passing << PointerArg->getSourceRange();
764 // Finally, do the cast and replace the argument with the corrected version.
765 AddrType = Context.getPointerType(AddrType);
766 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
767 if (PointerArgRes.isInvalid())
769 PointerArg = PointerArgRes.get();
771 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
773 // In general, we allow ints, floats and pointers to be loaded and stored.
774 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
775 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
776 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
777 << PointerArg->getType() << PointerArg->getSourceRange();
781 // But ARM doesn't have instructions to deal with 128-bit versions.
782 if (Context.getTypeSize(ValType) > MaxWidth) {
783 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
784 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
785 << PointerArg->getType() << PointerArg->getSourceRange();
789 switch (ValType.getObjCLifetime()) {
790 case Qualifiers::OCL_None:
791 case Qualifiers::OCL_ExplicitNone:
795 case Qualifiers::OCL_Weak:
796 case Qualifiers::OCL_Strong:
797 case Qualifiers::OCL_Autoreleasing:
798 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
799 << ValType << PointerArg->getSourceRange();
805 TheCall->setType(ValType);
809 // Initialize the argument to be stored.
810 ExprResult ValArg = TheCall->getArg(0);
811 InitializedEntity Entity = InitializedEntity::InitializeParameter(
812 Context, ValType, /*consume*/ false);
813 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
814 if (ValArg.isInvalid())
816 TheCall->setArg(0, ValArg.get());
818 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
819 // but the custom checker bypasses all default analysis.
820 TheCall->setType(Context.IntTy);
824 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
827 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
828 BuiltinID == ARM::BI__builtin_arm_ldaex ||
829 BuiltinID == ARM::BI__builtin_arm_strex ||
830 BuiltinID == ARM::BI__builtin_arm_stlex) {
831 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
834 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
835 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
839 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
842 // For intrinsics which take an immediate value as part of the instruction,
843 // range check them here.
844 unsigned i = 0, l = 0, u = 0;
846 default: return false;
847 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
848 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
849 case ARM::BI__builtin_arm_vcvtr_f:
850 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
851 case ARM::BI__builtin_arm_dmb:
852 case ARM::BI__builtin_arm_dsb:
853 case ARM::BI__builtin_arm_isb:
854 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
857 // FIXME: VFP Intrinsics should error if VFP not present.
858 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
861 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
865 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
866 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
867 BuiltinID == AArch64::BI__builtin_arm_strex ||
868 BuiltinID == AArch64::BI__builtin_arm_stlex) {
869 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
872 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
873 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
874 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
875 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
876 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
879 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
882 // For intrinsics which take an immediate value as part of the instruction,
883 // range check them here.
884 unsigned i = 0, l = 0, u = 0;
886 default: return false;
887 case AArch64::BI__builtin_arm_dmb:
888 case AArch64::BI__builtin_arm_dsb:
889 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
892 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
895 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
896 unsigned i = 0, l = 0, u = 0;
898 default: return false;
899 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
900 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
901 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
902 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
903 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
904 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
905 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
908 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
911 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
912 unsigned i = 0, l = 0, u = 0;
913 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
914 BuiltinID == PPC::BI__builtin_divdeu ||
915 BuiltinID == PPC::BI__builtin_bpermd;
916 bool IsTarget64Bit = Context.getTargetInfo()
917 .getTypeWidth(Context
919 .getIntPtrType()) == 64;
920 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
921 BuiltinID == PPC::BI__builtin_divweu ||
922 BuiltinID == PPC::BI__builtin_divde ||
923 BuiltinID == PPC::BI__builtin_divdeu;
925 if (Is64BitBltin && !IsTarget64Bit)
926 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
927 << TheCall->getSourceRange();
929 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
930 (BuiltinID == PPC::BI__builtin_bpermd &&
931 !Context.getTargetInfo().hasFeature("bpermd")))
932 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
933 << TheCall->getSourceRange();
936 default: return false;
937 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
938 case PPC::BI__builtin_altivec_crypto_vshasigmad:
939 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
940 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
941 case PPC::BI__builtin_tbegin:
942 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
943 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
944 case PPC::BI__builtin_tabortwc:
945 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
946 case PPC::BI__builtin_tabortwci:
947 case PPC::BI__builtin_tabortdci:
948 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
949 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
951 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
954 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
956 if (BuiltinID == SystemZ::BI__builtin_tabort) {
957 Expr *Arg = TheCall->getArg(0);
958 llvm::APSInt AbortCode(32);
959 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
960 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
961 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
962 << Arg->getSourceRange();
965 // For intrinsics which take an immediate value as part of the instruction,
966 // range check them here.
967 unsigned i = 0, l = 0, u = 0;
969 default: return false;
970 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
971 case SystemZ::BI__builtin_s390_verimb:
972 case SystemZ::BI__builtin_s390_verimh:
973 case SystemZ::BI__builtin_s390_verimf:
974 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
975 case SystemZ::BI__builtin_s390_vfaeb:
976 case SystemZ::BI__builtin_s390_vfaeh:
977 case SystemZ::BI__builtin_s390_vfaef:
978 case SystemZ::BI__builtin_s390_vfaebs:
979 case SystemZ::BI__builtin_s390_vfaehs:
980 case SystemZ::BI__builtin_s390_vfaefs:
981 case SystemZ::BI__builtin_s390_vfaezb:
982 case SystemZ::BI__builtin_s390_vfaezh:
983 case SystemZ::BI__builtin_s390_vfaezf:
984 case SystemZ::BI__builtin_s390_vfaezbs:
985 case SystemZ::BI__builtin_s390_vfaezhs:
986 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
987 case SystemZ::BI__builtin_s390_vfidb:
988 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
989 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
990 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
991 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
992 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
993 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
994 case SystemZ::BI__builtin_s390_vstrcb:
995 case SystemZ::BI__builtin_s390_vstrch:
996 case SystemZ::BI__builtin_s390_vstrcf:
997 case SystemZ::BI__builtin_s390_vstrczb:
998 case SystemZ::BI__builtin_s390_vstrczh:
999 case SystemZ::BI__builtin_s390_vstrczf:
1000 case SystemZ::BI__builtin_s390_vstrcbs:
1001 case SystemZ::BI__builtin_s390_vstrchs:
1002 case SystemZ::BI__builtin_s390_vstrcfs:
1003 case SystemZ::BI__builtin_s390_vstrczbs:
1004 case SystemZ::BI__builtin_s390_vstrczhs:
1005 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1007 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1010 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1011 unsigned i = 0, l = 0, u = 0;
1012 switch (BuiltinID) {
1013 default: return false;
1014 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
1015 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
1016 case X86::BI__builtin_ia32_vpermil2pd:
1017 case X86::BI__builtin_ia32_vpermil2pd256:
1018 case X86::BI__builtin_ia32_vpermil2ps:
1019 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
1020 case X86::BI__builtin_ia32_cmpb128_mask:
1021 case X86::BI__builtin_ia32_cmpw128_mask:
1022 case X86::BI__builtin_ia32_cmpd128_mask:
1023 case X86::BI__builtin_ia32_cmpq128_mask:
1024 case X86::BI__builtin_ia32_cmpb256_mask:
1025 case X86::BI__builtin_ia32_cmpw256_mask:
1026 case X86::BI__builtin_ia32_cmpd256_mask:
1027 case X86::BI__builtin_ia32_cmpq256_mask:
1028 case X86::BI__builtin_ia32_cmpb512_mask:
1029 case X86::BI__builtin_ia32_cmpw512_mask:
1030 case X86::BI__builtin_ia32_cmpd512_mask:
1031 case X86::BI__builtin_ia32_cmpq512_mask:
1032 case X86::BI__builtin_ia32_ucmpb128_mask:
1033 case X86::BI__builtin_ia32_ucmpw128_mask:
1034 case X86::BI__builtin_ia32_ucmpd128_mask:
1035 case X86::BI__builtin_ia32_ucmpq128_mask:
1036 case X86::BI__builtin_ia32_ucmpb256_mask:
1037 case X86::BI__builtin_ia32_ucmpw256_mask:
1038 case X86::BI__builtin_ia32_ucmpd256_mask:
1039 case X86::BI__builtin_ia32_ucmpq256_mask:
1040 case X86::BI__builtin_ia32_ucmpb512_mask:
1041 case X86::BI__builtin_ia32_ucmpw512_mask:
1042 case X86::BI__builtin_ia32_ucmpd512_mask:
1043 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
1044 case X86::BI__builtin_ia32_roundps:
1045 case X86::BI__builtin_ia32_roundpd:
1046 case X86::BI__builtin_ia32_roundps256:
1047 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1048 case X86::BI__builtin_ia32_roundss:
1049 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1050 case X86::BI__builtin_ia32_cmpps:
1051 case X86::BI__builtin_ia32_cmpss:
1052 case X86::BI__builtin_ia32_cmppd:
1053 case X86::BI__builtin_ia32_cmpsd:
1054 case X86::BI__builtin_ia32_cmpps256:
1055 case X86::BI__builtin_ia32_cmppd256:
1056 case X86::BI__builtin_ia32_cmpps512_mask:
1057 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
1058 case X86::BI__builtin_ia32_vpcomub:
1059 case X86::BI__builtin_ia32_vpcomuw:
1060 case X86::BI__builtin_ia32_vpcomud:
1061 case X86::BI__builtin_ia32_vpcomuq:
1062 case X86::BI__builtin_ia32_vpcomb:
1063 case X86::BI__builtin_ia32_vpcomw:
1064 case X86::BI__builtin_ia32_vpcomd:
1065 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
1067 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1070 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1071 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
1072 /// Returns true when the format fits the function and the FormatStringInfo has
1074 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1075 FormatStringInfo *FSI) {
1076 FSI->HasVAListArg = Format->getFirstArg() == 0;
1077 FSI->FormatIdx = Format->getFormatIdx() - 1;
1078 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1080 // The way the format attribute works in GCC, the implicit this argument
1081 // of member functions is counted. However, it doesn't appear in our own
1082 // lists, so decrement format_idx in that case.
1084 if(FSI->FormatIdx == 0)
1087 if (FSI->FirstDataArg != 0)
1088 --FSI->FirstDataArg;
1093 /// Checks if a the given expression evaluates to null.
1095 /// \brief Returns true if the value evaluates to null.
1096 static bool CheckNonNullExpr(Sema &S,
1098 // As a special case, transparent unions initialized with zero are
1099 // considered null for the purposes of the nonnull attribute.
1100 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
1101 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1102 if (const CompoundLiteralExpr *CLE =
1103 dyn_cast<CompoundLiteralExpr>(Expr))
1104 if (const InitListExpr *ILE =
1105 dyn_cast<InitListExpr>(CLE->getInitializer()))
1106 Expr = ILE->getInit(0);
1110 return (!Expr->isValueDependent() &&
1111 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1115 static void CheckNonNullArgument(Sema &S,
1116 const Expr *ArgExpr,
1117 SourceLocation CallSiteLoc) {
1118 if (CheckNonNullExpr(S, ArgExpr))
1119 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1122 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1123 FormatStringInfo FSI;
1124 if ((GetFormatStringType(Format) == FST_NSString) &&
1125 getFormatStringInfo(Format, false, &FSI)) {
1126 Idx = FSI.FormatIdx;
1131 /// \brief Diagnose use of %s directive in an NSString which is being passed
1132 /// as formatting string to formatting method.
1134 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1135 const NamedDecl *FDecl,
1139 bool Format = false;
1140 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1141 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1146 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1147 if (S.GetFormatNSStringIdx(I, Idx)) {
1152 if (!Format || NumArgs <= Idx)
1154 const Expr *FormatExpr = Args[Idx];
1155 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1156 FormatExpr = CSCE->getSubExpr();
1157 const StringLiteral *FormatString;
1158 if (const ObjCStringLiteral *OSL =
1159 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1160 FormatString = OSL->getString();
1162 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1165 if (S.FormatStringHasSArg(FormatString)) {
1166 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1168 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1169 << FDecl->getDeclName();
1173 static void CheckNonNullArguments(Sema &S,
1174 const NamedDecl *FDecl,
1175 ArrayRef<const Expr *> Args,
1176 SourceLocation CallSiteLoc) {
1177 // Check the attributes attached to the method/function itself.
1178 llvm::SmallBitVector NonNullArgs;
1179 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1180 if (!NonNull->args_size()) {
1181 // Easy case: all pointer arguments are nonnull.
1182 for (const auto *Arg : Args)
1183 if (S.isValidPointerAttrType(Arg->getType()))
1184 CheckNonNullArgument(S, Arg, CallSiteLoc);
1188 for (unsigned Val : NonNull->args()) {
1189 if (Val >= Args.size())
1191 if (NonNullArgs.empty())
1192 NonNullArgs.resize(Args.size());
1193 NonNullArgs.set(Val);
1197 // Check the attributes on the parameters.
1198 ArrayRef<ParmVarDecl*> parms;
1199 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1200 parms = FD->parameters();
1201 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1202 parms = MD->parameters();
1204 unsigned ArgIndex = 0;
1205 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1206 I != E; ++I, ++ArgIndex) {
1207 const ParmVarDecl *PVD = *I;
1208 if (PVD->hasAttr<NonNullAttr>() ||
1209 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1210 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1213 // In case this is a variadic call, check any remaining arguments.
1214 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1215 if (NonNullArgs[ArgIndex])
1216 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1219 /// Handles the checks for format strings, non-POD arguments to vararg
1220 /// functions, and NULL arguments passed to non-NULL parameters.
1221 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1222 unsigned NumParams, bool IsMemberFunction,
1223 SourceLocation Loc, SourceRange Range,
1224 VariadicCallType CallType) {
1225 // FIXME: We should check as much as we can in the template definition.
1226 if (CurContext->isDependentContext())
1229 // Printf and scanf checking.
1230 llvm::SmallBitVector CheckedVarArgs;
1232 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1233 // Only create vector if there are format attributes.
1234 CheckedVarArgs.resize(Args.size());
1236 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1241 // Refuse POD arguments that weren't caught by the format string
1243 if (CallType != VariadicDoesNotApply) {
1244 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1245 // Args[ArgIdx] can be null in malformed code.
1246 if (const Expr *Arg = Args[ArgIdx]) {
1247 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1248 checkVariadicArgument(Arg, CallType);
1254 CheckNonNullArguments(*this, FDecl, Args, Loc);
1256 // Type safety checking.
1257 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1258 CheckArgumentWithTypeTag(I, Args.data());
1262 /// CheckConstructorCall - Check a constructor call for correctness and safety
1263 /// properties not enforced by the C type system.
1264 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1265 ArrayRef<const Expr *> Args,
1266 const FunctionProtoType *Proto,
1267 SourceLocation Loc) {
1268 VariadicCallType CallType =
1269 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1270 checkCall(FDecl, Args, Proto->getNumParams(),
1271 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1274 /// CheckFunctionCall - Check a direct function call for various correctness
1275 /// and safety properties not strictly enforced by the C type system.
1276 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1277 const FunctionProtoType *Proto) {
1278 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1279 isa<CXXMethodDecl>(FDecl);
1280 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1281 IsMemberOperatorCall;
1282 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1283 TheCall->getCallee());
1284 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1285 Expr** Args = TheCall->getArgs();
1286 unsigned NumArgs = TheCall->getNumArgs();
1287 if (IsMemberOperatorCall) {
1288 // If this is a call to a member operator, hide the first argument
1290 // FIXME: Our choice of AST representation here is less than ideal.
1294 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
1295 IsMemberFunction, TheCall->getRParenLoc(),
1296 TheCall->getCallee()->getSourceRange(), CallType);
1298 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1299 // None of the checks below are needed for functions that don't have
1300 // simple names (e.g., C++ conversion functions).
1304 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1305 if (getLangOpts().ObjC1)
1306 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1308 unsigned CMId = FDecl->getMemoryFunctionKind();
1312 // Handle memory setting and copying functions.
1313 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1314 CheckStrlcpycatArguments(TheCall, FnInfo);
1315 else if (CMId == Builtin::BIstrncat)
1316 CheckStrncatArguments(TheCall, FnInfo);
1318 CheckMemaccessArguments(TheCall, CMId, FnInfo);
1323 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1324 ArrayRef<const Expr *> Args) {
1325 VariadicCallType CallType =
1326 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1328 checkCall(Method, Args, Method->param_size(),
1329 /*IsMemberFunction=*/false,
1330 lbrac, Method->getSourceRange(), CallType);
1335 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1336 const FunctionProtoType *Proto) {
1338 if (const auto *V = dyn_cast<VarDecl>(NDecl))
1340 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
1345 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
1348 VariadicCallType CallType;
1349 if (!Proto || !Proto->isVariadic()) {
1350 CallType = VariadicDoesNotApply;
1351 } else if (Ty->isBlockPointerType()) {
1352 CallType = VariadicBlock;
1353 } else { // Ty->isFunctionPointerType()
1354 CallType = VariadicFunction;
1356 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1358 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1359 TheCall->getNumArgs()),
1360 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1361 TheCall->getCallee()->getSourceRange(), CallType);
1366 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1367 /// such as function pointers returned from functions.
1368 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1369 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1370 TheCall->getCallee());
1371 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1373 checkCall(/*FDecl=*/nullptr,
1374 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1375 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1376 TheCall->getCallee()->getSourceRange(), CallType);
1381 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1382 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1383 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1387 case AtomicExpr::AO__c11_atomic_init:
1388 llvm_unreachable("There is no ordering argument for an init");
1390 case AtomicExpr::AO__c11_atomic_load:
1391 case AtomicExpr::AO__atomic_load_n:
1392 case AtomicExpr::AO__atomic_load:
1393 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1394 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1396 case AtomicExpr::AO__c11_atomic_store:
1397 case AtomicExpr::AO__atomic_store:
1398 case AtomicExpr::AO__atomic_store_n:
1399 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1400 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1401 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1408 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1409 AtomicExpr::AtomicOp Op) {
1410 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1411 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1413 // All these operations take one of the following forms:
1415 // C __c11_atomic_init(A *, C)
1417 // C __c11_atomic_load(A *, int)
1419 // void __atomic_load(A *, CP, int)
1421 // C __c11_atomic_add(A *, M, int)
1423 // C __atomic_exchange_n(A *, CP, int)
1425 // void __atomic_exchange(A *, C *, CP, int)
1427 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1429 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1432 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1433 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1435 // C is an appropriate type,
1436 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1437 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1438 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1439 // the int parameters are for orderings.
1441 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1442 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1443 AtomicExpr::AO__atomic_load,
1444 "need to update code for modified C11 atomics");
1445 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1446 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1447 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1448 Op == AtomicExpr::AO__atomic_store_n ||
1449 Op == AtomicExpr::AO__atomic_exchange_n ||
1450 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1451 bool IsAddSub = false;
1454 case AtomicExpr::AO__c11_atomic_init:
1458 case AtomicExpr::AO__c11_atomic_load:
1459 case AtomicExpr::AO__atomic_load_n:
1463 case AtomicExpr::AO__c11_atomic_store:
1464 case AtomicExpr::AO__atomic_load:
1465 case AtomicExpr::AO__atomic_store:
1466 case AtomicExpr::AO__atomic_store_n:
1470 case AtomicExpr::AO__c11_atomic_fetch_add:
1471 case AtomicExpr::AO__c11_atomic_fetch_sub:
1472 case AtomicExpr::AO__atomic_fetch_add:
1473 case AtomicExpr::AO__atomic_fetch_sub:
1474 case AtomicExpr::AO__atomic_add_fetch:
1475 case AtomicExpr::AO__atomic_sub_fetch:
1478 case AtomicExpr::AO__c11_atomic_fetch_and:
1479 case AtomicExpr::AO__c11_atomic_fetch_or:
1480 case AtomicExpr::AO__c11_atomic_fetch_xor:
1481 case AtomicExpr::AO__atomic_fetch_and:
1482 case AtomicExpr::AO__atomic_fetch_or:
1483 case AtomicExpr::AO__atomic_fetch_xor:
1484 case AtomicExpr::AO__atomic_fetch_nand:
1485 case AtomicExpr::AO__atomic_and_fetch:
1486 case AtomicExpr::AO__atomic_or_fetch:
1487 case AtomicExpr::AO__atomic_xor_fetch:
1488 case AtomicExpr::AO__atomic_nand_fetch:
1492 case AtomicExpr::AO__c11_atomic_exchange:
1493 case AtomicExpr::AO__atomic_exchange_n:
1497 case AtomicExpr::AO__atomic_exchange:
1501 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1502 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1506 case AtomicExpr::AO__atomic_compare_exchange:
1507 case AtomicExpr::AO__atomic_compare_exchange_n:
1512 // Check we have the right number of arguments.
1513 if (TheCall->getNumArgs() < NumArgs[Form]) {
1514 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1515 << 0 << NumArgs[Form] << TheCall->getNumArgs()
1516 << TheCall->getCallee()->getSourceRange();
1518 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1519 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1520 diag::err_typecheck_call_too_many_args)
1521 << 0 << NumArgs[Form] << TheCall->getNumArgs()
1522 << TheCall->getCallee()->getSourceRange();
1526 // Inspect the first argument of the atomic operation.
1527 Expr *Ptr = TheCall->getArg(0);
1528 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1529 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1531 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1532 << Ptr->getType() << Ptr->getSourceRange();
1536 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1537 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1538 QualType ValType = AtomTy; // 'C'
1540 if (!AtomTy->isAtomicType()) {
1541 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1542 << Ptr->getType() << Ptr->getSourceRange();
1545 if (AtomTy.isConstQualified()) {
1546 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1547 << Ptr->getType() << Ptr->getSourceRange();
1550 ValType = AtomTy->getAs<AtomicType>()->getValueType();
1553 // For an arithmetic operation, the implied arithmetic must be well-formed.
1554 if (Form == Arithmetic) {
1555 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1556 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1557 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1558 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1561 if (!IsAddSub && !ValType->isIntegerType()) {
1562 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1563 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1566 if (IsC11 && ValType->isPointerType() &&
1567 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1568 diag::err_incomplete_type)) {
1571 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1572 // For __atomic_*_n operations, the value type must be a scalar integral or
1573 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1574 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1575 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1579 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1580 !AtomTy->isScalarType()) {
1581 // For GNU atomics, require a trivially-copyable type. This is not part of
1582 // the GNU atomics specification, but we enforce it for sanity.
1583 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1584 << Ptr->getType() << Ptr->getSourceRange();
1588 // FIXME: For any builtin other than a load, the ValType must not be
1591 switch (ValType.getObjCLifetime()) {
1592 case Qualifiers::OCL_None:
1593 case Qualifiers::OCL_ExplicitNone:
1597 case Qualifiers::OCL_Weak:
1598 case Qualifiers::OCL_Strong:
1599 case Qualifiers::OCL_Autoreleasing:
1600 // FIXME: Can this happen? By this point, ValType should be known
1601 // to be trivially copyable.
1602 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1603 << ValType << Ptr->getSourceRange();
1607 QualType ResultType = ValType;
1608 if (Form == Copy || Form == GNUXchg || Form == Init)
1609 ResultType = Context.VoidTy;
1610 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1611 ResultType = Context.BoolTy;
1613 // The type of a parameter passed 'by value'. In the GNU atomics, such
1614 // arguments are actually passed as pointers.
1615 QualType ByValType = ValType; // 'CP'
1617 ByValType = Ptr->getType();
1619 // The first argument --- the pointer --- has a fixed type; we
1620 // deduce the types of the rest of the arguments accordingly. Walk
1621 // the remaining arguments, converting them to the deduced value type.
1622 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1624 if (i < NumVals[Form] + 1) {
1627 // The second argument is the non-atomic operand. For arithmetic, this
1628 // is always passed by value, and for a compare_exchange it is always
1629 // passed by address. For the rest, GNU uses by-address and C11 uses
1631 assert(Form != Load);
1632 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1634 else if (Form == Copy || Form == Xchg)
1636 else if (Form == Arithmetic)
1637 Ty = Context.getPointerDiffType();
1639 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1642 // The third argument to compare_exchange / GNU exchange is a
1643 // (pointer to a) desired value.
1647 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1648 Ty = Context.BoolTy;
1652 // The order(s) are always converted to int.
1656 InitializedEntity Entity =
1657 InitializedEntity::InitializeParameter(Context, Ty, false);
1658 ExprResult Arg = TheCall->getArg(i);
1659 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1660 if (Arg.isInvalid())
1662 TheCall->setArg(i, Arg.get());
1665 // Permute the arguments into a 'consistent' order.
1666 SmallVector<Expr*, 5> SubExprs;
1667 SubExprs.push_back(Ptr);
1670 // Note, AtomicExpr::getVal1() has a special case for this atomic.
1671 SubExprs.push_back(TheCall->getArg(1)); // Val1
1674 SubExprs.push_back(TheCall->getArg(1)); // Order
1679 SubExprs.push_back(TheCall->getArg(2)); // Order
1680 SubExprs.push_back(TheCall->getArg(1)); // Val1
1683 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1684 SubExprs.push_back(TheCall->getArg(3)); // Order
1685 SubExprs.push_back(TheCall->getArg(1)); // Val1
1686 SubExprs.push_back(TheCall->getArg(2)); // Val2
1689 SubExprs.push_back(TheCall->getArg(3)); // Order
1690 SubExprs.push_back(TheCall->getArg(1)); // Val1
1691 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1692 SubExprs.push_back(TheCall->getArg(2)); // Val2
1695 SubExprs.push_back(TheCall->getArg(4)); // Order
1696 SubExprs.push_back(TheCall->getArg(1)); // Val1
1697 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1698 SubExprs.push_back(TheCall->getArg(2)); // Val2
1699 SubExprs.push_back(TheCall->getArg(3)); // Weak
1703 if (SubExprs.size() >= 2 && Form != Init) {
1704 llvm::APSInt Result(32);
1705 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1706 !isValidOrderingForOp(Result.getSExtValue(), Op))
1707 Diag(SubExprs[1]->getLocStart(),
1708 diag::warn_atomic_op_has_invalid_memory_order)
1709 << SubExprs[1]->getSourceRange();
1712 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1713 SubExprs, ResultType, Op,
1714 TheCall->getRParenLoc());
1716 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1717 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1718 Context.AtomicUsesUnsupportedLibcall(AE))
1719 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1720 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1726 /// checkBuiltinArgument - Given a call to a builtin function, perform
1727 /// normal type-checking on the given argument, updating the call in
1728 /// place. This is useful when a builtin function requires custom
1729 /// type-checking for some of its arguments but not necessarily all of
1732 /// Returns true on error.
1733 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1734 FunctionDecl *Fn = E->getDirectCallee();
1735 assert(Fn && "builtin call without direct callee!");
1737 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1738 InitializedEntity Entity =
1739 InitializedEntity::InitializeParameter(S.Context, Param);
1741 ExprResult Arg = E->getArg(0);
1742 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1743 if (Arg.isInvalid())
1746 E->setArg(ArgIndex, Arg.get());
1750 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1751 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1752 /// type of its first argument. The main ActOnCallExpr routines have already
1753 /// promoted the types of arguments because all of these calls are prototyped as
1756 /// This function goes through and does final semantic checking for these
1759 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1760 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1761 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1762 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1764 // Ensure that we have at least one argument to do type inference from.
1765 if (TheCall->getNumArgs() < 1) {
1766 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1767 << 0 << 1 << TheCall->getNumArgs()
1768 << TheCall->getCallee()->getSourceRange();
1772 // Inspect the first argument of the atomic builtin. This should always be
1773 // a pointer type, whose element is an integral scalar or pointer type.
1774 // Because it is a pointer type, we don't have to worry about any implicit
1776 // FIXME: We don't allow floating point scalars as input.
1777 Expr *FirstArg = TheCall->getArg(0);
1778 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1779 if (FirstArgResult.isInvalid())
1781 FirstArg = FirstArgResult.get();
1782 TheCall->setArg(0, FirstArg);
1784 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1786 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1787 << FirstArg->getType() << FirstArg->getSourceRange();
1791 QualType ValType = pointerType->getPointeeType();
1792 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1793 !ValType->isBlockPointerType()) {
1794 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1795 << FirstArg->getType() << FirstArg->getSourceRange();
1799 switch (ValType.getObjCLifetime()) {
1800 case Qualifiers::OCL_None:
1801 case Qualifiers::OCL_ExplicitNone:
1805 case Qualifiers::OCL_Weak:
1806 case Qualifiers::OCL_Strong:
1807 case Qualifiers::OCL_Autoreleasing:
1808 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1809 << ValType << FirstArg->getSourceRange();
1813 // Strip any qualifiers off ValType.
1814 ValType = ValType.getUnqualifiedType();
1816 // The majority of builtins return a value, but a few have special return
1817 // types, so allow them to override appropriately below.
1818 QualType ResultType = ValType;
1820 // We need to figure out which concrete builtin this maps onto. For example,
1821 // __sync_fetch_and_add with a 2 byte object turns into
1822 // __sync_fetch_and_add_2.
1823 #define BUILTIN_ROW(x) \
1824 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1825 Builtin::BI##x##_8, Builtin::BI##x##_16 }
1827 static const unsigned BuiltinIndices[][5] = {
1828 BUILTIN_ROW(__sync_fetch_and_add),
1829 BUILTIN_ROW(__sync_fetch_and_sub),
1830 BUILTIN_ROW(__sync_fetch_and_or),
1831 BUILTIN_ROW(__sync_fetch_and_and),
1832 BUILTIN_ROW(__sync_fetch_and_xor),
1833 BUILTIN_ROW(__sync_fetch_and_nand),
1835 BUILTIN_ROW(__sync_add_and_fetch),
1836 BUILTIN_ROW(__sync_sub_and_fetch),
1837 BUILTIN_ROW(__sync_and_and_fetch),
1838 BUILTIN_ROW(__sync_or_and_fetch),
1839 BUILTIN_ROW(__sync_xor_and_fetch),
1840 BUILTIN_ROW(__sync_nand_and_fetch),
1842 BUILTIN_ROW(__sync_val_compare_and_swap),
1843 BUILTIN_ROW(__sync_bool_compare_and_swap),
1844 BUILTIN_ROW(__sync_lock_test_and_set),
1845 BUILTIN_ROW(__sync_lock_release),
1846 BUILTIN_ROW(__sync_swap)
1850 // Determine the index of the size.
1852 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1853 case 1: SizeIndex = 0; break;
1854 case 2: SizeIndex = 1; break;
1855 case 4: SizeIndex = 2; break;
1856 case 8: SizeIndex = 3; break;
1857 case 16: SizeIndex = 4; break;
1859 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1860 << FirstArg->getType() << FirstArg->getSourceRange();
1864 // Each of these builtins has one pointer argument, followed by some number of
1865 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1866 // that we ignore. Find out which row of BuiltinIndices to read from as well
1867 // as the number of fixed args.
1868 unsigned BuiltinID = FDecl->getBuiltinID();
1869 unsigned BuiltinIndex, NumFixed = 1;
1870 bool WarnAboutSemanticsChange = false;
1871 switch (BuiltinID) {
1872 default: llvm_unreachable("Unknown overloaded atomic builtin!");
1873 case Builtin::BI__sync_fetch_and_add:
1874 case Builtin::BI__sync_fetch_and_add_1:
1875 case Builtin::BI__sync_fetch_and_add_2:
1876 case Builtin::BI__sync_fetch_and_add_4:
1877 case Builtin::BI__sync_fetch_and_add_8:
1878 case Builtin::BI__sync_fetch_and_add_16:
1882 case Builtin::BI__sync_fetch_and_sub:
1883 case Builtin::BI__sync_fetch_and_sub_1:
1884 case Builtin::BI__sync_fetch_and_sub_2:
1885 case Builtin::BI__sync_fetch_and_sub_4:
1886 case Builtin::BI__sync_fetch_and_sub_8:
1887 case Builtin::BI__sync_fetch_and_sub_16:
1891 case Builtin::BI__sync_fetch_and_or:
1892 case Builtin::BI__sync_fetch_and_or_1:
1893 case Builtin::BI__sync_fetch_and_or_2:
1894 case Builtin::BI__sync_fetch_and_or_4:
1895 case Builtin::BI__sync_fetch_and_or_8:
1896 case Builtin::BI__sync_fetch_and_or_16:
1900 case Builtin::BI__sync_fetch_and_and:
1901 case Builtin::BI__sync_fetch_and_and_1:
1902 case Builtin::BI__sync_fetch_and_and_2:
1903 case Builtin::BI__sync_fetch_and_and_4:
1904 case Builtin::BI__sync_fetch_and_and_8:
1905 case Builtin::BI__sync_fetch_and_and_16:
1909 case Builtin::BI__sync_fetch_and_xor:
1910 case Builtin::BI__sync_fetch_and_xor_1:
1911 case Builtin::BI__sync_fetch_and_xor_2:
1912 case Builtin::BI__sync_fetch_and_xor_4:
1913 case Builtin::BI__sync_fetch_and_xor_8:
1914 case Builtin::BI__sync_fetch_and_xor_16:
1918 case Builtin::BI__sync_fetch_and_nand:
1919 case Builtin::BI__sync_fetch_and_nand_1:
1920 case Builtin::BI__sync_fetch_and_nand_2:
1921 case Builtin::BI__sync_fetch_and_nand_4:
1922 case Builtin::BI__sync_fetch_and_nand_8:
1923 case Builtin::BI__sync_fetch_and_nand_16:
1925 WarnAboutSemanticsChange = true;
1928 case Builtin::BI__sync_add_and_fetch:
1929 case Builtin::BI__sync_add_and_fetch_1:
1930 case Builtin::BI__sync_add_and_fetch_2:
1931 case Builtin::BI__sync_add_and_fetch_4:
1932 case Builtin::BI__sync_add_and_fetch_8:
1933 case Builtin::BI__sync_add_and_fetch_16:
1937 case Builtin::BI__sync_sub_and_fetch:
1938 case Builtin::BI__sync_sub_and_fetch_1:
1939 case Builtin::BI__sync_sub_and_fetch_2:
1940 case Builtin::BI__sync_sub_and_fetch_4:
1941 case Builtin::BI__sync_sub_and_fetch_8:
1942 case Builtin::BI__sync_sub_and_fetch_16:
1946 case Builtin::BI__sync_and_and_fetch:
1947 case Builtin::BI__sync_and_and_fetch_1:
1948 case Builtin::BI__sync_and_and_fetch_2:
1949 case Builtin::BI__sync_and_and_fetch_4:
1950 case Builtin::BI__sync_and_and_fetch_8:
1951 case Builtin::BI__sync_and_and_fetch_16:
1955 case Builtin::BI__sync_or_and_fetch:
1956 case Builtin::BI__sync_or_and_fetch_1:
1957 case Builtin::BI__sync_or_and_fetch_2:
1958 case Builtin::BI__sync_or_and_fetch_4:
1959 case Builtin::BI__sync_or_and_fetch_8:
1960 case Builtin::BI__sync_or_and_fetch_16:
1964 case Builtin::BI__sync_xor_and_fetch:
1965 case Builtin::BI__sync_xor_and_fetch_1:
1966 case Builtin::BI__sync_xor_and_fetch_2:
1967 case Builtin::BI__sync_xor_and_fetch_4:
1968 case Builtin::BI__sync_xor_and_fetch_8:
1969 case Builtin::BI__sync_xor_and_fetch_16:
1973 case Builtin::BI__sync_nand_and_fetch:
1974 case Builtin::BI__sync_nand_and_fetch_1:
1975 case Builtin::BI__sync_nand_and_fetch_2:
1976 case Builtin::BI__sync_nand_and_fetch_4:
1977 case Builtin::BI__sync_nand_and_fetch_8:
1978 case Builtin::BI__sync_nand_and_fetch_16:
1980 WarnAboutSemanticsChange = true;
1983 case Builtin::BI__sync_val_compare_and_swap:
1984 case Builtin::BI__sync_val_compare_and_swap_1:
1985 case Builtin::BI__sync_val_compare_and_swap_2:
1986 case Builtin::BI__sync_val_compare_and_swap_4:
1987 case Builtin::BI__sync_val_compare_and_swap_8:
1988 case Builtin::BI__sync_val_compare_and_swap_16:
1993 case Builtin::BI__sync_bool_compare_and_swap:
1994 case Builtin::BI__sync_bool_compare_and_swap_1:
1995 case Builtin::BI__sync_bool_compare_and_swap_2:
1996 case Builtin::BI__sync_bool_compare_and_swap_4:
1997 case Builtin::BI__sync_bool_compare_and_swap_8:
1998 case Builtin::BI__sync_bool_compare_and_swap_16:
2001 ResultType = Context.BoolTy;
2004 case Builtin::BI__sync_lock_test_and_set:
2005 case Builtin::BI__sync_lock_test_and_set_1:
2006 case Builtin::BI__sync_lock_test_and_set_2:
2007 case Builtin::BI__sync_lock_test_and_set_4:
2008 case Builtin::BI__sync_lock_test_and_set_8:
2009 case Builtin::BI__sync_lock_test_and_set_16:
2013 case Builtin::BI__sync_lock_release:
2014 case Builtin::BI__sync_lock_release_1:
2015 case Builtin::BI__sync_lock_release_2:
2016 case Builtin::BI__sync_lock_release_4:
2017 case Builtin::BI__sync_lock_release_8:
2018 case Builtin::BI__sync_lock_release_16:
2021 ResultType = Context.VoidTy;
2024 case Builtin::BI__sync_swap:
2025 case Builtin::BI__sync_swap_1:
2026 case Builtin::BI__sync_swap_2:
2027 case Builtin::BI__sync_swap_4:
2028 case Builtin::BI__sync_swap_8:
2029 case Builtin::BI__sync_swap_16:
2034 // Now that we know how many fixed arguments we expect, first check that we
2035 // have at least that many.
2036 if (TheCall->getNumArgs() < 1+NumFixed) {
2037 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2038 << 0 << 1+NumFixed << TheCall->getNumArgs()
2039 << TheCall->getCallee()->getSourceRange();
2043 if (WarnAboutSemanticsChange) {
2044 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2045 << TheCall->getCallee()->getSourceRange();
2048 // Get the decl for the concrete builtin from this, we can tell what the
2049 // concrete integer type we should convert to is.
2050 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2051 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
2052 FunctionDecl *NewBuiltinDecl;
2053 if (NewBuiltinID == BuiltinID)
2054 NewBuiltinDecl = FDecl;
2056 // Perform builtin lookup to avoid redeclaring it.
2057 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2058 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2059 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2060 assert(Res.getFoundDecl());
2061 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
2062 if (!NewBuiltinDecl)
2066 // The first argument --- the pointer --- has a fixed type; we
2067 // deduce the types of the rest of the arguments accordingly. Walk
2068 // the remaining arguments, converting them to the deduced value type.
2069 for (unsigned i = 0; i != NumFixed; ++i) {
2070 ExprResult Arg = TheCall->getArg(i+1);
2072 // GCC does an implicit conversion to the pointer or integer ValType. This
2073 // can fail in some cases (1i -> int**), check for this error case now.
2074 // Initialize the argument.
2075 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2076 ValType, /*consume*/ false);
2077 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2078 if (Arg.isInvalid())
2081 // Okay, we have something that *can* be converted to the right type. Check
2082 // to see if there is a potentially weird extension going on here. This can
2083 // happen when you do an atomic operation on something like an char* and
2084 // pass in 42. The 42 gets converted to char. This is even more strange
2085 // for things like 45.123 -> char, etc.
2086 // FIXME: Do this check.
2087 TheCall->setArg(i+1, Arg.get());
2090 ASTContext& Context = this->getASTContext();
2092 // Create a new DeclRefExpr to refer to the new decl.
2093 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2095 DRE->getQualifierLoc(),
2098 /*enclosing*/ false,
2100 Context.BuiltinFnTy,
2101 DRE->getValueKind());
2103 // Set the callee in the CallExpr.
2104 // FIXME: This loses syntactic information.
2105 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2106 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2107 CK_BuiltinFnToFnPtr);
2108 TheCall->setCallee(PromotedCall.get());
2110 // Change the result type of the call to match the original value type. This
2111 // is arbitrary, but the codegen for these builtins ins design to handle it
2113 TheCall->setType(ResultType);
2115 return TheCallResult;
2118 /// CheckObjCString - Checks that the argument to the builtin
2119 /// CFString constructor is correct
2120 /// Note: It might also make sense to do the UTF-16 conversion here (would
2121 /// simplify the backend).
2122 bool Sema::CheckObjCString(Expr *Arg) {
2123 Arg = Arg->IgnoreParenCasts();
2124 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2126 if (!Literal || !Literal->isAscii()) {
2127 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2128 << Arg->getSourceRange();
2132 if (Literal->containsNonAsciiOrNull()) {
2133 StringRef String = Literal->getString();
2134 unsigned NumBytes = String.size();
2135 SmallVector<UTF16, 128> ToBuf(NumBytes);
2136 const UTF8 *FromPtr = (const UTF8 *)String.data();
2137 UTF16 *ToPtr = &ToBuf[0];
2139 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2140 &ToPtr, ToPtr + NumBytes,
2142 // Check for conversion failure.
2143 if (Result != conversionOK)
2144 Diag(Arg->getLocStart(),
2145 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2150 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2151 /// Emit an error and return true on failure, return false on success.
2152 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2153 Expr *Fn = TheCall->getCallee();
2154 if (TheCall->getNumArgs() > 2) {
2155 Diag(TheCall->getArg(2)->getLocStart(),
2156 diag::err_typecheck_call_too_many_args)
2157 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2158 << Fn->getSourceRange()
2159 << SourceRange(TheCall->getArg(2)->getLocStart(),
2160 (*(TheCall->arg_end()-1))->getLocEnd());
2164 if (TheCall->getNumArgs() < 2) {
2165 return Diag(TheCall->getLocEnd(),
2166 diag::err_typecheck_call_too_few_args_at_least)
2167 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
2170 // Type-check the first argument normally.
2171 if (checkBuiltinArgument(*this, TheCall, 0))
2174 // Determine whether the current function is variadic or not.
2175 BlockScopeInfo *CurBlock = getCurBlock();
2178 isVariadic = CurBlock->TheDecl->isVariadic();
2179 else if (FunctionDecl *FD = getCurFunctionDecl())
2180 isVariadic = FD->isVariadic();
2182 isVariadic = getCurMethodDecl()->isVariadic();
2185 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2189 // Verify that the second argument to the builtin is the last argument of the
2190 // current function or method.
2191 bool SecondArgIsLastNamedArgument = false;
2192 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
2194 // These are valid if SecondArgIsLastNamedArgument is false after the next
2197 SourceLocation ParamLoc;
2199 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2200 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2201 // FIXME: This isn't correct for methods (results in bogus warning).
2202 // Get the last formal in the current function.
2203 const ParmVarDecl *LastArg;
2205 LastArg = *(CurBlock->TheDecl->param_end()-1);
2206 else if (FunctionDecl *FD = getCurFunctionDecl())
2207 LastArg = *(FD->param_end()-1);
2209 LastArg = *(getCurMethodDecl()->param_end()-1);
2210 SecondArgIsLastNamedArgument = PV == LastArg;
2212 Type = PV->getType();
2213 ParamLoc = PV->getLocation();
2217 if (!SecondArgIsLastNamedArgument)
2218 Diag(TheCall->getArg(1)->getLocStart(),
2219 diag::warn_second_parameter_of_va_start_not_last_named_argument);
2220 else if (Type->isReferenceType()) {
2221 Diag(Arg->getLocStart(),
2222 diag::warn_va_start_of_reference_type_is_undefined);
2223 Diag(ParamLoc, diag::note_parameter_type) << Type;
2226 TheCall->setType(Context.VoidTy);
2230 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2231 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2232 // const char *named_addr);
2234 Expr *Func = Call->getCallee();
2236 if (Call->getNumArgs() < 3)
2237 return Diag(Call->getLocEnd(),
2238 diag::err_typecheck_call_too_few_args_at_least)
2239 << 0 /*function call*/ << 3 << Call->getNumArgs();
2241 // Determine whether the current function is variadic or not.
2243 if (BlockScopeInfo *CurBlock = getCurBlock())
2244 IsVariadic = CurBlock->TheDecl->isVariadic();
2245 else if (FunctionDecl *FD = getCurFunctionDecl())
2246 IsVariadic = FD->isVariadic();
2247 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2248 IsVariadic = MD->isVariadic();
2250 llvm_unreachable("unexpected statement type");
2253 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2257 // Type-check the first argument normally.
2258 if (checkBuiltinArgument(*this, Call, 0))
2264 } ArgumentTypes[] = {
2265 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2266 { 2, Context.getSizeType() },
2269 for (const auto &AT : ArgumentTypes) {
2270 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2271 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2273 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2274 << Arg->getType() << AT.Type << 1 /* different class */
2275 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2276 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2282 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2283 /// friends. This is declared to take (...), so we have to check everything.
2284 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2285 if (TheCall->getNumArgs() < 2)
2286 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2287 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2288 if (TheCall->getNumArgs() > 2)
2289 return Diag(TheCall->getArg(2)->getLocStart(),
2290 diag::err_typecheck_call_too_many_args)
2291 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2292 << SourceRange(TheCall->getArg(2)->getLocStart(),
2293 (*(TheCall->arg_end()-1))->getLocEnd());
2295 ExprResult OrigArg0 = TheCall->getArg(0);
2296 ExprResult OrigArg1 = TheCall->getArg(1);
2298 // Do standard promotions between the two arguments, returning their common
2300 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2301 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2304 // Make sure any conversions are pushed back into the call; this is
2305 // type safe since unordered compare builtins are declared as "_Bool
2307 TheCall->setArg(0, OrigArg0.get());
2308 TheCall->setArg(1, OrigArg1.get());
2310 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2313 // If the common type isn't a real floating type, then the arguments were
2314 // invalid for this operation.
2315 if (Res.isNull() || !Res->isRealFloatingType())
2316 return Diag(OrigArg0.get()->getLocStart(),
2317 diag::err_typecheck_call_invalid_ordered_compare)
2318 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2319 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2324 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2325 /// __builtin_isnan and friends. This is declared to take (...), so we have
2326 /// to check everything. We expect the last argument to be a floating point
2328 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2329 if (TheCall->getNumArgs() < NumArgs)
2330 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2331 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2332 if (TheCall->getNumArgs() > NumArgs)
2333 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2334 diag::err_typecheck_call_too_many_args)
2335 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2336 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2337 (*(TheCall->arg_end()-1))->getLocEnd());
2339 Expr *OrigArg = TheCall->getArg(NumArgs-1);
2341 if (OrigArg->isTypeDependent())
2344 // This operation requires a non-_Complex floating-point number.
2345 if (!OrigArg->getType()->isRealFloatingType())
2346 return Diag(OrigArg->getLocStart(),
2347 diag::err_typecheck_call_invalid_unary_fp)
2348 << OrigArg->getType() << OrigArg->getSourceRange();
2350 // If this is an implicit conversion from float -> double, remove it.
2351 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2352 Expr *CastArg = Cast->getSubExpr();
2353 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2354 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2355 "promotion from float to double is the only expected cast here");
2356 Cast->setSubExpr(nullptr);
2357 TheCall->setArg(NumArgs-1, CastArg);
2364 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2365 // This is declared to take (...), so we have to check everything.
2366 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2367 if (TheCall->getNumArgs() < 2)
2368 return ExprError(Diag(TheCall->getLocEnd(),
2369 diag::err_typecheck_call_too_few_args_at_least)
2370 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2371 << TheCall->getSourceRange());
2373 // Determine which of the following types of shufflevector we're checking:
2374 // 1) unary, vector mask: (lhs, mask)
2375 // 2) binary, vector mask: (lhs, rhs, mask)
2376 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2377 QualType resType = TheCall->getArg(0)->getType();
2378 unsigned numElements = 0;
2380 if (!TheCall->getArg(0)->isTypeDependent() &&
2381 !TheCall->getArg(1)->isTypeDependent()) {
2382 QualType LHSType = TheCall->getArg(0)->getType();
2383 QualType RHSType = TheCall->getArg(1)->getType();
2385 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2386 return ExprError(Diag(TheCall->getLocStart(),
2387 diag::err_shufflevector_non_vector)
2388 << SourceRange(TheCall->getArg(0)->getLocStart(),
2389 TheCall->getArg(1)->getLocEnd()));
2391 numElements = LHSType->getAs<VectorType>()->getNumElements();
2392 unsigned numResElements = TheCall->getNumArgs() - 2;
2394 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2395 // with mask. If so, verify that RHS is an integer vector type with the
2396 // same number of elts as lhs.
2397 if (TheCall->getNumArgs() == 2) {
2398 if (!RHSType->hasIntegerRepresentation() ||
2399 RHSType->getAs<VectorType>()->getNumElements() != numElements)
2400 return ExprError(Diag(TheCall->getLocStart(),
2401 diag::err_shufflevector_incompatible_vector)
2402 << SourceRange(TheCall->getArg(1)->getLocStart(),
2403 TheCall->getArg(1)->getLocEnd()));
2404 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2405 return ExprError(Diag(TheCall->getLocStart(),
2406 diag::err_shufflevector_incompatible_vector)
2407 << SourceRange(TheCall->getArg(0)->getLocStart(),
2408 TheCall->getArg(1)->getLocEnd()));
2409 } else if (numElements != numResElements) {
2410 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2411 resType = Context.getVectorType(eltType, numResElements,
2412 VectorType::GenericVector);
2416 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2417 if (TheCall->getArg(i)->isTypeDependent() ||
2418 TheCall->getArg(i)->isValueDependent())
2421 llvm::APSInt Result(32);
2422 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2423 return ExprError(Diag(TheCall->getLocStart(),
2424 diag::err_shufflevector_nonconstant_argument)
2425 << TheCall->getArg(i)->getSourceRange());
2427 // Allow -1 which will be translated to undef in the IR.
2428 if (Result.isSigned() && Result.isAllOnesValue())
2431 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2432 return ExprError(Diag(TheCall->getLocStart(),
2433 diag::err_shufflevector_argument_too_large)
2434 << TheCall->getArg(i)->getSourceRange());
2437 SmallVector<Expr*, 32> exprs;
2439 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2440 exprs.push_back(TheCall->getArg(i));
2441 TheCall->setArg(i, nullptr);
2444 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2445 TheCall->getCallee()->getLocStart(),
2446 TheCall->getRParenLoc());
2449 /// SemaConvertVectorExpr - Handle __builtin_convertvector
2450 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2451 SourceLocation BuiltinLoc,
2452 SourceLocation RParenLoc) {
2453 ExprValueKind VK = VK_RValue;
2454 ExprObjectKind OK = OK_Ordinary;
2455 QualType DstTy = TInfo->getType();
2456 QualType SrcTy = E->getType();
2458 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2459 return ExprError(Diag(BuiltinLoc,
2460 diag::err_convertvector_non_vector)
2461 << E->getSourceRange());
2462 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2463 return ExprError(Diag(BuiltinLoc,
2464 diag::err_convertvector_non_vector_type));
2466 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2467 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2468 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2469 if (SrcElts != DstElts)
2470 return ExprError(Diag(BuiltinLoc,
2471 diag::err_convertvector_incompatible_vector)
2472 << E->getSourceRange());
2475 return new (Context)
2476 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
2479 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2480 // This is declared to take (const void*, ...) and can take two
2481 // optional constant int args.
2482 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
2483 unsigned NumArgs = TheCall->getNumArgs();
2486 return Diag(TheCall->getLocEnd(),
2487 diag::err_typecheck_call_too_many_args_at_most)
2488 << 0 /*function call*/ << 3 << NumArgs
2489 << TheCall->getSourceRange();
2491 // Argument 0 is checked for us and the remaining arguments must be
2492 // constant integers.
2493 for (unsigned i = 1; i != NumArgs; ++i)
2494 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2500 /// SemaBuiltinAssume - Handle __assume (MS Extension).
2501 // __assume does not evaluate its arguments, and should warn if its argument
2502 // has side effects.
2503 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2504 Expr *Arg = TheCall->getArg(0);
2505 if (Arg->isInstantiationDependent()) return false;
2507 if (Arg->HasSideEffects(Context))
2508 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2509 << Arg->getSourceRange()
2510 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2515 /// Handle __builtin_assume_aligned. This is declared
2516 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2517 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2518 unsigned NumArgs = TheCall->getNumArgs();
2521 return Diag(TheCall->getLocEnd(),
2522 diag::err_typecheck_call_too_many_args_at_most)
2523 << 0 /*function call*/ << 3 << NumArgs
2524 << TheCall->getSourceRange();
2526 // The alignment must be a constant integer.
2527 Expr *Arg = TheCall->getArg(1);
2529 // We can't check the value of a dependent argument.
2530 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2531 llvm::APSInt Result;
2532 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2535 if (!Result.isPowerOf2())
2536 return Diag(TheCall->getLocStart(),
2537 diag::err_alignment_not_power_of_two)
2538 << Arg->getSourceRange();
2542 ExprResult Arg(TheCall->getArg(2));
2543 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2544 Context.getSizeType(), false);
2545 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2546 if (Arg.isInvalid()) return true;
2547 TheCall->setArg(2, Arg.get());
2553 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2554 /// TheCall is a constant expression.
2555 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2556 llvm::APSInt &Result) {
2557 Expr *Arg = TheCall->getArg(ArgNum);
2558 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2559 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2561 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2563 if (!Arg->isIntegerConstantExpr(Result, Context))
2564 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
2565 << FDecl->getDeclName() << Arg->getSourceRange();
2570 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2571 /// TheCall is a constant expression in the range [Low, High].
2572 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2573 int Low, int High) {
2574 llvm::APSInt Result;
2576 // We can't check the value of a dependent argument.
2577 Expr *Arg = TheCall->getArg(ArgNum);
2578 if (Arg->isTypeDependent() || Arg->isValueDependent())
2581 // Check constant-ness first.
2582 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2585 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2586 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2587 << Low << High << Arg->getSourceRange();
2592 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2593 /// This checks that the target supports __builtin_longjmp and
2594 /// that val is a constant 1.
2595 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2596 if (!Context.getTargetInfo().hasSjLjLowering())
2597 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2598 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2600 Expr *Arg = TheCall->getArg(1);
2601 llvm::APSInt Result;
2603 // TODO: This is less than ideal. Overload this to take a value.
2604 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2608 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2609 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2615 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2616 /// This checks that the target supports __builtin_setjmp.
2617 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2618 if (!Context.getTargetInfo().hasSjLjLowering())
2619 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2620 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2625 enum StringLiteralCheckType {
2627 SLCT_UncheckedLiteral,
2632 // Determine if an expression is a string literal or constant string.
2633 // If this function returns false on the arguments to a function expecting a
2634 // format string, we will usually need to emit a warning.
2635 // True string literals are then checked by CheckFormatString.
2636 static StringLiteralCheckType
2637 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2638 bool HasVAListArg, unsigned format_idx,
2639 unsigned firstDataArg, Sema::FormatStringType Type,
2640 Sema::VariadicCallType CallType, bool InFunctionCall,
2641 llvm::SmallBitVector &CheckedVarArgs) {
2643 if (E->isTypeDependent() || E->isValueDependent())
2644 return SLCT_NotALiteral;
2646 E = E->IgnoreParenCasts();
2648 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2649 // Technically -Wformat-nonliteral does not warn about this case.
2650 // The behavior of printf and friends in this case is implementation
2651 // dependent. Ideally if the format string cannot be null then
2652 // it should have a 'nonnull' attribute in the function prototype.
2653 return SLCT_UncheckedLiteral;
2655 switch (E->getStmtClass()) {
2656 case Stmt::BinaryConditionalOperatorClass:
2657 case Stmt::ConditionalOperatorClass: {
2658 // The expression is a literal if both sub-expressions were, and it was
2659 // completely checked only if both sub-expressions were checked.
2660 const AbstractConditionalOperator *C =
2661 cast<AbstractConditionalOperator>(E);
2662 StringLiteralCheckType Left =
2663 checkFormatStringExpr(S, C->getTrueExpr(), Args,
2664 HasVAListArg, format_idx, firstDataArg,
2665 Type, CallType, InFunctionCall, CheckedVarArgs);
2666 if (Left == SLCT_NotALiteral)
2667 return SLCT_NotALiteral;
2668 StringLiteralCheckType Right =
2669 checkFormatStringExpr(S, C->getFalseExpr(), Args,
2670 HasVAListArg, format_idx, firstDataArg,
2671 Type, CallType, InFunctionCall, CheckedVarArgs);
2672 return Left < Right ? Left : Right;
2675 case Stmt::ImplicitCastExprClass: {
2676 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2680 case Stmt::OpaqueValueExprClass:
2681 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2685 return SLCT_NotALiteral;
2687 case Stmt::PredefinedExprClass:
2688 // While __func__, etc., are technically not string literals, they
2689 // cannot contain format specifiers and thus are not a security
2691 return SLCT_UncheckedLiteral;
2693 case Stmt::DeclRefExprClass: {
2694 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2696 // As an exception, do not flag errors for variables binding to
2697 // const string literals.
2698 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2699 bool isConstant = false;
2700 QualType T = DR->getType();
2702 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2703 isConstant = AT->getElementType().isConstant(S.Context);
2704 } else if (const PointerType *PT = T->getAs<PointerType>()) {
2705 isConstant = T.isConstant(S.Context) &&
2706 PT->getPointeeType().isConstant(S.Context);
2707 } else if (T->isObjCObjectPointerType()) {
2708 // In ObjC, there is usually no "const ObjectPointer" type,
2709 // so don't check if the pointee type is constant.
2710 isConstant = T.isConstant(S.Context);
2714 if (const Expr *Init = VD->getAnyInitializer()) {
2715 // Look through initializers like const char c[] = { "foo" }
2716 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2717 if (InitList->isStringLiteralInit())
2718 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2720 return checkFormatStringExpr(S, Init, Args,
2721 HasVAListArg, format_idx,
2722 firstDataArg, Type, CallType,
2723 /*InFunctionCall*/false, CheckedVarArgs);
2727 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2728 // special check to see if the format string is a function parameter
2729 // of the function calling the printf function. If the function
2730 // has an attribute indicating it is a printf-like function, then we
2731 // should suppress warnings concerning non-literals being used in a call
2732 // to a vprintf function. For example:
2735 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2737 // va_start(ap, fmt);
2738 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2742 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2743 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2744 int PVIndex = PV->getFunctionScopeIndex() + 1;
2745 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2746 // adjust for implicit parameter
2747 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2748 if (MD->isInstance())
2750 // We also check if the formats are compatible.
2751 // We can't pass a 'scanf' string to a 'printf' function.
2752 if (PVIndex == PVFormat->getFormatIdx() &&
2753 Type == S.GetFormatStringType(PVFormat))
2754 return SLCT_UncheckedLiteral;
2761 return SLCT_NotALiteral;
2764 case Stmt::CallExprClass:
2765 case Stmt::CXXMemberCallExprClass: {
2766 const CallExpr *CE = cast<CallExpr>(E);
2767 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2768 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2769 unsigned ArgIndex = FA->getFormatIdx();
2770 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2771 if (MD->isInstance())
2773 const Expr *Arg = CE->getArg(ArgIndex - 1);
2775 return checkFormatStringExpr(S, Arg, Args,
2776 HasVAListArg, format_idx, firstDataArg,
2777 Type, CallType, InFunctionCall,
2779 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2780 unsigned BuiltinID = FD->getBuiltinID();
2781 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2782 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2783 const Expr *Arg = CE->getArg(0);
2784 return checkFormatStringExpr(S, Arg, Args,
2785 HasVAListArg, format_idx,
2786 firstDataArg, Type, CallType,
2787 InFunctionCall, CheckedVarArgs);
2792 return SLCT_NotALiteral;
2794 case Stmt::ObjCStringLiteralClass:
2795 case Stmt::StringLiteralClass: {
2796 const StringLiteral *StrE = nullptr;
2798 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2799 StrE = ObjCFExpr->getString();
2801 StrE = cast<StringLiteral>(E);
2804 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2805 Type, InFunctionCall, CallType, CheckedVarArgs);
2806 return SLCT_CheckedLiteral;
2809 return SLCT_NotALiteral;
2813 return SLCT_NotALiteral;
2817 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2818 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2819 .Case("scanf", FST_Scanf)
2820 .Cases("printf", "printf0", FST_Printf)
2821 .Cases("NSString", "CFString", FST_NSString)
2822 .Case("strftime", FST_Strftime)
2823 .Case("strfmon", FST_Strfmon)
2824 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2825 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
2826 .Case("os_trace", FST_OSTrace)
2827 .Default(FST_Unknown);
2830 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2831 /// functions) for correct use of format strings.
2832 /// Returns true if a format string has been fully checked.
2833 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2834 ArrayRef<const Expr *> Args,
2836 VariadicCallType CallType,
2837 SourceLocation Loc, SourceRange Range,
2838 llvm::SmallBitVector &CheckedVarArgs) {
2839 FormatStringInfo FSI;
2840 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2841 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2842 FSI.FirstDataArg, GetFormatStringType(Format),
2843 CallType, Loc, Range, CheckedVarArgs);
2847 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2848 bool HasVAListArg, unsigned format_idx,
2849 unsigned firstDataArg, FormatStringType Type,
2850 VariadicCallType CallType,
2851 SourceLocation Loc, SourceRange Range,
2852 llvm::SmallBitVector &CheckedVarArgs) {
2853 // CHECK: printf/scanf-like function is called with no format string.
2854 if (format_idx >= Args.size()) {
2855 Diag(Loc, diag::warn_missing_format_string) << Range;
2859 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2861 // CHECK: format string is not a string literal.
2863 // Dynamically generated format strings are difficult to
2864 // automatically vet at compile time. Requiring that format strings
2865 // are string literals: (1) permits the checking of format strings by
2866 // the compiler and thereby (2) can practically remove the source of
2867 // many format string exploits.
2869 // Format string can be either ObjC string (e.g. @"%d") or
2870 // C string (e.g. "%d")
2871 // ObjC string uses the same format specifiers as C string, so we can use
2872 // the same format string checking logic for both ObjC and C strings.
2873 StringLiteralCheckType CT =
2874 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2875 format_idx, firstDataArg, Type, CallType,
2876 /*IsFunctionCall*/true, CheckedVarArgs);
2877 if (CT != SLCT_NotALiteral)
2878 // Literal format string found, check done!
2879 return CT == SLCT_CheckedLiteral;
2881 // Strftime is particular as it always uses a single 'time' argument,
2882 // so it is safe to pass a non-literal string.
2883 if (Type == FST_Strftime)
2886 // Do not emit diag when the string param is a macro expansion and the
2887 // format is either NSString or CFString. This is a hack to prevent
2888 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2889 // which are usually used in place of NS and CF string literals.
2890 if (Type == FST_NSString &&
2891 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2894 // If there are no arguments specified, warn with -Wformat-security, otherwise
2895 // warn only with -Wformat-nonliteral.
2896 if (Args.size() == firstDataArg)
2897 Diag(Args[format_idx]->getLocStart(),
2898 diag::warn_format_nonliteral_noargs)
2899 << OrigFormatExpr->getSourceRange();
2901 Diag(Args[format_idx]->getLocStart(),
2902 diag::warn_format_nonliteral)
2903 << OrigFormatExpr->getSourceRange();
2908 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2911 const StringLiteral *FExpr;
2912 const Expr *OrigFormatExpr;
2913 const unsigned FirstDataArg;
2914 const unsigned NumDataArgs;
2915 const char *Beg; // Start of format string.
2916 const bool HasVAListArg;
2917 ArrayRef<const Expr *> Args;
2919 llvm::SmallBitVector CoveredArgs;
2920 bool usesPositionalArgs;
2922 bool inFunctionCall;
2923 Sema::VariadicCallType CallType;
2924 llvm::SmallBitVector &CheckedVarArgs;
2926 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2927 const Expr *origFormatExpr, unsigned firstDataArg,
2928 unsigned numDataArgs, const char *beg, bool hasVAListArg,
2929 ArrayRef<const Expr *> Args,
2930 unsigned formatIdx, bool inFunctionCall,
2931 Sema::VariadicCallType callType,
2932 llvm::SmallBitVector &CheckedVarArgs)
2933 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2934 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2935 Beg(beg), HasVAListArg(hasVAListArg),
2936 Args(Args), FormatIdx(formatIdx),
2937 usesPositionalArgs(false), atFirstArg(true),
2938 inFunctionCall(inFunctionCall), CallType(callType),
2939 CheckedVarArgs(CheckedVarArgs) {
2940 CoveredArgs.resize(numDataArgs);
2941 CoveredArgs.reset();
2944 void DoneProcessing();
2946 void HandleIncompleteSpecifier(const char *startSpecifier,
2947 unsigned specifierLen) override;
2949 void HandleInvalidLengthModifier(
2950 const analyze_format_string::FormatSpecifier &FS,
2951 const analyze_format_string::ConversionSpecifier &CS,
2952 const char *startSpecifier, unsigned specifierLen,
2955 void HandleNonStandardLengthModifier(
2956 const analyze_format_string::FormatSpecifier &FS,
2957 const char *startSpecifier, unsigned specifierLen);
2959 void HandleNonStandardConversionSpecifier(
2960 const analyze_format_string::ConversionSpecifier &CS,
2961 const char *startSpecifier, unsigned specifierLen);
2963 void HandlePosition(const char *startPos, unsigned posLen) override;
2965 void HandleInvalidPosition(const char *startSpecifier,
2966 unsigned specifierLen,
2967 analyze_format_string::PositionContext p) override;
2969 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
2971 void HandleNullChar(const char *nullCharacter) override;
2973 template <typename Range>
2974 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2975 const Expr *ArgumentExpr,
2976 PartialDiagnostic PDiag,
2977 SourceLocation StringLoc,
2978 bool IsStringLocation, Range StringRange,
2979 ArrayRef<FixItHint> Fixit = None);
2982 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2983 const char *startSpec,
2984 unsigned specifierLen,
2985 const char *csStart, unsigned csLen);
2987 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2988 const char *startSpec,
2989 unsigned specifierLen);
2991 SourceRange getFormatStringRange();
2992 CharSourceRange getSpecifierRange(const char *startSpecifier,
2993 unsigned specifierLen);
2994 SourceLocation getLocationOfByte(const char *x);
2996 const Expr *getDataArg(unsigned i) const;
2998 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2999 const analyze_format_string::ConversionSpecifier &CS,
3000 const char *startSpecifier, unsigned specifierLen,
3003 template <typename Range>
3004 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3005 bool IsStringLocation, Range StringRange,
3006 ArrayRef<FixItHint> Fixit = None);
3010 SourceRange CheckFormatHandler::getFormatStringRange() {
3011 return OrigFormatExpr->getSourceRange();
3014 CharSourceRange CheckFormatHandler::
3015 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
3016 SourceLocation Start = getLocationOfByte(startSpecifier);
3017 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3019 // Advance the end SourceLocation by one due to half-open ranges.
3020 End = End.getLocWithOffset(1);
3022 return CharSourceRange::getCharRange(Start, End);
3025 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
3026 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
3029 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3030 unsigned specifierLen){
3031 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3032 getLocationOfByte(startSpecifier),
3033 /*IsStringLocation*/true,
3034 getSpecifierRange(startSpecifier, specifierLen));
3037 void CheckFormatHandler::HandleInvalidLengthModifier(
3038 const analyze_format_string::FormatSpecifier &FS,
3039 const analyze_format_string::ConversionSpecifier &CS,
3040 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
3041 using namespace analyze_format_string;
3043 const LengthModifier &LM = FS.getLengthModifier();
3044 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3046 // See if we know how to fix this length modifier.
3047 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
3049 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
3050 getLocationOfByte(LM.getStart()),
3051 /*IsStringLocation*/true,
3052 getSpecifierRange(startSpecifier, specifierLen));
3054 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3055 << FixedLM->toString()
3056 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3060 if (DiagID == diag::warn_format_nonsensical_length)
3061 Hint = FixItHint::CreateRemoval(LMRange);
3063 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
3064 getLocationOfByte(LM.getStart()),
3065 /*IsStringLocation*/true,
3066 getSpecifierRange(startSpecifier, specifierLen),
3071 void CheckFormatHandler::HandleNonStandardLengthModifier(
3072 const analyze_format_string::FormatSpecifier &FS,
3073 const char *startSpecifier, unsigned specifierLen) {
3074 using namespace analyze_format_string;
3076 const LengthModifier &LM = FS.getLengthModifier();
3077 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3079 // See if we know how to fix this length modifier.
3080 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
3082 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3083 << LM.toString() << 0,
3084 getLocationOfByte(LM.getStart()),
3085 /*IsStringLocation*/true,
3086 getSpecifierRange(startSpecifier, specifierLen));
3088 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3089 << FixedLM->toString()
3090 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3093 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3094 << LM.toString() << 0,
3095 getLocationOfByte(LM.getStart()),
3096 /*IsStringLocation*/true,
3097 getSpecifierRange(startSpecifier, specifierLen));
3101 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3102 const analyze_format_string::ConversionSpecifier &CS,
3103 const char *startSpecifier, unsigned specifierLen) {
3104 using namespace analyze_format_string;
3106 // See if we know how to fix this conversion specifier.
3107 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
3109 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3110 << CS.toString() << /*conversion specifier*/1,
3111 getLocationOfByte(CS.getStart()),
3112 /*IsStringLocation*/true,
3113 getSpecifierRange(startSpecifier, specifierLen));
3115 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3116 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3117 << FixedCS->toString()
3118 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3120 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3121 << CS.toString() << /*conversion specifier*/1,
3122 getLocationOfByte(CS.getStart()),
3123 /*IsStringLocation*/true,
3124 getSpecifierRange(startSpecifier, specifierLen));
3128 void CheckFormatHandler::HandlePosition(const char *startPos,
3130 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3131 getLocationOfByte(startPos),
3132 /*IsStringLocation*/true,
3133 getSpecifierRange(startPos, posLen));
3137 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3138 analyze_format_string::PositionContext p) {
3139 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3141 getLocationOfByte(startPos), /*IsStringLocation*/true,
3142 getSpecifierRange(startPos, posLen));
3145 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
3147 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3148 getLocationOfByte(startPos),
3149 /*IsStringLocation*/true,
3150 getSpecifierRange(startPos, posLen));
3153 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
3154 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
3155 // The presence of a null character is likely an error.
3156 EmitFormatDiagnostic(
3157 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3158 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3159 getFormatStringRange());
3163 // Note that this may return NULL if there was an error parsing or building
3164 // one of the argument expressions.
3165 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
3166 return Args[FirstDataArg + i];
3169 void CheckFormatHandler::DoneProcessing() {
3170 // Does the number of data arguments exceed the number of
3171 // format conversions in the format string?
3172 if (!HasVAListArg) {
3173 // Find any arguments that weren't covered.
3175 signed notCoveredArg = CoveredArgs.find_first();
3176 if (notCoveredArg >= 0) {
3177 assert((unsigned)notCoveredArg < NumDataArgs);
3178 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3179 SourceLocation Loc = E->getLocStart();
3180 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3181 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3182 Loc, /*IsStringLocation*/false,
3183 getFormatStringRange());
3191 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3193 const char *startSpec,
3194 unsigned specifierLen,
3195 const char *csStart,
3198 bool keepGoing = true;
3199 if (argIndex < NumDataArgs) {
3200 // Consider the argument coverered, even though the specifier doesn't
3202 CoveredArgs.set(argIndex);
3205 // If argIndex exceeds the number of data arguments we
3206 // don't issue a warning because that is just a cascade of warnings (and
3207 // they may have intended '%%' anyway). We don't want to continue processing
3208 // the format string after this point, however, as we will like just get
3209 // gibberish when trying to match arguments.
3213 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3214 << StringRef(csStart, csLen),
3215 Loc, /*IsStringLocation*/true,
3216 getSpecifierRange(startSpec, specifierLen));
3222 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3223 const char *startSpec,
3224 unsigned specifierLen) {
3225 EmitFormatDiagnostic(
3226 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3227 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3231 CheckFormatHandler::CheckNumArgs(
3232 const analyze_format_string::FormatSpecifier &FS,
3233 const analyze_format_string::ConversionSpecifier &CS,
3234 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3236 if (argIndex >= NumDataArgs) {
3237 PartialDiagnostic PDiag = FS.usesPositionalArg()
3238 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3239 << (argIndex+1) << NumDataArgs)
3240 : S.PDiag(diag::warn_printf_insufficient_data_args);
3241 EmitFormatDiagnostic(
3242 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3243 getSpecifierRange(startSpecifier, specifierLen));
3249 template<typename Range>
3250 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3252 bool IsStringLocation,
3254 ArrayRef<FixItHint> FixIt) {
3255 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
3256 Loc, IsStringLocation, StringRange, FixIt);
3259 /// \brief If the format string is not within the funcion call, emit a note
3260 /// so that the function call and string are in diagnostic messages.
3262 /// \param InFunctionCall if true, the format string is within the function
3263 /// call and only one diagnostic message will be produced. Otherwise, an
3264 /// extra note will be emitted pointing to location of the format string.
3266 /// \param ArgumentExpr the expression that is passed as the format string
3267 /// argument in the function call. Used for getting locations when two
3268 /// diagnostics are emitted.
3270 /// \param PDiag the callee should already have provided any strings for the
3271 /// diagnostic message. This function only adds locations and fixits
3274 /// \param Loc primary location for diagnostic. If two diagnostics are
3275 /// required, one will be at Loc and a new SourceLocation will be created for
3278 /// \param IsStringLocation if true, Loc points to the format string should be
3279 /// used for the note. Otherwise, Loc points to the argument list and will
3280 /// be used with PDiag.
3282 /// \param StringRange some or all of the string to highlight. This is
3283 /// templated so it can accept either a CharSourceRange or a SourceRange.
3285 /// \param FixIt optional fix it hint for the format string.
3286 template<typename Range>
3287 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3288 const Expr *ArgumentExpr,
3289 PartialDiagnostic PDiag,
3291 bool IsStringLocation,
3293 ArrayRef<FixItHint> FixIt) {
3294 if (InFunctionCall) {
3295 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3299 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3300 << ArgumentExpr->getSourceRange();
3302 const Sema::SemaDiagnosticBuilder &Note =
3303 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3304 diag::note_format_string_defined);
3306 Note << StringRange;
3311 //===--- CHECK: Printf format string checking ------------------------------===//
3314 class CheckPrintfHandler : public CheckFormatHandler {
3317 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3318 const Expr *origFormatExpr, unsigned firstDataArg,
3319 unsigned numDataArgs, bool isObjC,
3320 const char *beg, bool hasVAListArg,
3321 ArrayRef<const Expr *> Args,
3322 unsigned formatIdx, bool inFunctionCall,
3323 Sema::VariadicCallType CallType,
3324 llvm::SmallBitVector &CheckedVarArgs)
3325 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3326 numDataArgs, beg, hasVAListArg, Args,
3327 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3332 bool HandleInvalidPrintfConversionSpecifier(
3333 const analyze_printf::PrintfSpecifier &FS,
3334 const char *startSpecifier,
3335 unsigned specifierLen) override;
3337 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3338 const char *startSpecifier,
3339 unsigned specifierLen) override;
3340 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3341 const char *StartSpecifier,
3342 unsigned SpecifierLen,
3345 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3346 const char *startSpecifier, unsigned specifierLen);
3347 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3348 const analyze_printf::OptionalAmount &Amt,
3350 const char *startSpecifier, unsigned specifierLen);
3351 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3352 const analyze_printf::OptionalFlag &flag,
3353 const char *startSpecifier, unsigned specifierLen);
3354 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3355 const analyze_printf::OptionalFlag &ignoredFlag,
3356 const analyze_printf::OptionalFlag &flag,
3357 const char *startSpecifier, unsigned specifierLen);
3358 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
3364 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3365 const analyze_printf::PrintfSpecifier &FS,
3366 const char *startSpecifier,
3367 unsigned specifierLen) {
3368 const analyze_printf::PrintfConversionSpecifier &CS =
3369 FS.getConversionSpecifier();
3371 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3372 getLocationOfByte(CS.getStart()),
3373 startSpecifier, specifierLen,
3374 CS.getStart(), CS.getLength());
3377 bool CheckPrintfHandler::HandleAmount(
3378 const analyze_format_string::OptionalAmount &Amt,
3379 unsigned k, const char *startSpecifier,
3380 unsigned specifierLen) {
3382 if (Amt.hasDataArgument()) {
3383 if (!HasVAListArg) {
3384 unsigned argIndex = Amt.getArgIndex();
3385 if (argIndex >= NumDataArgs) {
3386 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3388 getLocationOfByte(Amt.getStart()),
3389 /*IsStringLocation*/true,
3390 getSpecifierRange(startSpecifier, specifierLen));
3391 // Don't do any more checking. We will just emit
3396 // Type check the data argument. It should be an 'int'.
3397 // Although not in conformance with C99, we also allow the argument to be
3398 // an 'unsigned int' as that is a reasonably safe case. GCC also
3399 // doesn't emit a warning for that case.
3400 CoveredArgs.set(argIndex);
3401 const Expr *Arg = getDataArg(argIndex);
3405 QualType T = Arg->getType();
3407 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3408 assert(AT.isValid());
3410 if (!AT.matchesType(S.Context, T)) {
3411 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
3412 << k << AT.getRepresentativeTypeName(S.Context)
3413 << T << Arg->getSourceRange(),
3414 getLocationOfByte(Amt.getStart()),
3415 /*IsStringLocation*/true,
3416 getSpecifierRange(startSpecifier, specifierLen));
3417 // Don't do any more checking. We will just emit
3426 void CheckPrintfHandler::HandleInvalidAmount(
3427 const analyze_printf::PrintfSpecifier &FS,
3428 const analyze_printf::OptionalAmount &Amt,
3430 const char *startSpecifier,
3431 unsigned specifierLen) {
3432 const analyze_printf::PrintfConversionSpecifier &CS =
3433 FS.getConversionSpecifier();
3436 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3437 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3438 Amt.getConstantLength()))
3441 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3442 << type << CS.toString(),
3443 getLocationOfByte(Amt.getStart()),
3444 /*IsStringLocation*/true,
3445 getSpecifierRange(startSpecifier, specifierLen),
3449 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3450 const analyze_printf::OptionalFlag &flag,
3451 const char *startSpecifier,
3452 unsigned specifierLen) {
3453 // Warn about pointless flag with a fixit removal.
3454 const analyze_printf::PrintfConversionSpecifier &CS =
3455 FS.getConversionSpecifier();
3456 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3457 << flag.toString() << CS.toString(),
3458 getLocationOfByte(flag.getPosition()),
3459 /*IsStringLocation*/true,
3460 getSpecifierRange(startSpecifier, specifierLen),
3461 FixItHint::CreateRemoval(
3462 getSpecifierRange(flag.getPosition(), 1)));
3465 void CheckPrintfHandler::HandleIgnoredFlag(
3466 const analyze_printf::PrintfSpecifier &FS,
3467 const analyze_printf::OptionalFlag &ignoredFlag,
3468 const analyze_printf::OptionalFlag &flag,
3469 const char *startSpecifier,
3470 unsigned specifierLen) {
3471 // Warn about ignored flag with a fixit removal.
3472 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3473 << ignoredFlag.toString() << flag.toString(),
3474 getLocationOfByte(ignoredFlag.getPosition()),
3475 /*IsStringLocation*/true,
3476 getSpecifierRange(startSpecifier, specifierLen),
3477 FixItHint::CreateRemoval(
3478 getSpecifierRange(ignoredFlag.getPosition(), 1)));
3481 // Determines if the specified is a C++ class or struct containing
3482 // a member with the specified name and kind (e.g. a CXXMethodDecl named
3484 template<typename MemberKind>
3485 static llvm::SmallPtrSet<MemberKind*, 1>
3486 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3487 const RecordType *RT = Ty->getAs<RecordType>();
3488 llvm::SmallPtrSet<MemberKind*, 1> Results;
3492 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3493 if (!RD || !RD->getDefinition())
3496 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
3497 Sema::LookupMemberName);
3498 R.suppressDiagnostics();
3500 // We just need to include all members of the right kind turned up by the
3501 // filter, at this point.
3502 if (S.LookupQualifiedName(R, RT->getDecl()))
3503 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3504 NamedDecl *decl = (*I)->getUnderlyingDecl();
3505 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3511 /// Check if we could call '.c_str()' on an object.
3513 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3514 /// allow the call, or if it would be ambiguous).
3515 bool Sema::hasCStrMethod(const Expr *E) {
3516 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3518 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3519 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3521 if ((*MI)->getMinRequiredArguments() == 0)
3526 // Check if a (w)string was passed when a (w)char* was needed, and offer a
3527 // better diagnostic if so. AT is assumed to be valid.
3528 // Returns true when a c_str() conversion method is found.
3529 bool CheckPrintfHandler::checkForCStrMembers(
3530 const analyze_printf::ArgType &AT, const Expr *E) {
3531 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3534 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3536 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3538 const CXXMethodDecl *Method = *MI;
3539 if (Method->getMinRequiredArguments() == 0 &&
3540 AT.matchesType(S.Context, Method->getReturnType())) {
3541 // FIXME: Suggest parens if the expression needs them.
3542 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
3543 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3545 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3554 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
3556 const char *startSpecifier,
3557 unsigned specifierLen) {
3559 using namespace analyze_format_string;
3560 using namespace analyze_printf;
3561 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
3563 if (FS.consumesDataArgument()) {
3566 usesPositionalArgs = FS.usesPositionalArg();
3568 else if (usesPositionalArgs != FS.usesPositionalArg()) {
3569 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3570 startSpecifier, specifierLen);
3575 // First check if the field width, precision, and conversion specifier
3576 // have matching data arguments.
3577 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3578 startSpecifier, specifierLen)) {
3582 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3583 startSpecifier, specifierLen)) {
3587 if (!CS.consumesDataArgument()) {
3588 // FIXME: Technically specifying a precision or field width here
3589 // makes no sense. Worth issuing a warning at some point.
3593 // Consume the argument.
3594 unsigned argIndex = FS.getArgIndex();
3595 if (argIndex < NumDataArgs) {
3596 // The check to see if the argIndex is valid will come later.
3597 // We set the bit here because we may exit early from this
3598 // function if we encounter some other error.
3599 CoveredArgs.set(argIndex);
3602 // FreeBSD kernel extensions.
3603 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3604 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3605 // We need at least two arguments.
3606 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3609 // Claim the second argument.
3610 CoveredArgs.set(argIndex + 1);
3612 // Type check the first argument (int for %b, pointer for %D)
3613 const Expr *Ex = getDataArg(argIndex);
3614 const analyze_printf::ArgType &AT =
3615 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3616 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3617 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3618 EmitFormatDiagnostic(
3619 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3620 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3621 << false << Ex->getSourceRange(),
3622 Ex->getLocStart(), /*IsStringLocation*/false,
3623 getSpecifierRange(startSpecifier, specifierLen));
3625 // Type check the second argument (char * for both %b and %D)
3626 Ex = getDataArg(argIndex + 1);
3627 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3628 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3629 EmitFormatDiagnostic(
3630 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3631 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3632 << false << Ex->getSourceRange(),
3633 Ex->getLocStart(), /*IsStringLocation*/false,
3634 getSpecifierRange(startSpecifier, specifierLen));
3639 // Check for using an Objective-C specific conversion specifier
3640 // in a non-ObjC literal.
3641 if (!ObjCContext && CS.isObjCArg()) {
3642 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3646 // Check for invalid use of field width
3647 if (!FS.hasValidFieldWidth()) {
3648 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3649 startSpecifier, specifierLen);
3652 // Check for invalid use of precision
3653 if (!FS.hasValidPrecision()) {
3654 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3655 startSpecifier, specifierLen);
3658 // Check each flag does not conflict with any other component.
3659 if (!FS.hasValidThousandsGroupingPrefix())
3660 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3661 if (!FS.hasValidLeadingZeros())
3662 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3663 if (!FS.hasValidPlusPrefix())
3664 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3665 if (!FS.hasValidSpacePrefix())
3666 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3667 if (!FS.hasValidAlternativeForm())
3668 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3669 if (!FS.hasValidLeftJustified())
3670 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3672 // Check that flags are not ignored by another flag
3673 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3674 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3675 startSpecifier, specifierLen);
3676 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3677 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3678 startSpecifier, specifierLen);
3680 // Check the length modifier is valid with the given conversion specifier.
3681 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3682 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3683 diag::warn_format_nonsensical_length);
3684 else if (!FS.hasStandardLengthModifier())
3685 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3686 else if (!FS.hasStandardLengthConversionCombination())
3687 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3688 diag::warn_format_non_standard_conversion_spec);
3690 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3691 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3693 // The remaining checks depend on the data arguments.
3697 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3700 const Expr *Arg = getDataArg(argIndex);
3704 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3707 static bool requiresParensToAddCast(const Expr *E) {
3708 // FIXME: We should have a general way to reason about operator
3709 // precedence and whether parens are actually needed here.
3710 // Take care of a few common cases where they aren't.
3711 const Expr *Inside = E->IgnoreImpCasts();
3712 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3713 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3715 switch (Inside->getStmtClass()) {
3716 case Stmt::ArraySubscriptExprClass:
3717 case Stmt::CallExprClass:
3718 case Stmt::CharacterLiteralClass:
3719 case Stmt::CXXBoolLiteralExprClass:
3720 case Stmt::DeclRefExprClass:
3721 case Stmt::FloatingLiteralClass:
3722 case Stmt::IntegerLiteralClass:
3723 case Stmt::MemberExprClass:
3724 case Stmt::ObjCArrayLiteralClass:
3725 case Stmt::ObjCBoolLiteralExprClass:
3726 case Stmt::ObjCBoxedExprClass:
3727 case Stmt::ObjCDictionaryLiteralClass:
3728 case Stmt::ObjCEncodeExprClass:
3729 case Stmt::ObjCIvarRefExprClass:
3730 case Stmt::ObjCMessageExprClass:
3731 case Stmt::ObjCPropertyRefExprClass:
3732 case Stmt::ObjCStringLiteralClass:
3733 case Stmt::ObjCSubscriptRefExprClass:
3734 case Stmt::ParenExprClass:
3735 case Stmt::StringLiteralClass:
3736 case Stmt::UnaryOperatorClass:
3743 static std::pair<QualType, StringRef>
3744 shouldNotPrintDirectly(const ASTContext &Context,
3745 QualType IntendedTy,
3747 // Use a 'while' to peel off layers of typedefs.
3748 QualType TyTy = IntendedTy;
3749 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3750 StringRef Name = UserTy->getDecl()->getName();
3751 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3752 .Case("NSInteger", Context.LongTy)
3753 .Case("NSUInteger", Context.UnsignedLongTy)
3754 .Case("SInt32", Context.IntTy)
3755 .Case("UInt32", Context.UnsignedIntTy)
3756 .Default(QualType());
3758 if (!CastTy.isNull())
3759 return std::make_pair(CastTy, Name);
3761 TyTy = UserTy->desugar();
3764 // Strip parens if necessary.
3765 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3766 return shouldNotPrintDirectly(Context,
3767 PE->getSubExpr()->getType(),
3770 // If this is a conditional expression, then its result type is constructed
3771 // via usual arithmetic conversions and thus there might be no necessary
3772 // typedef sugar there. Recurse to operands to check for NSInteger &
3773 // Co. usage condition.
3774 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3775 QualType TrueTy, FalseTy;
3776 StringRef TrueName, FalseName;
3778 std::tie(TrueTy, TrueName) =
3779 shouldNotPrintDirectly(Context,
3780 CO->getTrueExpr()->getType(),
3782 std::tie(FalseTy, FalseName) =
3783 shouldNotPrintDirectly(Context,
3784 CO->getFalseExpr()->getType(),
3785 CO->getFalseExpr());
3787 if (TrueTy == FalseTy)
3788 return std::make_pair(TrueTy, TrueName);
3789 else if (TrueTy.isNull())
3790 return std::make_pair(FalseTy, FalseName);
3791 else if (FalseTy.isNull())
3792 return std::make_pair(TrueTy, TrueName);
3795 return std::make_pair(QualType(), StringRef());
3799 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3800 const char *StartSpecifier,
3801 unsigned SpecifierLen,
3803 using namespace analyze_format_string;
3804 using namespace analyze_printf;
3805 // Now type check the data expression that matches the
3806 // format specifier.
3807 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3812 QualType ExprTy = E->getType();
3813 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3814 ExprTy = TET->getUnderlyingExpr()->getType();
3817 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3819 if (match == analyze_printf::ArgType::Match) {
3823 // Look through argument promotions for our error message's reported type.
3824 // This includes the integral and floating promotions, but excludes array
3825 // and function pointer decay; seeing that an argument intended to be a
3826 // string has type 'char [6]' is probably more confusing than 'char *'.
3827 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3828 if (ICE->getCastKind() == CK_IntegralCast ||
3829 ICE->getCastKind() == CK_FloatingCast) {
3830 E = ICE->getSubExpr();
3831 ExprTy = E->getType();
3833 // Check if we didn't match because of an implicit cast from a 'char'
3834 // or 'short' to an 'int'. This is done because printf is a varargs
3836 if (ICE->getType() == S.Context.IntTy ||
3837 ICE->getType() == S.Context.UnsignedIntTy) {
3838 // All further checking is done on the subexpression.
3839 if (AT.matchesType(S.Context, ExprTy))
3843 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3844 // Special case for 'a', which has type 'int' in C.
3845 // Note, however, that we do /not/ want to treat multibyte constants like
3846 // 'MooV' as characters! This form is deprecated but still exists.
3847 if (ExprTy == S.Context.IntTy)
3848 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3849 ExprTy = S.Context.CharTy;
3852 // Look through enums to their underlying type.
3853 bool IsEnum = false;
3854 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3855 ExprTy = EnumTy->getDecl()->getIntegerType();
3859 // %C in an Objective-C context prints a unichar, not a wchar_t.
3860 // If the argument is an integer of some kind, believe the %C and suggest
3861 // a cast instead of changing the conversion specifier.
3862 QualType IntendedTy = ExprTy;
3864 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3865 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3866 !ExprTy->isCharType()) {
3867 // 'unichar' is defined as a typedef of unsigned short, but we should
3868 // prefer using the typedef if it is visible.
3869 IntendedTy = S.Context.UnsignedShortTy;
3871 // While we are here, check if the value is an IntegerLiteral that happens
3872 // to be within the valid range.
3873 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3874 const llvm::APInt &V = IL->getValue();
3875 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3879 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3880 Sema::LookupOrdinaryName);
3881 if (S.LookupName(Result, S.getCurScope())) {
3882 NamedDecl *ND = Result.getFoundDecl();
3883 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3884 if (TD->getUnderlyingType() == IntendedTy)
3885 IntendedTy = S.Context.getTypedefType(TD);
3890 // Special-case some of Darwin's platform-independence types by suggesting
3891 // casts to primitive types that are known to be large enough.
3892 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
3893 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3895 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3896 if (!CastTy.isNull()) {
3897 IntendedTy = CastTy;
3898 ShouldNotPrintDirectly = true;
3902 // We may be able to offer a FixItHint if it is a supported type.
3903 PrintfSpecifier fixedFS = FS;
3904 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3905 S.Context, ObjCContext);
3908 // Get the fix string from the fixed format specifier
3909 SmallString<16> buf;
3910 llvm::raw_svector_ostream os(buf);
3911 fixedFS.toString(os);
3913 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3915 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
3916 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3917 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3918 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3920 // In this case, the specifier is wrong and should be changed to match
3922 EmitFormatDiagnostic(S.PDiag(diag)
3923 << AT.getRepresentativeTypeName(S.Context)
3924 << IntendedTy << IsEnum << E->getSourceRange(),
3926 /*IsStringLocation*/ false, SpecRange,
3927 FixItHint::CreateReplacement(SpecRange, os.str()));
3930 // The canonical type for formatting this value is different from the
3931 // actual type of the expression. (This occurs, for example, with Darwin's
3932 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3933 // should be printed as 'long' for 64-bit compatibility.)
3934 // Rather than emitting a normal format/argument mismatch, we want to
3935 // add a cast to the recommended type (and correct the format string
3937 SmallString<16> CastBuf;
3938 llvm::raw_svector_ostream CastFix(CastBuf);
3940 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3943 SmallVector<FixItHint,4> Hints;
3944 if (!AT.matchesType(S.Context, IntendedTy))
3945 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3947 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3948 // If there's already a cast present, just replace it.
3949 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3950 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3952 } else if (!requiresParensToAddCast(E)) {
3953 // If the expression has high enough precedence,
3954 // just write the C-style cast.
3955 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3958 // Otherwise, add parens around the expression as well as the cast.
3960 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3963 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
3964 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3967 if (ShouldNotPrintDirectly) {
3968 // The expression has a type that should not be printed directly.
3969 // We extract the name from the typedef because we don't want to show
3970 // the underlying type in the diagnostic.
3972 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3973 Name = TypedefTy->getDecl()->getName();
3976 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3977 << Name << IntendedTy << IsEnum
3978 << E->getSourceRange(),
3979 E->getLocStart(), /*IsStringLocation=*/false,
3982 // In this case, the expression could be printed using a different
3983 // specifier, but we've decided that the specifier is probably correct
3984 // and we should cast instead. Just use the normal warning message.
3985 EmitFormatDiagnostic(
3986 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3987 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3988 << E->getSourceRange(),
3989 E->getLocStart(), /*IsStringLocation*/false,
3994 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3996 // Since the warning for passing non-POD types to variadic functions
3997 // was deferred until now, we emit a warning for non-POD
3999 switch (S.isValidVarArgType(ExprTy)) {
4000 case Sema::VAK_Valid:
4001 case Sema::VAK_ValidInCXX11: {
4002 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4003 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4004 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4007 EmitFormatDiagnostic(
4008 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4009 << IsEnum << CSR << E->getSourceRange(),
4010 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4013 case Sema::VAK_Undefined:
4014 case Sema::VAK_MSVCUndefined:
4015 EmitFormatDiagnostic(
4016 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
4017 << S.getLangOpts().CPlusPlus11
4020 << AT.getRepresentativeTypeName(S.Context)
4022 << E->getSourceRange(),
4023 E->getLocStart(), /*IsStringLocation*/false, CSR);
4024 checkForCStrMembers(AT, E);
4027 case Sema::VAK_Invalid:
4028 if (ExprTy->isObjCObjectType())
4029 EmitFormatDiagnostic(
4030 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4031 << S.getLangOpts().CPlusPlus11
4034 << AT.getRepresentativeTypeName(S.Context)
4036 << E->getSourceRange(),
4037 E->getLocStart(), /*IsStringLocation*/false, CSR);
4039 // FIXME: If this is an initializer list, suggest removing the braces
4040 // or inserting a cast to the target type.
4041 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4042 << isa<InitListExpr>(E) << ExprTy << CallType
4043 << AT.getRepresentativeTypeName(S.Context)
4044 << E->getSourceRange();
4048 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4049 "format string specifier index out of range");
4050 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
4056 //===--- CHECK: Scanf format string checking ------------------------------===//
4059 class CheckScanfHandler : public CheckFormatHandler {
4061 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4062 const Expr *origFormatExpr, unsigned firstDataArg,
4063 unsigned numDataArgs, const char *beg, bool hasVAListArg,
4064 ArrayRef<const Expr *> Args,
4065 unsigned formatIdx, bool inFunctionCall,
4066 Sema::VariadicCallType CallType,
4067 llvm::SmallBitVector &CheckedVarArgs)
4068 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4069 numDataArgs, beg, hasVAListArg,
4070 Args, formatIdx, inFunctionCall, CallType,
4074 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4075 const char *startSpecifier,
4076 unsigned specifierLen) override;
4078 bool HandleInvalidScanfConversionSpecifier(
4079 const analyze_scanf::ScanfSpecifier &FS,
4080 const char *startSpecifier,
4081 unsigned specifierLen) override;
4083 void HandleIncompleteScanList(const char *start, const char *end) override;
4087 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4089 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4090 getLocationOfByte(end), /*IsStringLocation*/true,
4091 getSpecifierRange(start, end - start));
4094 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4095 const analyze_scanf::ScanfSpecifier &FS,
4096 const char *startSpecifier,
4097 unsigned specifierLen) {
4099 const analyze_scanf::ScanfConversionSpecifier &CS =
4100 FS.getConversionSpecifier();
4102 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4103 getLocationOfByte(CS.getStart()),
4104 startSpecifier, specifierLen,
4105 CS.getStart(), CS.getLength());
4108 bool CheckScanfHandler::HandleScanfSpecifier(
4109 const analyze_scanf::ScanfSpecifier &FS,
4110 const char *startSpecifier,
4111 unsigned specifierLen) {
4113 using namespace analyze_scanf;
4114 using namespace analyze_format_string;
4116 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
4118 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4119 // be used to decide if we are using positional arguments consistently.
4120 if (FS.consumesDataArgument()) {
4123 usesPositionalArgs = FS.usesPositionalArg();
4125 else if (usesPositionalArgs != FS.usesPositionalArg()) {
4126 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4127 startSpecifier, specifierLen);
4132 // Check if the field with is non-zero.
4133 const OptionalAmount &Amt = FS.getFieldWidth();
4134 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4135 if (Amt.getConstantAmount() == 0) {
4136 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4137 Amt.getConstantLength());
4138 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4139 getLocationOfByte(Amt.getStart()),
4140 /*IsStringLocation*/true, R,
4141 FixItHint::CreateRemoval(R));
4145 if (!FS.consumesDataArgument()) {
4146 // FIXME: Technically specifying a precision or field width here
4147 // makes no sense. Worth issuing a warning at some point.
4151 // Consume the argument.
4152 unsigned argIndex = FS.getArgIndex();
4153 if (argIndex < NumDataArgs) {
4154 // The check to see if the argIndex is valid will come later.
4155 // We set the bit here because we may exit early from this
4156 // function if we encounter some other error.
4157 CoveredArgs.set(argIndex);
4160 // Check the length modifier is valid with the given conversion specifier.
4161 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
4162 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4163 diag::warn_format_nonsensical_length);
4164 else if (!FS.hasStandardLengthModifier())
4165 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4166 else if (!FS.hasStandardLengthConversionCombination())
4167 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4168 diag::warn_format_non_standard_conversion_spec);
4170 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4171 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4173 // The remaining checks depend on the data arguments.
4177 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4180 // Check that the argument type matches the format specifier.
4181 const Expr *Ex = getDataArg(argIndex);
4185 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
4187 if (!AT.isValid()) {
4191 analyze_format_string::ArgType::MatchKind match =
4192 AT.matchesType(S.Context, Ex->getType());
4193 if (match == analyze_format_string::ArgType::Match) {
4197 ScanfSpecifier fixedFS = FS;
4198 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4199 S.getLangOpts(), S.Context);
4201 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4202 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4203 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4207 // Get the fix string from the fixed format specifier.
4208 SmallString<128> buf;
4209 llvm::raw_svector_ostream os(buf);
4210 fixedFS.toString(os);
4212 EmitFormatDiagnostic(
4213 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4214 << Ex->getType() << false << Ex->getSourceRange(),
4216 /*IsStringLocation*/ false,
4217 getSpecifierRange(startSpecifier, specifierLen),
4218 FixItHint::CreateReplacement(
4219 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4221 EmitFormatDiagnostic(S.PDiag(diag)
4222 << AT.getRepresentativeTypeName(S.Context)
4223 << Ex->getType() << false << Ex->getSourceRange(),
4225 /*IsStringLocation*/ false,
4226 getSpecifierRange(startSpecifier, specifierLen));
4232 void Sema::CheckFormatString(const StringLiteral *FExpr,
4233 const Expr *OrigFormatExpr,
4234 ArrayRef<const Expr *> Args,
4235 bool HasVAListArg, unsigned format_idx,
4236 unsigned firstDataArg, FormatStringType Type,
4237 bool inFunctionCall, VariadicCallType CallType,
4238 llvm::SmallBitVector &CheckedVarArgs) {
4240 // CHECK: is the format string a wide literal?
4241 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
4242 CheckFormatHandler::EmitFormatDiagnostic(
4243 *this, inFunctionCall, Args[format_idx],
4244 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4245 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4249 // Str - The format string. NOTE: this is NOT null-terminated!
4250 StringRef StrRef = FExpr->getString();
4251 const char *Str = StrRef.data();
4252 // Account for cases where the string literal is truncated in a declaration.
4253 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4254 assert(T && "String literal not of constant array type!");
4255 size_t TypeSize = T->getSize().getZExtValue();
4256 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4257 const unsigned numDataArgs = Args.size() - firstDataArg;
4259 // Emit a warning if the string literal is truncated and does not contain an
4260 // embedded null character.
4261 if (TypeSize <= StrRef.size() &&
4262 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4263 CheckFormatHandler::EmitFormatDiagnostic(
4264 *this, inFunctionCall, Args[format_idx],
4265 PDiag(diag::warn_printf_format_string_not_null_terminated),
4266 FExpr->getLocStart(),
4267 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4271 // CHECK: empty format string?
4272 if (StrLen == 0 && numDataArgs > 0) {
4273 CheckFormatHandler::EmitFormatDiagnostic(
4274 *this, inFunctionCall, Args[format_idx],
4275 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4276 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4280 if (Type == FST_Printf || Type == FST_NSString ||
4281 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
4282 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
4283 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
4284 Str, HasVAListArg, Args, format_idx,
4285 inFunctionCall, CallType, CheckedVarArgs);
4287 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
4289 Context.getTargetInfo(),
4290 Type == FST_FreeBSDKPrintf))
4292 } else if (Type == FST_Scanf) {
4293 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
4294 Str, HasVAListArg, Args, format_idx,
4295 inFunctionCall, CallType, CheckedVarArgs);
4297 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
4299 Context.getTargetInfo()))
4301 } // TODO: handle other formats
4304 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4305 // Str - The format string. NOTE: this is NOT null-terminated!
4306 StringRef StrRef = FExpr->getString();
4307 const char *Str = StrRef.data();
4308 // Account for cases where the string literal is truncated in a declaration.
4309 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4310 assert(T && "String literal not of constant array type!");
4311 size_t TypeSize = T->getSize().getZExtValue();
4312 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4313 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4315 Context.getTargetInfo());
4318 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4320 // Returns the related absolute value function that is larger, of 0 if one
4322 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4323 switch (AbsFunction) {
4327 case Builtin::BI__builtin_abs:
4328 return Builtin::BI__builtin_labs;
4329 case Builtin::BI__builtin_labs:
4330 return Builtin::BI__builtin_llabs;
4331 case Builtin::BI__builtin_llabs:
4334 case Builtin::BI__builtin_fabsf:
4335 return Builtin::BI__builtin_fabs;
4336 case Builtin::BI__builtin_fabs:
4337 return Builtin::BI__builtin_fabsl;
4338 case Builtin::BI__builtin_fabsl:
4341 case Builtin::BI__builtin_cabsf:
4342 return Builtin::BI__builtin_cabs;
4343 case Builtin::BI__builtin_cabs:
4344 return Builtin::BI__builtin_cabsl;
4345 case Builtin::BI__builtin_cabsl:
4348 case Builtin::BIabs:
4349 return Builtin::BIlabs;
4350 case Builtin::BIlabs:
4351 return Builtin::BIllabs;
4352 case Builtin::BIllabs:
4355 case Builtin::BIfabsf:
4356 return Builtin::BIfabs;
4357 case Builtin::BIfabs:
4358 return Builtin::BIfabsl;
4359 case Builtin::BIfabsl:
4362 case Builtin::BIcabsf:
4363 return Builtin::BIcabs;
4364 case Builtin::BIcabs:
4365 return Builtin::BIcabsl;
4366 case Builtin::BIcabsl:
4371 // Returns the argument type of the absolute value function.
4372 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4377 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4378 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4379 if (Error != ASTContext::GE_None)
4382 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4386 if (FT->getNumParams() != 1)
4389 return FT->getParamType(0);
4392 // Returns the best absolute value function, or zero, based on type and
4393 // current absolute value function.
4394 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4395 unsigned AbsFunctionKind) {
4396 unsigned BestKind = 0;
4397 uint64_t ArgSize = Context.getTypeSize(ArgType);
4398 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4399 Kind = getLargerAbsoluteValueFunction(Kind)) {
4400 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4401 if (Context.getTypeSize(ParamType) >= ArgSize) {
4404 else if (Context.hasSameType(ParamType, ArgType)) {
4413 enum AbsoluteValueKind {
4419 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4420 if (T->isIntegralOrEnumerationType())
4422 if (T->isRealFloatingType())
4423 return AVK_Floating;
4424 if (T->isAnyComplexType())
4427 llvm_unreachable("Type not integer, floating, or complex");
4430 // Changes the absolute value function to a different type. Preserves whether
4431 // the function is a builtin.
4432 static unsigned changeAbsFunction(unsigned AbsKind,
4433 AbsoluteValueKind ValueKind) {
4434 switch (ValueKind) {
4439 case Builtin::BI__builtin_fabsf:
4440 case Builtin::BI__builtin_fabs:
4441 case Builtin::BI__builtin_fabsl:
4442 case Builtin::BI__builtin_cabsf:
4443 case Builtin::BI__builtin_cabs:
4444 case Builtin::BI__builtin_cabsl:
4445 return Builtin::BI__builtin_abs;
4446 case Builtin::BIfabsf:
4447 case Builtin::BIfabs:
4448 case Builtin::BIfabsl:
4449 case Builtin::BIcabsf:
4450 case Builtin::BIcabs:
4451 case Builtin::BIcabsl:
4452 return Builtin::BIabs;
4458 case Builtin::BI__builtin_abs:
4459 case Builtin::BI__builtin_labs:
4460 case Builtin::BI__builtin_llabs:
4461 case Builtin::BI__builtin_cabsf:
4462 case Builtin::BI__builtin_cabs:
4463 case Builtin::BI__builtin_cabsl:
4464 return Builtin::BI__builtin_fabsf;
4465 case Builtin::BIabs:
4466 case Builtin::BIlabs:
4467 case Builtin::BIllabs:
4468 case Builtin::BIcabsf:
4469 case Builtin::BIcabs:
4470 case Builtin::BIcabsl:
4471 return Builtin::BIfabsf;
4477 case Builtin::BI__builtin_abs:
4478 case Builtin::BI__builtin_labs:
4479 case Builtin::BI__builtin_llabs:
4480 case Builtin::BI__builtin_fabsf:
4481 case Builtin::BI__builtin_fabs:
4482 case Builtin::BI__builtin_fabsl:
4483 return Builtin::BI__builtin_cabsf;
4484 case Builtin::BIabs:
4485 case Builtin::BIlabs:
4486 case Builtin::BIllabs:
4487 case Builtin::BIfabsf:
4488 case Builtin::BIfabs:
4489 case Builtin::BIfabsl:
4490 return Builtin::BIcabsf;
4493 llvm_unreachable("Unable to convert function");
4496 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4497 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4501 switch (FDecl->getBuiltinID()) {
4504 case Builtin::BI__builtin_abs:
4505 case Builtin::BI__builtin_fabs:
4506 case Builtin::BI__builtin_fabsf:
4507 case Builtin::BI__builtin_fabsl:
4508 case Builtin::BI__builtin_labs:
4509 case Builtin::BI__builtin_llabs:
4510 case Builtin::BI__builtin_cabs:
4511 case Builtin::BI__builtin_cabsf:
4512 case Builtin::BI__builtin_cabsl:
4513 case Builtin::BIabs:
4514 case Builtin::BIlabs:
4515 case Builtin::BIllabs:
4516 case Builtin::BIfabs:
4517 case Builtin::BIfabsf:
4518 case Builtin::BIfabsl:
4519 case Builtin::BIcabs:
4520 case Builtin::BIcabsf:
4521 case Builtin::BIcabsl:
4522 return FDecl->getBuiltinID();
4524 llvm_unreachable("Unknown Builtin type");
4527 // If the replacement is valid, emit a note with replacement function.
4528 // Additionally, suggest including the proper header if not already included.
4529 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
4530 unsigned AbsKind, QualType ArgType) {
4531 bool EmitHeaderHint = true;
4532 const char *HeaderName = nullptr;
4533 const char *FunctionName = nullptr;
4534 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4535 FunctionName = "std::abs";
4536 if (ArgType->isIntegralOrEnumerationType()) {
4537 HeaderName = "cstdlib";
4538 } else if (ArgType->isRealFloatingType()) {
4539 HeaderName = "cmath";
4541 llvm_unreachable("Invalid Type");
4544 // Lookup all std::abs
4545 if (NamespaceDecl *Std = S.getStdNamespace()) {
4546 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4547 R.suppressDiagnostics();
4548 S.LookupQualifiedName(R, Std);
4550 for (const auto *I : R) {
4551 const FunctionDecl *FDecl = nullptr;
4552 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4553 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4555 FDecl = dyn_cast<FunctionDecl>(I);
4560 // Found std::abs(), check that they are the right ones.
4561 if (FDecl->getNumParams() != 1)
4564 // Check that the parameter type can handle the argument.
4565 QualType ParamType = FDecl->getParamDecl(0)->getType();
4566 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4567 S.Context.getTypeSize(ArgType) <=
4568 S.Context.getTypeSize(ParamType)) {
4569 // Found a function, don't need the header hint.
4570 EmitHeaderHint = false;
4576 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4577 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4580 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4581 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4582 R.suppressDiagnostics();
4583 S.LookupName(R, S.getCurScope());
4585 if (R.isSingleResult()) {
4586 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4587 if (FD && FD->getBuiltinID() == AbsKind) {
4588 EmitHeaderHint = false;
4592 } else if (!R.empty()) {
4598 S.Diag(Loc, diag::note_replace_abs_function)
4599 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
4604 if (!EmitHeaderHint)
4607 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4611 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4615 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4618 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4620 while (ND && ND->isInlineNamespace()) {
4621 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
4624 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4627 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4633 // Warn when using the wrong abs() function.
4634 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4635 const FunctionDecl *FDecl,
4636 IdentifierInfo *FnInfo) {
4637 if (Call->getNumArgs() != 1)
4640 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
4641 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4642 if (AbsKind == 0 && !IsStdAbs)
4645 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4646 QualType ParamType = Call->getArg(0)->getType();
4648 // Unsigned types cannot be negative. Suggest removing the absolute value
4650 if (ArgType->isUnsignedIntegerType()) {
4651 const char *FunctionName =
4652 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
4653 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4654 Diag(Call->getExprLoc(), diag::note_remove_abs)
4656 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4660 // std::abs has overloads which prevent most of the absolute value problems
4665 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4666 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4668 // The argument and parameter are the same kind. Check if they are the right
4670 if (ArgValueKind == ParamValueKind) {
4671 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4674 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4675 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4676 << FDecl << ArgType << ParamType;
4678 if (NewAbsKind == 0)
4681 emitReplacement(*this, Call->getExprLoc(),
4682 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4686 // ArgValueKind != ParamValueKind
4687 // The wrong type of absolute value function was used. Attempt to find the
4689 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4690 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4691 if (NewAbsKind == 0)
4694 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4695 << FDecl << ParamValueKind << ArgValueKind;
4697 emitReplacement(*this, Call->getExprLoc(),
4698 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4702 //===--- CHECK: Standard memory functions ---------------------------------===//
4704 /// \brief Takes the expression passed to the size_t parameter of functions
4705 /// such as memcmp, strncat, etc and warns if it's a comparison.
4707 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4708 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4709 IdentifierInfo *FnName,
4710 SourceLocation FnLoc,
4711 SourceLocation RParenLoc) {
4712 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4716 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4717 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4720 SourceRange SizeRange = Size->getSourceRange();
4721 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4722 << SizeRange << FnName;
4723 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4724 << FnName << FixItHint::CreateInsertion(
4725 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
4726 << FixItHint::CreateRemoval(RParenLoc);
4727 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
4728 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
4729 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4735 /// \brief Determine whether the given type is or contains a dynamic class type
4736 /// (e.g., whether it has a vtable).
4737 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4738 bool &IsContained) {
4739 // Look through array types while ignoring qualifiers.
4740 const Type *Ty = T->getBaseElementTypeUnsafe();
4741 IsContained = false;
4743 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4744 RD = RD ? RD->getDefinition() : nullptr;
4748 if (RD->isDynamicClass())
4751 // Check all the fields. If any bases were dynamic, the class is dynamic.
4752 // It's impossible for a class to transitively contain itself by value, so
4753 // infinite recursion is impossible.
4754 for (auto *FD : RD->fields()) {
4756 if (const CXXRecordDecl *ContainedRD =
4757 getContainedDynamicClass(FD->getType(), SubContained)) {
4766 /// \brief If E is a sizeof expression, returns its argument expression,
4767 /// otherwise returns NULL.
4768 static const Expr *getSizeOfExprArg(const Expr *E) {
4769 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4770 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4771 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4772 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
4777 /// \brief If E is a sizeof expression, returns its argument type.
4778 static QualType getSizeOfArgType(const Expr *E) {
4779 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4780 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4781 if (SizeOf->getKind() == clang::UETT_SizeOf)
4782 return SizeOf->getTypeOfArgument();
4787 /// \brief Check for dangerous or invalid arguments to memset().
4789 /// This issues warnings on known problematic, dangerous or unspecified
4790 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4793 /// \param Call The call expression to diagnose.
4794 void Sema::CheckMemaccessArguments(const CallExpr *Call,
4796 IdentifierInfo *FnName) {
4799 // It is possible to have a non-standard definition of memset. Validate
4800 // we have enough arguments, and if not, abort further checking.
4801 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4802 if (Call->getNumArgs() < ExpectedNumArgs)
4805 unsigned LastArg = (BId == Builtin::BImemset ||
4806 BId == Builtin::BIstrndup ? 1 : 2);
4807 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
4808 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4810 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4811 Call->getLocStart(), Call->getRParenLoc()))
4814 // We have special checking when the length is a sizeof expression.
4815 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4816 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4817 llvm::FoldingSetNodeID SizeOfArgID;
4819 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4820 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4821 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4823 QualType DestTy = Dest->getType();
4825 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4826 PointeeTy = DestPtrTy->getPointeeType();
4828 // Never warn about void type pointers. This can be used to suppress
4830 if (PointeeTy->isVoidType())
4833 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4834 // actually comparing the expressions for equality. Because computing the
4835 // expression IDs can be expensive, we only do this if the diagnostic is
4838 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4839 SizeOfArg->getExprLoc())) {
4840 // We only compute IDs for expressions if the warning is enabled, and
4841 // cache the sizeof arg's ID.
4842 if (SizeOfArgID == llvm::FoldingSetNodeID())
4843 SizeOfArg->Profile(SizeOfArgID, Context, true);
4844 llvm::FoldingSetNodeID DestID;
4845 Dest->Profile(DestID, Context, true);
4846 if (DestID == SizeOfArgID) {
4847 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4848 // over sizeof(src) as well.
4849 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4850 StringRef ReadableName = FnName->getName();
4852 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4853 if (UnaryOp->getOpcode() == UO_AddrOf)
4854 ActionIdx = 1; // If its an address-of operator, just remove it.
4855 if (!PointeeTy->isIncompleteType() &&
4856 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4857 ActionIdx = 2; // If the pointee's size is sizeof(char),
4858 // suggest an explicit length.
4860 // If the function is defined as a builtin macro, do not show macro
4862 SourceLocation SL = SizeOfArg->getExprLoc();
4863 SourceRange DSR = Dest->getSourceRange();
4864 SourceRange SSR = SizeOfArg->getSourceRange();
4865 SourceManager &SM = getSourceManager();
4867 if (SM.isMacroArgExpansion(SL)) {
4868 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4869 SL = SM.getSpellingLoc(SL);
4870 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4871 SM.getSpellingLoc(DSR.getEnd()));
4872 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4873 SM.getSpellingLoc(SSR.getEnd()));
4876 DiagRuntimeBehavior(SL, SizeOfArg,
4877 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4883 DiagRuntimeBehavior(SL, SizeOfArg,
4884 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4892 // Also check for cases where the sizeof argument is the exact same
4893 // type as the memory argument, and where it points to a user-defined
4895 if (SizeOfArgTy != QualType()) {
4896 if (PointeeTy->isRecordType() &&
4897 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4898 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4899 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4900 << FnName << SizeOfArgTy << ArgIdx
4901 << PointeeTy << Dest->getSourceRange()
4902 << LenExpr->getSourceRange());
4906 } else if (DestTy->isArrayType()) {
4910 if (PointeeTy == QualType())
4913 // Always complain about dynamic classes.
4915 if (const CXXRecordDecl *ContainedRD =
4916 getContainedDynamicClass(PointeeTy, IsContained)) {
4918 unsigned OperationType = 0;
4919 // "overwritten" if we're warning about the destination for any call
4920 // but memcmp; otherwise a verb appropriate to the call.
4921 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4922 if (BId == Builtin::BImemcpy)
4924 else if(BId == Builtin::BImemmove)
4926 else if (BId == Builtin::BImemcmp)
4930 DiagRuntimeBehavior(
4931 Dest->getExprLoc(), Dest,
4932 PDiag(diag::warn_dyn_class_memaccess)
4933 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4934 << FnName << IsContained << ContainedRD << OperationType
4935 << Call->getCallee()->getSourceRange());
4936 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4937 BId != Builtin::BImemset)
4938 DiagRuntimeBehavior(
4939 Dest->getExprLoc(), Dest,
4940 PDiag(diag::warn_arc_object_memaccess)
4941 << ArgIdx << FnName << PointeeTy
4942 << Call->getCallee()->getSourceRange());
4946 DiagRuntimeBehavior(
4947 Dest->getExprLoc(), Dest,
4948 PDiag(diag::note_bad_memaccess_silence)
4949 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4955 // A little helper routine: ignore addition and subtraction of integer literals.
4956 // This intentionally does not ignore all integer constant expressions because
4957 // we don't want to remove sizeof().
4958 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4959 Ex = Ex->IgnoreParenCasts();
4962 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4963 if (!BO || !BO->isAdditiveOp())
4966 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4967 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4969 if (isa<IntegerLiteral>(RHS))
4971 else if (isa<IntegerLiteral>(LHS))
4980 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4981 ASTContext &Context) {
4982 // Only handle constant-sized or VLAs, but not flexible members.
4983 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4984 // Only issue the FIXIT for arrays of size > 1.
4985 if (CAT->getSize().getSExtValue() <= 1)
4987 } else if (!Ty->isVariableArrayType()) {
4993 // Warn if the user has made the 'size' argument to strlcpy or strlcat
4994 // be the size of the source, instead of the destination.
4995 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4996 IdentifierInfo *FnName) {
4998 // Don't crash if the user has the wrong number of arguments
4999 unsigned NumArgs = Call->getNumArgs();
5000 if ((NumArgs != 3) && (NumArgs != 4))
5003 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5004 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
5005 const Expr *CompareWithSrc = nullptr;
5007 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5008 Call->getLocStart(), Call->getRParenLoc()))
5011 // Look for 'strlcpy(dst, x, sizeof(x))'
5012 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5013 CompareWithSrc = Ex;
5015 // Look for 'strlcpy(dst, x, strlen(x))'
5016 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
5017 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5018 SizeCall->getNumArgs() == 1)
5019 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5023 if (!CompareWithSrc)
5026 // Determine if the argument to sizeof/strlen is equal to the source
5027 // argument. In principle there's all kinds of things you could do
5028 // here, for instance creating an == expression and evaluating it with
5029 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5030 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5034 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5035 if (!CompareWithSrcDRE ||
5036 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5039 const Expr *OriginalSizeArg = Call->getArg(2);
5040 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5041 << OriginalSizeArg->getSourceRange() << FnName;
5043 // Output a FIXIT hint if the destination is an array (rather than a
5044 // pointer to an array). This could be enhanced to handle some
5045 // pointers if we know the actual size, like if DstArg is 'array+2'
5046 // we could say 'sizeof(array)-2'.
5047 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
5048 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
5051 SmallString<128> sizeString;
5052 llvm::raw_svector_ostream OS(sizeString);
5054 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5057 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5058 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5062 /// Check if two expressions refer to the same declaration.
5063 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5064 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5065 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5066 return D1->getDecl() == D2->getDecl();
5070 static const Expr *getStrlenExprArg(const Expr *E) {
5071 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5072 const FunctionDecl *FD = CE->getDirectCallee();
5073 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
5075 return CE->getArg(0)->IgnoreParenCasts();
5080 // Warn on anti-patterns as the 'size' argument to strncat.
5081 // The correct size argument should look like following:
5082 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5083 void Sema::CheckStrncatArguments(const CallExpr *CE,
5084 IdentifierInfo *FnName) {
5085 // Don't crash if the user has the wrong number of arguments.
5086 if (CE->getNumArgs() < 3)
5088 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5089 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5090 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5092 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5093 CE->getRParenLoc()))
5096 // Identify common expressions, which are wrongly used as the size argument
5097 // to strncat and may lead to buffer overflows.
5098 unsigned PatternType = 0;
5099 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5101 if (referToTheSameDecl(SizeOfArg, DstArg))
5104 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5106 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5107 if (BE->getOpcode() == BO_Sub) {
5108 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5109 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5110 // - sizeof(dst) - strlen(dst)
5111 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5112 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5114 // - sizeof(src) - (anything)
5115 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5120 if (PatternType == 0)
5123 // Generate the diagnostic.
5124 SourceLocation SL = LenArg->getLocStart();
5125 SourceRange SR = LenArg->getSourceRange();
5126 SourceManager &SM = getSourceManager();
5128 // If the function is defined as a builtin macro, do not show macro expansion.
5129 if (SM.isMacroArgExpansion(SL)) {
5130 SL = SM.getSpellingLoc(SL);
5131 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5132 SM.getSpellingLoc(SR.getEnd()));
5135 // Check if the destination is an array (rather than a pointer to an array).
5136 QualType DstTy = DstArg->getType();
5137 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5139 if (!isKnownSizeArray) {
5140 if (PatternType == 1)
5141 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5143 Diag(SL, diag::warn_strncat_src_size) << SR;
5147 if (PatternType == 1)
5148 Diag(SL, diag::warn_strncat_large_size) << SR;
5150 Diag(SL, diag::warn_strncat_src_size) << SR;
5152 SmallString<128> sizeString;
5153 llvm::raw_svector_ostream OS(sizeString);
5155 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5158 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5161 Diag(SL, diag::note_strncat_wrong_size)
5162 << FixItHint::CreateReplacement(SR, OS.str());
5165 //===--- CHECK: Return Address of Stack Variable --------------------------===//
5167 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5169 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5172 /// CheckReturnStackAddr - Check if a return statement returns the address
5173 /// of a stack variable.
5175 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5176 SourceLocation ReturnLoc) {
5178 Expr *stackE = nullptr;
5179 SmallVector<DeclRefExpr *, 8> refVars;
5181 // Perform checking for returned stack addresses, local blocks,
5182 // label addresses or references to temporaries.
5183 if (lhsType->isPointerType() ||
5184 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
5185 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
5186 } else if (lhsType->isReferenceType()) {
5187 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
5191 return; // Nothing suspicious was found.
5193 SourceLocation diagLoc;
5194 SourceRange diagRange;
5195 if (refVars.empty()) {
5196 diagLoc = stackE->getLocStart();
5197 diagRange = stackE->getSourceRange();
5199 // We followed through a reference variable. 'stackE' contains the
5200 // problematic expression but we will warn at the return statement pointing
5201 // at the reference variable. We will later display the "trail" of
5202 // reference variables using notes.
5203 diagLoc = refVars[0]->getLocStart();
5204 diagRange = refVars[0]->getSourceRange();
5207 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
5208 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
5209 : diag::warn_ret_stack_addr)
5210 << DR->getDecl()->getDeclName() << diagRange;
5211 } else if (isa<BlockExpr>(stackE)) { // local block.
5212 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
5213 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
5214 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
5215 } else { // local temporary.
5216 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5217 : diag::warn_ret_local_temp_addr)
5221 // Display the "trail" of reference variables that we followed until we
5222 // found the problematic expression using notes.
5223 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5224 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5225 // If this var binds to another reference var, show the range of the next
5226 // var, otherwise the var binds to the problematic expression, in which case
5227 // show the range of the expression.
5228 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5229 : stackE->getSourceRange();
5230 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5231 << VD->getDeclName() << range;
5235 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5236 /// check if the expression in a return statement evaluates to an address
5237 /// to a location on the stack, a local block, an address of a label, or a
5238 /// reference to local temporary. The recursion is used to traverse the
5239 /// AST of the return expression, with recursion backtracking when we
5240 /// encounter a subexpression that (1) clearly does not lead to one of the
5241 /// above problematic expressions (2) is something we cannot determine leads to
5242 /// a problematic expression based on such local checking.
5244 /// Both EvalAddr and EvalVal follow through reference variables to evaluate
5245 /// the expression that they point to. Such variables are added to the
5246 /// 'refVars' vector so that we know what the reference variable "trail" was.
5248 /// EvalAddr processes expressions that are pointers that are used as
5249 /// references (and not L-values). EvalVal handles all other values.
5250 /// At the base case of the recursion is a check for the above problematic
5253 /// This implementation handles:
5255 /// * pointer-to-pointer casts
5256 /// * implicit conversions from array references to pointers
5257 /// * taking the address of fields
5258 /// * arbitrary interplay between "&" and "*" operators
5259 /// * pointer arithmetic from an address of a stack variable
5260 /// * taking the address of an array element where the array is on the stack
5261 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5263 if (E->isTypeDependent())
5266 // We should only be called for evaluating pointer expressions.
5267 assert((E->getType()->isAnyPointerType() ||
5268 E->getType()->isBlockPointerType() ||
5269 E->getType()->isObjCQualifiedIdType()) &&
5270 "EvalAddr only works on pointers");
5272 E = E->IgnoreParens();
5274 // Our "symbolic interpreter" is just a dispatch off the currently
5275 // viewed AST node. We then recursively traverse the AST by calling
5276 // EvalAddr and EvalVal appropriately.
5277 switch (E->getStmtClass()) {
5278 case Stmt::DeclRefExprClass: {
5279 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5281 // If we leave the immediate function, the lifetime isn't about to end.
5282 if (DR->refersToEnclosingVariableOrCapture())
5285 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5286 // If this is a reference variable, follow through to the expression that
5288 if (V->hasLocalStorage() &&
5289 V->getType()->isReferenceType() && V->hasInit()) {
5290 // Add the reference variable to the "trail".
5291 refVars.push_back(DR);
5292 return EvalAddr(V->getInit(), refVars, ParentDecl);
5298 case Stmt::UnaryOperatorClass: {
5299 // The only unary operator that make sense to handle here
5300 // is AddrOf. All others don't make sense as pointers.
5301 UnaryOperator *U = cast<UnaryOperator>(E);
5303 if (U->getOpcode() == UO_AddrOf)
5304 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
5309 case Stmt::BinaryOperatorClass: {
5310 // Handle pointer arithmetic. All other binary operators are not valid
5312 BinaryOperator *B = cast<BinaryOperator>(E);
5313 BinaryOperatorKind op = B->getOpcode();
5315 if (op != BO_Add && op != BO_Sub)
5318 Expr *Base = B->getLHS();
5320 // Determine which argument is the real pointer base. It could be
5321 // the RHS argument instead of the LHS.
5322 if (!Base->getType()->isPointerType()) Base = B->getRHS();
5324 assert (Base->getType()->isPointerType());
5325 return EvalAddr(Base, refVars, ParentDecl);
5328 // For conditional operators we need to see if either the LHS or RHS are
5329 // valid DeclRefExpr*s. If one of them is valid, we return it.
5330 case Stmt::ConditionalOperatorClass: {
5331 ConditionalOperator *C = cast<ConditionalOperator>(E);
5333 // Handle the GNU extension for missing LHS.
5334 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5335 if (Expr *LHSExpr = C->getLHS()) {
5336 // In C++, we can have a throw-expression, which has 'void' type.
5337 if (!LHSExpr->getType()->isVoidType())
5338 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
5342 // In C++, we can have a throw-expression, which has 'void' type.
5343 if (C->getRHS()->getType()->isVoidType())
5346 return EvalAddr(C->getRHS(), refVars, ParentDecl);
5349 case Stmt::BlockExprClass:
5350 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5351 return E; // local block.
5354 case Stmt::AddrLabelExprClass:
5355 return E; // address of label.
5357 case Stmt::ExprWithCleanupsClass:
5358 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5361 // For casts, we need to handle conversions from arrays to
5362 // pointer values, and pointer-to-pointer conversions.
5363 case Stmt::ImplicitCastExprClass:
5364 case Stmt::CStyleCastExprClass:
5365 case Stmt::CXXFunctionalCastExprClass:
5366 case Stmt::ObjCBridgedCastExprClass:
5367 case Stmt::CXXStaticCastExprClass:
5368 case Stmt::CXXDynamicCastExprClass:
5369 case Stmt::CXXConstCastExprClass:
5370 case Stmt::CXXReinterpretCastExprClass: {
5371 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5372 switch (cast<CastExpr>(E)->getCastKind()) {
5373 case CK_LValueToRValue:
5375 case CK_BaseToDerived:
5376 case CK_DerivedToBase:
5377 case CK_UncheckedDerivedToBase:
5379 case CK_CPointerToObjCPointerCast:
5380 case CK_BlockPointerToObjCPointerCast:
5381 case CK_AnyPointerToBlockPointerCast:
5382 return EvalAddr(SubExpr, refVars, ParentDecl);
5384 case CK_ArrayToPointerDecay:
5385 return EvalVal(SubExpr, refVars, ParentDecl);
5388 if (SubExpr->getType()->isAnyPointerType() ||
5389 SubExpr->getType()->isBlockPointerType() ||
5390 SubExpr->getType()->isObjCQualifiedIdType())
5391 return EvalAddr(SubExpr, refVars, ParentDecl);
5400 case Stmt::MaterializeTemporaryExprClass:
5401 if (Expr *Result = EvalAddr(
5402 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5403 refVars, ParentDecl))
5408 // Everything else: we simply don't reason about them.
5415 /// EvalVal - This function is complements EvalAddr in the mutual recursion.
5416 /// See the comments for EvalAddr for more details.
5417 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5420 // We should only be called for evaluating non-pointer expressions, or
5421 // expressions with a pointer type that are not used as references but instead
5422 // are l-values (e.g., DeclRefExpr with a pointer type).
5424 // Our "symbolic interpreter" is just a dispatch off the currently
5425 // viewed AST node. We then recursively traverse the AST by calling
5426 // EvalAddr and EvalVal appropriately.
5428 E = E->IgnoreParens();
5429 switch (E->getStmtClass()) {
5430 case Stmt::ImplicitCastExprClass: {
5431 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
5432 if (IE->getValueKind() == VK_LValue) {
5433 E = IE->getSubExpr();
5439 case Stmt::ExprWithCleanupsClass:
5440 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5442 case Stmt::DeclRefExprClass: {
5443 // When we hit a DeclRefExpr we are looking at code that refers to a
5444 // variable's name. If it's not a reference variable we check if it has
5445 // local storage within the function, and if so, return the expression.
5446 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5448 // If we leave the immediate function, the lifetime isn't about to end.
5449 if (DR->refersToEnclosingVariableOrCapture())
5452 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5453 // Check if it refers to itself, e.g. "int& i = i;".
5454 if (V == ParentDecl)
5457 if (V->hasLocalStorage()) {
5458 if (!V->getType()->isReferenceType())
5461 // Reference variable, follow through to the expression that
5464 // Add the reference variable to the "trail".
5465 refVars.push_back(DR);
5466 return EvalVal(V->getInit(), refVars, V);
5474 case Stmt::UnaryOperatorClass: {
5475 // The only unary operator that make sense to handle here
5476 // is Deref. All others don't resolve to a "name." This includes
5477 // handling all sorts of rvalues passed to a unary operator.
5478 UnaryOperator *U = cast<UnaryOperator>(E);
5480 if (U->getOpcode() == UO_Deref)
5481 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
5486 case Stmt::ArraySubscriptExprClass: {
5487 // Array subscripts are potential references to data on the stack. We
5488 // retrieve the DeclRefExpr* for the array variable if it indeed
5489 // has local storage.
5490 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5493 case Stmt::ConditionalOperatorClass: {
5494 // For conditional operators we need to see if either the LHS or RHS are
5495 // non-NULL Expr's. If one is non-NULL, we return it.
5496 ConditionalOperator *C = cast<ConditionalOperator>(E);
5498 // Handle the GNU extension for missing LHS.
5499 if (Expr *LHSExpr = C->getLHS()) {
5500 // In C++, we can have a throw-expression, which has 'void' type.
5501 if (!LHSExpr->getType()->isVoidType())
5502 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5506 // In C++, we can have a throw-expression, which has 'void' type.
5507 if (C->getRHS()->getType()->isVoidType())
5510 return EvalVal(C->getRHS(), refVars, ParentDecl);
5513 // Accesses to members are potential references to data on the stack.
5514 case Stmt::MemberExprClass: {
5515 MemberExpr *M = cast<MemberExpr>(E);
5517 // Check for indirect access. We only want direct field accesses.
5521 // Check whether the member type is itself a reference, in which case
5522 // we're not going to refer to the member, but to what the member refers to.
5523 if (M->getMemberDecl()->getType()->isReferenceType())
5526 return EvalVal(M->getBase(), refVars, ParentDecl);
5529 case Stmt::MaterializeTemporaryExprClass:
5530 if (Expr *Result = EvalVal(
5531 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5532 refVars, ParentDecl))
5538 // Check that we don't return or take the address of a reference to a
5539 // temporary. This is only useful in C++.
5540 if (!E->isTypeDependent() && E->isRValue())
5543 // Everything else: we simply don't reason about them.
5550 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5551 SourceLocation ReturnLoc,
5553 const AttrVec *Attrs,
5554 const FunctionDecl *FD) {
5555 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5557 // Check if the return value is null but should not be.
5558 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5559 CheckNonNullExpr(*this, RetValExp))
5560 Diag(ReturnLoc, diag::warn_null_ret)
5561 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5563 // C++11 [basic.stc.dynamic.allocation]p4:
5564 // If an allocation function declared with a non-throwing
5565 // exception-specification fails to allocate storage, it shall return
5566 // a null pointer. Any other allocation function that fails to allocate
5567 // storage shall indicate failure only by throwing an exception [...]
5569 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5570 if (Op == OO_New || Op == OO_Array_New) {
5571 const FunctionProtoType *Proto
5572 = FD->getType()->castAs<FunctionProtoType>();
5573 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5574 CheckNonNullExpr(*this, RetValExp))
5575 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5576 << FD << getLangOpts().CPlusPlus11;
5581 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5583 /// Check for comparisons of floating point operands using != and ==.
5584 /// Issue a warning if these are no self-comparisons, as they are not likely
5585 /// to do what the programmer intended.
5586 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
5587 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5588 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
5590 // Special case: check for x == x (which is OK).
5591 // Do not emit warnings for such cases.
5592 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5593 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5594 if (DRL->getDecl() == DRR->getDecl())
5598 // Special case: check for comparisons against literals that can be exactly
5599 // represented by APFloat. In such cases, do not emit a warning. This
5600 // is a heuristic: often comparison against such literals are used to
5601 // detect if a value in a variable has not changed. This clearly can
5602 // lead to false negatives.
5603 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5607 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5611 // Check for comparisons with builtin types.
5612 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
5613 if (CL->getBuiltinCallee())
5616 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
5617 if (CR->getBuiltinCallee())
5620 // Emit the diagnostic.
5621 Diag(Loc, diag::warn_floatingpoint_eq)
5622 << LHS->getSourceRange() << RHS->getSourceRange();
5625 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5626 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
5630 /// Structure recording the 'active' range of an integer-valued
5633 /// The number of bits active in the int.
5636 /// True if the int is known not to have negative values.
5639 IntRange(unsigned Width, bool NonNegative)
5640 : Width(Width), NonNegative(NonNegative)
5643 /// Returns the range of the bool type.
5644 static IntRange forBoolType() {
5645 return IntRange(1, true);
5648 /// Returns the range of an opaque value of the given integral type.
5649 static IntRange forValueOfType(ASTContext &C, QualType T) {
5650 return forValueOfCanonicalType(C,
5651 T->getCanonicalTypeInternal().getTypePtr());
5654 /// Returns the range of an opaque value of a canonical integral type.
5655 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
5656 assert(T->isCanonicalUnqualified());
5658 if (const VectorType *VT = dyn_cast<VectorType>(T))
5659 T = VT->getElementType().getTypePtr();
5660 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5661 T = CT->getElementType().getTypePtr();
5662 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5663 T = AT->getValueType().getTypePtr();
5665 // For enum types, use the known bit width of the enumerators.
5666 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
5667 EnumDecl *Enum = ET->getDecl();
5668 if (!Enum->isCompleteDefinition())
5669 return IntRange(C.getIntWidth(QualType(T, 0)), false);
5671 unsigned NumPositive = Enum->getNumPositiveBits();
5672 unsigned NumNegative = Enum->getNumNegativeBits();
5674 if (NumNegative == 0)
5675 return IntRange(NumPositive, true/*NonNegative*/);
5677 return IntRange(std::max(NumPositive + 1, NumNegative),
5678 false/*NonNegative*/);
5681 const BuiltinType *BT = cast<BuiltinType>(T);
5682 assert(BT->isInteger());
5684 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5687 /// Returns the "target" range of a canonical integral type, i.e.
5688 /// the range of values expressible in the type.
5690 /// This matches forValueOfCanonicalType except that enums have the
5691 /// full range of their type, not the range of their enumerators.
5692 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5693 assert(T->isCanonicalUnqualified());
5695 if (const VectorType *VT = dyn_cast<VectorType>(T))
5696 T = VT->getElementType().getTypePtr();
5697 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5698 T = CT->getElementType().getTypePtr();
5699 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5700 T = AT->getValueType().getTypePtr();
5701 if (const EnumType *ET = dyn_cast<EnumType>(T))
5702 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
5704 const BuiltinType *BT = cast<BuiltinType>(T);
5705 assert(BT->isInteger());
5707 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5710 /// Returns the supremum of two ranges: i.e. their conservative merge.
5711 static IntRange join(IntRange L, IntRange R) {
5712 return IntRange(std::max(L.Width, R.Width),
5713 L.NonNegative && R.NonNegative);
5716 /// Returns the infinum of two ranges: i.e. their aggressive merge.
5717 static IntRange meet(IntRange L, IntRange R) {
5718 return IntRange(std::min(L.Width, R.Width),
5719 L.NonNegative || R.NonNegative);
5723 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5724 unsigned MaxWidth) {
5725 if (value.isSigned() && value.isNegative())
5726 return IntRange(value.getMinSignedBits(), false);
5728 if (value.getBitWidth() > MaxWidth)
5729 value = value.trunc(MaxWidth);
5731 // isNonNegative() just checks the sign bit without considering
5733 return IntRange(value.getActiveBits(), true);
5736 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5737 unsigned MaxWidth) {
5739 return GetValueRange(C, result.getInt(), MaxWidth);
5741 if (result.isVector()) {
5742 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5743 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5744 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5745 R = IntRange::join(R, El);
5750 if (result.isComplexInt()) {
5751 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5752 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5753 return IntRange::join(R, I);
5756 // This can happen with lossless casts to intptr_t of "based" lvalues.
5757 // Assume it might use arbitrary bits.
5758 // FIXME: The only reason we need to pass the type in here is to get
5759 // the sign right on this one case. It would be nice if APValue
5761 assert(result.isLValue() || result.isAddrLabelDiff());
5762 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
5765 static QualType GetExprType(Expr *E) {
5766 QualType Ty = E->getType();
5767 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5768 Ty = AtomicRHS->getValueType();
5772 /// Pseudo-evaluate the given integer expression, estimating the
5773 /// range of values it might take.
5775 /// \param MaxWidth - the width to which the value will be truncated
5776 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
5777 E = E->IgnoreParens();
5779 // Try a full evaluation first.
5780 Expr::EvalResult result;
5781 if (E->EvaluateAsRValue(result, C))
5782 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
5784 // I think we only want to look through implicit casts here; if the
5785 // user has an explicit widening cast, we should treat the value as
5786 // being of the new, wider type.
5787 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
5788 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
5789 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5791 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
5793 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
5795 // Assume that non-integer casts can span the full range of the type.
5797 return OutputTypeRange;
5800 = GetExprRange(C, CE->getSubExpr(),
5801 std::min(MaxWidth, OutputTypeRange.Width));
5803 // Bail out if the subexpr's range is as wide as the cast type.
5804 if (SubRange.Width >= OutputTypeRange.Width)
5805 return OutputTypeRange;
5807 // Otherwise, we take the smaller width, and we're non-negative if
5808 // either the output type or the subexpr is.
5809 return IntRange(SubRange.Width,
5810 SubRange.NonNegative || OutputTypeRange.NonNegative);
5813 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5814 // If we can fold the condition, just take that operand.
5816 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5817 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5818 : CO->getFalseExpr(),
5821 // Otherwise, conservatively merge.
5822 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5823 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5824 return IntRange::join(L, R);
5827 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5828 switch (BO->getOpcode()) {
5830 // Boolean-valued operations are single-bit and positive.
5839 return IntRange::forBoolType();
5841 // The type of the assignments is the type of the LHS, so the RHS
5842 // is not necessarily the same type.
5851 return IntRange::forValueOfType(C, GetExprType(E));
5853 // Simple assignments just pass through the RHS, which will have
5854 // been coerced to the LHS type.
5857 return GetExprRange(C, BO->getRHS(), MaxWidth);
5859 // Operations with opaque sources are black-listed.
5862 return IntRange::forValueOfType(C, GetExprType(E));
5864 // Bitwise-and uses the *infinum* of the two source ranges.
5867 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5868 GetExprRange(C, BO->getRHS(), MaxWidth));
5870 // Left shift gets black-listed based on a judgement call.
5872 // ...except that we want to treat '1 << (blah)' as logically
5873 // positive. It's an important idiom.
5874 if (IntegerLiteral *I
5875 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5876 if (I->getValue() == 1) {
5877 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5878 return IntRange(R.Width, /*NonNegative*/ true);
5884 return IntRange::forValueOfType(C, GetExprType(E));
5886 // Right shift by a constant can narrow its left argument.
5888 case BO_ShrAssign: {
5889 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5891 // If the shift amount is a positive constant, drop the width by
5894 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5895 shift.isNonNegative()) {
5896 unsigned zext = shift.getZExtValue();
5897 if (zext >= L.Width)
5898 L.Width = (L.NonNegative ? 0 : 1);
5906 // Comma acts as its right operand.
5908 return GetExprRange(C, BO->getRHS(), MaxWidth);
5910 // Black-list pointer subtractions.
5912 if (BO->getLHS()->getType()->isPointerType())
5913 return IntRange::forValueOfType(C, GetExprType(E));
5916 // The width of a division result is mostly determined by the size
5919 // Don't 'pre-truncate' the operands.
5920 unsigned opWidth = C.getIntWidth(GetExprType(E));
5921 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5923 // If the divisor is constant, use that.
5924 llvm::APSInt divisor;
5925 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5926 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5927 if (log2 >= L.Width)
5928 L.Width = (L.NonNegative ? 0 : 1);
5930 L.Width = std::min(L.Width - log2, MaxWidth);
5934 // Otherwise, just use the LHS's width.
5935 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5936 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5939 // The result of a remainder can't be larger than the result of
5942 // Don't 'pre-truncate' the operands.
5943 unsigned opWidth = C.getIntWidth(GetExprType(E));
5944 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5945 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5947 IntRange meet = IntRange::meet(L, R);
5948 meet.Width = std::min(meet.Width, MaxWidth);
5952 // The default behavior is okay for these.
5960 // The default case is to treat the operation as if it were closed
5961 // on the narrowest type that encompasses both operands.
5962 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5963 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5964 return IntRange::join(L, R);
5967 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5968 switch (UO->getOpcode()) {
5969 // Boolean-valued operations are white-listed.
5971 return IntRange::forBoolType();
5973 // Operations with opaque sources are black-listed.
5975 case UO_AddrOf: // should be impossible
5976 return IntRange::forValueOfType(C, GetExprType(E));
5979 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5983 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5984 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5986 if (FieldDecl *BitField = E->getSourceBitField())
5987 return IntRange(BitField->getBitWidthValue(C),
5988 BitField->getType()->isUnsignedIntegerOrEnumerationType());
5990 return IntRange::forValueOfType(C, GetExprType(E));
5993 static IntRange GetExprRange(ASTContext &C, Expr *E) {
5994 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5997 /// Checks whether the given value, which currently has the given
5998 /// source semantics, has the same value when coerced through the
5999 /// target semantics.
6000 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6001 const llvm::fltSemantics &Src,
6002 const llvm::fltSemantics &Tgt) {
6003 llvm::APFloat truncated = value;
6006 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6007 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6009 return truncated.bitwiseIsEqual(value);
6012 /// Checks whether the given value, which currently has the given
6013 /// source semantics, has the same value when coerced through the
6014 /// target semantics.
6016 /// The value might be a vector of floats (or a complex number).
6017 static bool IsSameFloatAfterCast(const APValue &value,
6018 const llvm::fltSemantics &Src,
6019 const llvm::fltSemantics &Tgt) {
6020 if (value.isFloat())
6021 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6023 if (value.isVector()) {
6024 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6025 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6030 assert(value.isComplexFloat());
6031 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6032 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6035 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
6037 static bool IsZero(Sema &S, Expr *E) {
6038 // Suppress cases where we are comparing against an enum constant.
6039 if (const DeclRefExpr *DR =
6040 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6041 if (isa<EnumConstantDecl>(DR->getDecl()))
6044 // Suppress cases where the '0' value is expanded from a macro.
6045 if (E->getLocStart().isMacroID())
6049 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6052 static bool HasEnumType(Expr *E) {
6053 // Strip off implicit integral promotions.
6054 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6055 if (ICE->getCastKind() != CK_IntegralCast &&
6056 ICE->getCastKind() != CK_NoOp)
6058 E = ICE->getSubExpr();
6061 return E->getType()->isEnumeralType();
6064 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
6065 // Disable warning in template instantiations.
6066 if (!S.ActiveTemplateInstantiations.empty())
6069 BinaryOperatorKind op = E->getOpcode();
6070 if (E->isValueDependent())
6073 if (op == BO_LT && IsZero(S, E->getRHS())) {
6074 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6075 << "< 0" << "false" << HasEnumType(E->getLHS())
6076 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6077 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
6078 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6079 << ">= 0" << "true" << HasEnumType(E->getLHS())
6080 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6081 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
6082 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6083 << "0 >" << "false" << HasEnumType(E->getRHS())
6084 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6085 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
6086 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6087 << "0 <=" << "true" << HasEnumType(E->getRHS())
6088 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6092 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6093 Expr *Constant, Expr *Other,
6096 // Disable warning in template instantiations.
6097 if (!S.ActiveTemplateInstantiations.empty())
6100 // TODO: Investigate using GetExprRange() to get tighter bounds
6101 // on the bit ranges.
6102 QualType OtherT = Other->getType();
6103 if (const auto *AT = OtherT->getAs<AtomicType>())
6104 OtherT = AT->getValueType();
6105 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6106 unsigned OtherWidth = OtherRange.Width;
6108 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6110 // 0 values are handled later by CheckTrivialUnsignedComparison().
6111 if ((Value == 0) && (!OtherIsBooleanType))
6114 BinaryOperatorKind op = E->getOpcode();
6117 // Used for diagnostic printout.
6119 LiteralConstant = 0,
6122 } LiteralOrBoolConstant = LiteralConstant;
6124 if (!OtherIsBooleanType) {
6125 QualType ConstantT = Constant->getType();
6126 QualType CommonT = E->getLHS()->getType();
6128 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6130 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6131 "comparison with non-integer type");
6133 bool ConstantSigned = ConstantT->isSignedIntegerType();
6134 bool CommonSigned = CommonT->isSignedIntegerType();
6136 bool EqualityOnly = false;
6139 // The common type is signed, therefore no signed to unsigned conversion.
6140 if (!OtherRange.NonNegative) {
6141 // Check that the constant is representable in type OtherT.
6142 if (ConstantSigned) {
6143 if (OtherWidth >= Value.getMinSignedBits())
6145 } else { // !ConstantSigned
6146 if (OtherWidth >= Value.getActiveBits() + 1)
6149 } else { // !OtherSigned
6150 // Check that the constant is representable in type OtherT.
6151 // Negative values are out of range.
6152 if (ConstantSigned) {
6153 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6155 } else { // !ConstantSigned
6156 if (OtherWidth >= Value.getActiveBits())
6160 } else { // !CommonSigned
6161 if (OtherRange.NonNegative) {
6162 if (OtherWidth >= Value.getActiveBits())
6164 } else { // OtherSigned
6165 assert(!ConstantSigned &&
6166 "Two signed types converted to unsigned types.");
6167 // Check to see if the constant is representable in OtherT.
6168 if (OtherWidth > Value.getActiveBits())
6170 // Check to see if the constant is equivalent to a negative value
6172 if (S.Context.getIntWidth(ConstantT) ==
6173 S.Context.getIntWidth(CommonT) &&
6174 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6176 // The constant value rests between values that OtherT can represent
6177 // after conversion. Relational comparison still works, but equality
6178 // comparisons will be tautological.
6179 EqualityOnly = true;
6183 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6185 if (op == BO_EQ || op == BO_NE) {
6186 IsTrue = op == BO_NE;
6187 } else if (EqualityOnly) {
6189 } else if (RhsConstant) {
6190 if (op == BO_GT || op == BO_GE)
6191 IsTrue = !PositiveConstant;
6192 else // op == BO_LT || op == BO_LE
6193 IsTrue = PositiveConstant;
6195 if (op == BO_LT || op == BO_LE)
6196 IsTrue = !PositiveConstant;
6197 else // op == BO_GT || op == BO_GE
6198 IsTrue = PositiveConstant;
6201 // Other isKnownToHaveBooleanValue
6202 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6203 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6204 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6206 static const struct LinkedConditions {
6207 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6208 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6209 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6210 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6211 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6212 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6215 // Constant on LHS. | Constant on RHS. |
6216 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6217 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6218 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6219 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6220 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6221 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6222 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6225 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6227 enum ConstantValue ConstVal = Zero;
6228 if (Value.isUnsigned() || Value.isNonNegative()) {
6230 LiteralOrBoolConstant =
6231 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6233 } else if (Value == 1) {
6234 LiteralOrBoolConstant =
6235 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6238 LiteralOrBoolConstant = LiteralConstant;
6245 CompareBoolWithConstantResult CmpRes;
6249 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6252 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6255 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6258 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6261 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6264 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6271 if (CmpRes == AFals) {
6273 } else if (CmpRes == ATrue) {
6280 // If this is a comparison to an enum constant, include that
6281 // constant in the diagnostic.
6282 const EnumConstantDecl *ED = nullptr;
6283 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6284 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6286 SmallString<64> PrettySourceValue;
6287 llvm::raw_svector_ostream OS(PrettySourceValue);
6289 OS << '\'' << *ED << "' (" << Value << ")";
6293 S.DiagRuntimeBehavior(
6294 E->getOperatorLoc(), E,
6295 S.PDiag(diag::warn_out_of_range_compare)
6296 << OS.str() << LiteralOrBoolConstant
6297 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6298 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
6301 /// Analyze the operands of the given comparison. Implements the
6302 /// fallback case from AnalyzeComparison.
6303 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
6304 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6305 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6308 /// \brief Implements -Wsign-compare.
6310 /// \param E the binary operator to check for warnings
6311 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
6312 // The type the comparison is being performed in.
6313 QualType T = E->getLHS()->getType();
6315 // Only analyze comparison operators where both sides have been converted to
6317 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6318 return AnalyzeImpConvsInComparison(S, E);
6320 // Don't analyze value-dependent comparisons directly.
6321 if (E->isValueDependent())
6322 return AnalyzeImpConvsInComparison(S, E);
6324 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6325 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
6327 bool IsComparisonConstant = false;
6329 // Check whether an integer constant comparison results in a value
6330 // of 'true' or 'false'.
6331 if (T->isIntegralType(S.Context)) {
6332 llvm::APSInt RHSValue;
6333 bool IsRHSIntegralLiteral =
6334 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6335 llvm::APSInt LHSValue;
6336 bool IsLHSIntegralLiteral =
6337 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6338 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6339 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6340 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6341 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6343 IsComparisonConstant =
6344 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6345 } else if (!T->hasUnsignedIntegerRepresentation())
6346 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
6348 // We don't do anything special if this isn't an unsigned integral
6349 // comparison: we're only interested in integral comparisons, and
6350 // signed comparisons only happen in cases we don't care to warn about.
6352 // We also don't care about value-dependent expressions or expressions
6353 // whose result is a constant.
6354 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
6355 return AnalyzeImpConvsInComparison(S, E);
6357 // Check to see if one of the (unmodified) operands is of different
6359 Expr *signedOperand, *unsignedOperand;
6360 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6361 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
6362 "unsigned comparison between two signed integer expressions?");
6363 signedOperand = LHS;
6364 unsignedOperand = RHS;
6365 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6366 signedOperand = RHS;
6367 unsignedOperand = LHS;
6369 CheckTrivialUnsignedComparison(S, E);
6370 return AnalyzeImpConvsInComparison(S, E);
6373 // Otherwise, calculate the effective range of the signed operand.
6374 IntRange signedRange = GetExprRange(S.Context, signedOperand);
6376 // Go ahead and analyze implicit conversions in the operands. Note
6377 // that we skip the implicit conversions on both sides.
6378 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6379 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
6381 // If the signed range is non-negative, -Wsign-compare won't fire,
6382 // but we should still check for comparisons which are always true
6384 if (signedRange.NonNegative)
6385 return CheckTrivialUnsignedComparison(S, E);
6387 // For (in)equality comparisons, if the unsigned operand is a
6388 // constant which cannot collide with a overflowed signed operand,
6389 // then reinterpreting the signed operand as unsigned will not
6390 // change the result of the comparison.
6391 if (E->isEqualityOp()) {
6392 unsigned comparisonWidth = S.Context.getIntWidth(T);
6393 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
6395 // We should never be unable to prove that the unsigned operand is
6397 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6399 if (unsignedRange.Width < comparisonWidth)
6403 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6404 S.PDiag(diag::warn_mixed_sign_comparison)
6405 << LHS->getType() << RHS->getType()
6406 << LHS->getSourceRange() << RHS->getSourceRange());
6409 /// Analyzes an attempt to assign the given value to a bitfield.
6411 /// Returns true if there was something fishy about the attempt.
6412 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6413 SourceLocation InitLoc) {
6414 assert(Bitfield->isBitField());
6415 if (Bitfield->isInvalidDecl())
6418 // White-list bool bitfields.
6419 if (Bitfield->getType()->isBooleanType())
6422 // Ignore value- or type-dependent expressions.
6423 if (Bitfield->getBitWidth()->isValueDependent() ||
6424 Bitfield->getBitWidth()->isTypeDependent() ||
6425 Init->isValueDependent() ||
6426 Init->isTypeDependent())
6429 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6432 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
6435 unsigned OriginalWidth = Value.getBitWidth();
6436 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
6438 if (OriginalWidth <= FieldWidth)
6441 // Compute the value which the bitfield will contain.
6442 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6443 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
6445 // Check whether the stored value is equal to the original value.
6446 TruncatedValue = TruncatedValue.extend(OriginalWidth);
6447 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6450 // Special-case bitfields of width 1: booleans are naturally 0/1, and
6451 // therefore don't strictly fit into a signed bitfield of width 1.
6452 if (FieldWidth == 1 && Value == 1)
6455 std::string PrettyValue = Value.toString(10);
6456 std::string PrettyTrunc = TruncatedValue.toString(10);
6458 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6459 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6460 << Init->getSourceRange();
6465 /// Analyze the given simple or compound assignment for warning-worthy
6467 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
6468 // Just recurse on the LHS.
6469 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6471 // We want to recurse on the RHS as normal unless we're assigning to
6473 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
6474 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
6475 E->getOperatorLoc())) {
6476 // Recurse, ignoring any implicit conversions on the RHS.
6477 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6478 E->getOperatorLoc());
6482 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6485 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
6486 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
6487 SourceLocation CContext, unsigned diag,
6488 bool pruneControlFlow = false) {
6489 if (pruneControlFlow) {
6490 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6492 << SourceType << T << E->getSourceRange()
6493 << SourceRange(CContext));
6496 S.Diag(E->getExprLoc(), diag)
6497 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6500 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
6501 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
6502 SourceLocation CContext, unsigned diag,
6503 bool pruneControlFlow = false) {
6504 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
6507 /// Diagnose an implicit cast from a literal expression. Does not warn when the
6508 /// cast wouldn't lose information.
6509 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6510 SourceLocation CContext) {
6511 // Try to convert the literal exactly to an integer. If we can, don't warn.
6512 bool isExact = false;
6513 const llvm::APFloat &Value = FL->getValue();
6514 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6515 T->hasUnsignedIntegerRepresentation());
6516 if (Value.convertToInteger(IntegerValue,
6517 llvm::APFloat::rmTowardZero, &isExact)
6518 == llvm::APFloat::opOK && isExact)
6521 // FIXME: Force the precision of the source value down so we don't print
6522 // digits which are usually useless (we don't really care here if we
6523 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6524 // would automatically print the shortest representation, but it's a bit
6525 // tricky to implement.
6526 SmallString<16> PrettySourceValue;
6527 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6528 precision = (precision * 59 + 195) / 196;
6529 Value.toString(PrettySourceValue, precision);
6531 SmallString<16> PrettyTargetValue;
6532 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6533 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6535 IntegerValue.toString(PrettyTargetValue);
6537 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6538 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6539 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
6542 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6543 if (!Range.Width) return "0";
6545 llvm::APSInt ValueInRange = Value;
6546 ValueInRange.setIsSigned(!Range.NonNegative);
6547 ValueInRange = ValueInRange.trunc(Range.Width);
6548 return ValueInRange.toString(10);
6551 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6552 if (!isa<ImplicitCastExpr>(Ex))
6555 Expr *InnerE = Ex->IgnoreParenImpCasts();
6556 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6557 const Type *Source =
6558 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6559 if (Target->isDependentType())
6562 const BuiltinType *FloatCandidateBT =
6563 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6564 const Type *BoolCandidateType = ToBool ? Target : Source;
6566 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6567 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6570 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6571 SourceLocation CC) {
6572 unsigned NumArgs = TheCall->getNumArgs();
6573 for (unsigned i = 0; i < NumArgs; ++i) {
6574 Expr *CurrA = TheCall->getArg(i);
6575 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6578 bool IsSwapped = ((i > 0) &&
6579 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6580 IsSwapped |= ((i < (NumArgs - 1)) &&
6581 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6583 // Warn on this floating-point to bool conversion.
6584 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6585 CurrA->getType(), CC,
6586 diag::warn_impcast_floating_point_to_bool);
6591 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6592 SourceLocation CC) {
6593 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6597 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6598 const Expr::NullPointerConstantKind NullKind =
6599 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6600 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6603 // Return if target type is a safe conversion.
6604 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6605 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6608 SourceLocation Loc = E->getSourceRange().getBegin();
6610 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6611 if (NullKind == Expr::NPCK_GNUNull) {
6612 if (Loc.isMacroID())
6613 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6616 // Only warn if the null and context location are in the same macro expansion.
6617 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6620 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6621 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6622 << FixItHint::CreateReplacement(Loc,
6623 S.getFixItZeroLiteralForType(T, Loc));
6626 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
6627 SourceLocation CC, bool *ICContext = nullptr) {
6628 if (E->isTypeDependent() || E->isValueDependent()) return;
6630 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6631 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6632 if (Source == Target) return;
6633 if (Target->isDependentType()) return;
6635 // If the conversion context location is invalid don't complain. We also
6636 // don't want to emit a warning if the issue occurs from the expansion of
6637 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6638 // delay this check as long as possible. Once we detect we are in that
6639 // scenario, we just return.
6643 // Diagnose implicit casts to bool.
6644 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6645 if (isa<StringLiteral>(E))
6646 // Warn on string literal to bool. Checks for string literals in logical
6647 // and expressions, for instance, assert(0 && "error here"), are
6648 // prevented by a check in AnalyzeImplicitConversions().
6649 return DiagnoseImpCast(S, E, T, CC,
6650 diag::warn_impcast_string_literal_to_bool);
6651 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6652 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6653 // This covers the literal expressions that evaluate to Objective-C
6655 return DiagnoseImpCast(S, E, T, CC,
6656 diag::warn_impcast_objective_c_literal_to_bool);
6658 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6659 // Warn on pointer to bool conversion that is always true.
6660 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6665 // Strip vector types.
6666 if (isa<VectorType>(Source)) {
6667 if (!isa<VectorType>(Target)) {
6668 if (S.SourceMgr.isInSystemMacro(CC))
6670 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
6673 // If the vector cast is cast between two vectors of the same size, it is
6674 // a bitcast, not a conversion.
6675 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6678 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6679 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6681 if (auto VecTy = dyn_cast<VectorType>(Target))
6682 Target = VecTy->getElementType().getTypePtr();
6684 // Strip complex types.
6685 if (isa<ComplexType>(Source)) {
6686 if (!isa<ComplexType>(Target)) {
6687 if (S.SourceMgr.isInSystemMacro(CC))
6690 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
6693 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6694 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6697 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6698 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6700 // If the source is floating point...
6701 if (SourceBT && SourceBT->isFloatingPoint()) {
6702 // ...and the target is floating point...
6703 if (TargetBT && TargetBT->isFloatingPoint()) {
6704 // ...then warn if we're dropping FP rank.
6706 // Builtin FP kinds are ordered by increasing FP rank.
6707 if (SourceBT->getKind() > TargetBT->getKind()) {
6708 // Don't warn about float constants that are precisely
6709 // representable in the target type.
6710 Expr::EvalResult result;
6711 if (E->EvaluateAsRValue(result, S.Context)) {
6712 // Value might be a float, a float vector, or a float complex.
6713 if (IsSameFloatAfterCast(result.Val,
6714 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6715 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
6719 if (S.SourceMgr.isInSystemMacro(CC))
6722 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
6727 // If the target is integral, always warn.
6728 if (TargetBT && TargetBT->isInteger()) {
6729 if (S.SourceMgr.isInSystemMacro(CC))
6732 Expr *InnerE = E->IgnoreParenImpCasts();
6733 // We also want to warn on, e.g., "int i = -1.234"
6734 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6735 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6736 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6738 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6739 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
6741 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6745 // If the target is bool, warn if expr is a function or method call.
6746 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6748 // Check last argument of function call to see if it is an
6749 // implicit cast from a type matching the type the result
6750 // is being cast to.
6751 CallExpr *CEx = cast<CallExpr>(E);
6752 unsigned NumArgs = CEx->getNumArgs();
6754 Expr *LastA = CEx->getArg(NumArgs - 1);
6755 Expr *InnerE = LastA->IgnoreParenImpCasts();
6756 const Type *InnerType =
6757 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6758 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6759 // Warn on this floating-point to bool conversion
6760 DiagnoseImpCast(S, E, T, CC,
6761 diag::warn_impcast_floating_point_to_bool);
6768 DiagnoseNullConversion(S, E, T, CC);
6770 if (!Source->isIntegerType() || !Target->isIntegerType())
6773 // TODO: remove this early return once the false positives for constant->bool
6774 // in templates, macros, etc, are reduced or removed.
6775 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6778 IntRange SourceRange = GetExprRange(S.Context, E);
6779 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
6781 if (SourceRange.Width > TargetRange.Width) {
6782 // If the source is a constant, use a default-on diagnostic.
6783 // TODO: this should happen for bitfield stores, too.
6784 llvm::APSInt Value(32);
6785 if (E->isIntegerConstantExpr(Value, S.Context)) {
6786 if (S.SourceMgr.isInSystemMacro(CC))
6789 std::string PrettySourceValue = Value.toString(10);
6790 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
6792 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6793 S.PDiag(diag::warn_impcast_integer_precision_constant)
6794 << PrettySourceValue << PrettyTargetValue
6795 << E->getType() << T << E->getSourceRange()
6796 << clang::SourceRange(CC));
6800 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6801 if (S.SourceMgr.isInSystemMacro(CC))
6804 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
6805 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6806 /* pruneControlFlow */ true);
6807 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
6810 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6811 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6812 SourceRange.Width == TargetRange.Width)) {
6814 if (S.SourceMgr.isInSystemMacro(CC))
6817 unsigned DiagID = diag::warn_impcast_integer_sign;
6819 // Traditionally, gcc has warned about this under -Wsign-compare.
6820 // We also want to warn about it in -Wconversion.
6821 // So if -Wconversion is off, use a completely identical diagnostic
6822 // in the sign-compare group.
6823 // The conditional-checking code will
6825 DiagID = diag::warn_impcast_integer_sign_conditional;
6829 return DiagnoseImpCast(S, E, T, CC, DiagID);
6832 // Diagnose conversions between different enumeration types.
6833 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6834 // type, to give us better diagnostics.
6835 QualType SourceType = E->getType();
6836 if (!S.getLangOpts().CPlusPlus) {
6837 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6838 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6839 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6840 SourceType = S.Context.getTypeDeclType(Enum);
6841 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6845 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6846 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
6847 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6848 TargetEnum->getDecl()->hasNameForLinkage() &&
6849 SourceEnum != TargetEnum) {
6850 if (S.SourceMgr.isInSystemMacro(CC))
6853 return DiagnoseImpCast(S, E, SourceType, T, CC,
6854 diag::warn_impcast_different_enum_types);
6860 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6861 SourceLocation CC, QualType T);
6863 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
6864 SourceLocation CC, bool &ICContext) {
6865 E = E->IgnoreParenImpCasts();
6867 if (isa<ConditionalOperator>(E))
6868 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
6870 AnalyzeImplicitConversions(S, E, CC);
6871 if (E->getType() != T)
6872 return CheckImplicitConversion(S, E, T, CC, &ICContext);
6876 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6877 SourceLocation CC, QualType T) {
6878 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
6880 bool Suspicious = false;
6881 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6882 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
6884 // If -Wconversion would have warned about either of the candidates
6885 // for a signedness conversion to the context type...
6886 if (!Suspicious) return;
6888 // ...but it's currently ignored...
6889 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
6892 // ...then check whether it would have warned about either of the
6893 // candidates for a signedness conversion to the condition type.
6894 if (E->getType() == T) return;
6897 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6898 E->getType(), CC, &Suspicious);
6900 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
6901 E->getType(), CC, &Suspicious);
6904 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6905 /// Input argument E is a logical expression.
6906 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6907 if (S.getLangOpts().Bool)
6909 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6912 /// AnalyzeImplicitConversions - Find and report any interesting
6913 /// implicit conversions in the given expression. There are a couple
6914 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
6915 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
6916 QualType T = OrigE->getType();
6917 Expr *E = OrigE->IgnoreParenImpCasts();
6919 if (E->isTypeDependent() || E->isValueDependent())
6922 // For conditional operators, we analyze the arguments as if they
6923 // were being fed directly into the output.
6924 if (isa<ConditionalOperator>(E)) {
6925 ConditionalOperator *CO = cast<ConditionalOperator>(E);
6926 CheckConditionalOperator(S, CO, CC, T);
6930 // Check implicit argument conversions for function calls.
6931 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6932 CheckImplicitArgumentConversions(S, Call, CC);
6934 // Go ahead and check any implicit conversions we might have skipped.
6935 // The non-canonical typecheck is just an optimization;
6936 // CheckImplicitConversion will filter out dead implicit conversions.
6937 if (E->getType() != T)
6938 CheckImplicitConversion(S, E, T, CC);
6940 // Now continue drilling into this expression.
6942 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
6943 if (POE->getResultExpr())
6944 E = POE->getResultExpr();
6947 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6948 if (OVE->getSourceExpr())
6949 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6953 // Skip past explicit casts.
6954 if (isa<ExplicitCastExpr>(E)) {
6955 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
6956 return AnalyzeImplicitConversions(S, E, CC);
6959 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6960 // Do a somewhat different check with comparison operators.
6961 if (BO->isComparisonOp())
6962 return AnalyzeComparison(S, BO);
6964 // And with simple assignments.
6965 if (BO->getOpcode() == BO_Assign)
6966 return AnalyzeAssignment(S, BO);
6969 // These break the otherwise-useful invariant below. Fortunately,
6970 // we don't really need to recurse into them, because any internal
6971 // expressions should have been analyzed already when they were
6972 // built into statements.
6973 if (isa<StmtExpr>(E)) return;
6975 // Don't descend into unevaluated contexts.
6976 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6978 // Now just recurse over the expression's children.
6979 CC = E->getExprLoc();
6980 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6981 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6982 for (Stmt::child_range I = E->children(); I; ++I) {
6983 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6987 if (IsLogicalAndOperator &&
6988 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6989 // Ignore checking string literals that are in logical and operators.
6990 // This is a common pattern for asserts.
6992 AnalyzeImplicitConversions(S, ChildExpr, CC);
6995 if (BO && BO->isLogicalOp()) {
6996 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6997 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6998 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
7000 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7001 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7002 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
7005 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7006 if (U->getOpcode() == UO_LNot)
7007 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
7010 } // end anonymous namespace
7018 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7019 // Returns true when emitting a warning about taking the address of a reference.
7020 static bool CheckForReference(Sema &SemaRef, const Expr *E,
7021 PartialDiagnostic PD) {
7022 E = E->IgnoreParenImpCasts();
7024 const FunctionDecl *FD = nullptr;
7026 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7027 if (!DRE->getDecl()->getType()->isReferenceType())
7029 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7030 if (!M->getMemberDecl()->getType()->isReferenceType())
7032 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
7033 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
7035 FD = Call->getDirectCallee();
7040 SemaRef.Diag(E->getExprLoc(), PD);
7042 // If possible, point to location of function.
7044 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7050 // Returns true if the SourceLocation is expanded from any macro body.
7051 // Returns false if the SourceLocation is invalid, is from not in a macro
7052 // expansion, or is from expanded from a top-level macro argument.
7053 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7054 if (Loc.isInvalid())
7057 while (Loc.isMacroID()) {
7058 if (SM.isMacroBodyExpansion(Loc))
7060 Loc = SM.getImmediateMacroCallerLoc(Loc);
7066 /// \brief Diagnose pointers that are always non-null.
7067 /// \param E the expression containing the pointer
7068 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7069 /// compared to a null pointer
7070 /// \param IsEqual True when the comparison is equal to a null pointer
7071 /// \param Range Extra SourceRange to highlight in the diagnostic
7072 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7073 Expr::NullPointerConstantKind NullKind,
7074 bool IsEqual, SourceRange Range) {
7078 // Don't warn inside macros.
7079 if (E->getExprLoc().isMacroID()) {
7080 const SourceManager &SM = getSourceManager();
7081 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7082 IsInAnyMacroBody(SM, Range.getBegin()))
7085 E = E->IgnoreImpCasts();
7087 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7089 if (isa<CXXThisExpr>(E)) {
7090 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7091 : diag::warn_this_bool_conversion;
7092 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7096 bool IsAddressOf = false;
7098 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7099 if (UO->getOpcode() != UO_AddrOf)
7102 E = UO->getSubExpr();
7106 unsigned DiagID = IsCompare
7107 ? diag::warn_address_of_reference_null_compare
7108 : diag::warn_address_of_reference_bool_conversion;
7109 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7111 if (CheckForReference(*this, E, PD)) {
7116 // Expect to find a single Decl. Skip anything more complicated.
7117 ValueDecl *D = nullptr;
7118 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7120 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7121 D = M->getMemberDecl();
7124 // Weak Decls can be null.
7125 if (!D || D->isWeak())
7128 // Check for parameter decl with nonnull attribute
7129 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7130 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7131 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7132 unsigned NumArgs = FD->getNumParams();
7133 llvm::SmallBitVector AttrNonNull(NumArgs);
7134 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7135 if (!NonNull->args_size()) {
7136 AttrNonNull.set(0, NumArgs);
7139 for (unsigned Val : NonNull->args()) {
7142 AttrNonNull.set(Val);
7145 if (!AttrNonNull.empty())
7146 for (unsigned i = 0; i < NumArgs; ++i)
7147 if (FD->getParamDecl(i) == PV &&
7148 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
7150 llvm::raw_string_ostream S(Str);
7151 E->printPretty(S, nullptr, getPrintingPolicy());
7152 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7153 : diag::warn_cast_nonnull_to_bool;
7154 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7155 << Range << IsEqual;
7161 QualType T = D->getType();
7162 const bool IsArray = T->isArrayType();
7163 const bool IsFunction = T->isFunctionType();
7165 // Address of function is used to silence the function warning.
7166 if (IsAddressOf && IsFunction) {
7171 if (!IsAddressOf && !IsFunction && !IsArray)
7174 // Pretty print the expression for the diagnostic.
7176 llvm::raw_string_ostream S(Str);
7177 E->printPretty(S, nullptr, getPrintingPolicy());
7179 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7180 : diag::warn_impcast_pointer_to_bool;
7183 DiagType = AddressOf;
7184 else if (IsFunction)
7185 DiagType = FunctionPointer;
7187 DiagType = ArrayPointer;
7189 llvm_unreachable("Could not determine diagnostic.");
7190 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7191 << Range << IsEqual;
7196 // Suggest '&' to silence the function warning.
7197 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7198 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7200 // Check to see if '()' fixit should be emitted.
7201 QualType ReturnType;
7202 UnresolvedSet<4> NonTemplateOverloads;
7203 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7204 if (ReturnType.isNull())
7208 // There are two cases here. If there is null constant, the only suggest
7209 // for a pointer return type. If the null is 0, then suggest if the return
7210 // type is a pointer or an integer type.
7211 if (!ReturnType->isPointerType()) {
7212 if (NullKind == Expr::NPCK_ZeroExpression ||
7213 NullKind == Expr::NPCK_ZeroLiteral) {
7214 if (!ReturnType->isIntegerType())
7220 } else { // !IsCompare
7221 // For function to bool, only suggest if the function pointer has bool
7223 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7226 Diag(E->getExprLoc(), diag::note_function_to_function_call)
7227 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
7231 /// Diagnoses "dangerous" implicit conversions within the given
7232 /// expression (which is a full expression). Implements -Wconversion
7233 /// and -Wsign-compare.
7235 /// \param CC the "context" location of the implicit conversion, i.e.
7236 /// the most location of the syntactic entity requiring the implicit
7238 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
7239 // Don't diagnose in unevaluated contexts.
7240 if (isUnevaluatedContext())
7243 // Don't diagnose for value- or type-dependent expressions.
7244 if (E->isTypeDependent() || E->isValueDependent())
7247 // Check for array bounds violations in cases where the check isn't triggered
7248 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7249 // ArraySubscriptExpr is on the RHS of a variable initialization.
7250 CheckArrayAccess(E);
7252 // This is not the right CC for (e.g.) a variable initialization.
7253 AnalyzeImplicitConversions(*this, E, CC);
7256 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7257 /// Input argument E is a logical expression.
7258 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7259 ::CheckBoolLikeConversion(*this, E, CC);
7262 /// Diagnose when expression is an integer constant expression and its evaluation
7263 /// results in integer overflow
7264 void Sema::CheckForIntOverflow (Expr *E) {
7265 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7266 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
7270 /// \brief Visitor for expressions which looks for unsequenced operations on the
7272 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
7273 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7275 /// \brief A tree of sequenced regions within an expression. Two regions are
7276 /// unsequenced if one is an ancestor or a descendent of the other. When we
7277 /// finish processing an expression with sequencing, such as a comma
7278 /// expression, we fold its tree nodes into its parent, since they are
7279 /// unsequenced with respect to nodes we will visit later.
7280 class SequenceTree {
7282 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7283 unsigned Parent : 31;
7286 SmallVector<Value, 8> Values;
7289 /// \brief A region within an expression which may be sequenced with respect
7290 /// to some other region.
7292 explicit Seq(unsigned N) : Index(N) {}
7294 friend class SequenceTree;
7299 SequenceTree() { Values.push_back(Value(0)); }
7300 Seq root() const { return Seq(0); }
7302 /// \brief Create a new sequence of operations, which is an unsequenced
7303 /// subset of \p Parent. This sequence of operations is sequenced with
7304 /// respect to other children of \p Parent.
7305 Seq allocate(Seq Parent) {
7306 Values.push_back(Value(Parent.Index));
7307 return Seq(Values.size() - 1);
7310 /// \brief Merge a sequence of operations into its parent.
7312 Values[S.Index].Merged = true;
7315 /// \brief Determine whether two operations are unsequenced. This operation
7316 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7317 /// should have been merged into its parent as appropriate.
7318 bool isUnsequenced(Seq Cur, Seq Old) {
7319 unsigned C = representative(Cur.Index);
7320 unsigned Target = representative(Old.Index);
7321 while (C >= Target) {
7324 C = Values[C].Parent;
7330 /// \brief Pick a representative for a sequence.
7331 unsigned representative(unsigned K) {
7332 if (Values[K].Merged)
7333 // Perform path compression as we go.
7334 return Values[K].Parent = representative(Values[K].Parent);
7339 /// An object for which we can track unsequenced uses.
7340 typedef NamedDecl *Object;
7342 /// Different flavors of object usage which we track. We only track the
7343 /// least-sequenced usage of each kind.
7345 /// A read of an object. Multiple unsequenced reads are OK.
7347 /// A modification of an object which is sequenced before the value
7348 /// computation of the expression, such as ++n in C++.
7350 /// A modification of an object which is not sequenced before the value
7351 /// computation of the expression, such as n++.
7354 UK_Count = UK_ModAsSideEffect + 1
7358 Usage() : Use(nullptr), Seq() {}
7360 SequenceTree::Seq Seq;
7364 UsageInfo() : Diagnosed(false) {}
7365 Usage Uses[UK_Count];
7366 /// Have we issued a diagnostic for this variable already?
7369 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7372 /// Sequenced regions within the expression.
7374 /// Declaration modifications and references which we have seen.
7375 UsageInfoMap UsageMap;
7376 /// The region we are currently within.
7377 SequenceTree::Seq Region;
7378 /// Filled in with declarations which were modified as a side-effect
7379 /// (that is, post-increment operations).
7380 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7381 /// Expressions to check later. We defer checking these to reduce
7383 SmallVectorImpl<Expr *> &WorkList;
7385 /// RAII object wrapping the visitation of a sequenced subexpression of an
7386 /// expression. At the end of this process, the side-effects of the evaluation
7387 /// become sequenced with respect to the value computation of the result, so
7388 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7390 struct SequencedSubexpression {
7391 SequencedSubexpression(SequenceChecker &Self)
7392 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7393 Self.ModAsSideEffect = &ModAsSideEffect;
7395 ~SequencedSubexpression() {
7396 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7398 UsageInfo &U = Self.UsageMap[MI->first];
7399 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7400 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7401 SideEffectUsage = MI->second;
7403 Self.ModAsSideEffect = OldModAsSideEffect;
7406 SequenceChecker &Self;
7407 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7408 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
7411 /// RAII object wrapping the visitation of a subexpression which we might
7412 /// choose to evaluate as a constant. If any subexpression is evaluated and
7413 /// found to be non-constant, this allows us to suppress the evaluation of
7414 /// the outer expression.
7415 class EvaluationTracker {
7417 EvaluationTracker(SequenceChecker &Self)
7418 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7419 Self.EvalTracker = this;
7421 ~EvaluationTracker() {
7422 Self.EvalTracker = Prev;
7424 Prev->EvalOK &= EvalOK;
7427 bool evaluate(const Expr *E, bool &Result) {
7428 if (!EvalOK || E->isValueDependent())
7430 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7435 SequenceChecker &Self;
7436 EvaluationTracker *Prev;
7440 /// \brief Find the object which is produced by the specified expression,
7442 Object getObject(Expr *E, bool Mod) const {
7443 E = E->IgnoreParenCasts();
7444 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7445 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7446 return getObject(UO->getSubExpr(), Mod);
7447 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7448 if (BO->getOpcode() == BO_Comma)
7449 return getObject(BO->getRHS(), Mod);
7450 if (Mod && BO->isAssignmentOp())
7451 return getObject(BO->getLHS(), Mod);
7452 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7453 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7454 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7455 return ME->getMemberDecl();
7456 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7457 // FIXME: If this is a reference, map through to its value.
7458 return DRE->getDecl();
7462 /// \brief Note that an object was modified or used by an expression.
7463 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7464 Usage &U = UI.Uses[UK];
7465 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7466 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7467 ModAsSideEffect->push_back(std::make_pair(O, U));
7472 /// \brief Check whether a modification or use conflicts with a prior usage.
7473 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7478 const Usage &U = UI.Uses[OtherKind];
7479 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7483 Expr *ModOrUse = Ref;
7484 if (OtherKind == UK_Use)
7485 std::swap(Mod, ModOrUse);
7487 SemaRef.Diag(Mod->getExprLoc(),
7488 IsModMod ? diag::warn_unsequenced_mod_mod
7489 : diag::warn_unsequenced_mod_use)
7490 << O << SourceRange(ModOrUse->getExprLoc());
7491 UI.Diagnosed = true;
7494 void notePreUse(Object O, Expr *Use) {
7495 UsageInfo &U = UsageMap[O];
7496 // Uses conflict with other modifications.
7497 checkUsage(O, U, Use, UK_ModAsValue, false);
7499 void notePostUse(Object O, Expr *Use) {
7500 UsageInfo &U = UsageMap[O];
7501 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7502 addUsage(U, O, Use, UK_Use);
7505 void notePreMod(Object O, Expr *Mod) {
7506 UsageInfo &U = UsageMap[O];
7507 // Modifications conflict with other modifications and with uses.
7508 checkUsage(O, U, Mod, UK_ModAsValue, true);
7509 checkUsage(O, U, Mod, UK_Use, false);
7511 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7512 UsageInfo &U = UsageMap[O];
7513 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7514 addUsage(U, O, Use, UK);
7518 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
7519 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7520 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
7524 void VisitStmt(Stmt *S) {
7525 // Skip all statements which aren't expressions for now.
7528 void VisitExpr(Expr *E) {
7529 // By default, just recurse to evaluated subexpressions.
7533 void VisitCastExpr(CastExpr *E) {
7534 Object O = Object();
7535 if (E->getCastKind() == CK_LValueToRValue)
7536 O = getObject(E->getSubExpr(), false);
7545 void VisitBinComma(BinaryOperator *BO) {
7546 // C++11 [expr.comma]p1:
7547 // Every value computation and side effect associated with the left
7548 // expression is sequenced before every value computation and side
7549 // effect associated with the right expression.
7550 SequenceTree::Seq LHS = Tree.allocate(Region);
7551 SequenceTree::Seq RHS = Tree.allocate(Region);
7552 SequenceTree::Seq OldRegion = Region;
7555 SequencedSubexpression SeqLHS(*this);
7557 Visit(BO->getLHS());
7561 Visit(BO->getRHS());
7565 // Forget that LHS and RHS are sequenced. They are both unsequenced
7566 // with respect to other stuff.
7571 void VisitBinAssign(BinaryOperator *BO) {
7572 // The modification is sequenced after the value computation of the LHS
7573 // and RHS, so check it before inspecting the operands and update the
7575 Object O = getObject(BO->getLHS(), true);
7577 return VisitExpr(BO);
7581 // C++11 [expr.ass]p7:
7582 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7585 // Therefore, for a compound assignment operator, O is considered used
7586 // everywhere except within the evaluation of E1 itself.
7587 if (isa<CompoundAssignOperator>(BO))
7590 Visit(BO->getLHS());
7592 if (isa<CompoundAssignOperator>(BO))
7595 Visit(BO->getRHS());
7597 // C++11 [expr.ass]p1:
7598 // the assignment is sequenced [...] before the value computation of the
7599 // assignment expression.
7600 // C11 6.5.16/3 has no such rule.
7601 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7602 : UK_ModAsSideEffect);
7604 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7605 VisitBinAssign(CAO);
7608 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7609 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7610 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7611 Object O = getObject(UO->getSubExpr(), true);
7613 return VisitExpr(UO);
7616 Visit(UO->getSubExpr());
7617 // C++11 [expr.pre.incr]p1:
7618 // the expression ++x is equivalent to x+=1
7619 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7620 : UK_ModAsSideEffect);
7623 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7624 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7625 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7626 Object O = getObject(UO->getSubExpr(), true);
7628 return VisitExpr(UO);
7631 Visit(UO->getSubExpr());
7632 notePostMod(O, UO, UK_ModAsSideEffect);
7635 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7636 void VisitBinLOr(BinaryOperator *BO) {
7637 // The side-effects of the LHS of an '&&' are sequenced before the
7638 // value computation of the RHS, and hence before the value computation
7639 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7640 // as if they were unconditionally sequenced.
7641 EvaluationTracker Eval(*this);
7643 SequencedSubexpression Sequenced(*this);
7644 Visit(BO->getLHS());
7648 if (Eval.evaluate(BO->getLHS(), Result)) {
7650 Visit(BO->getRHS());
7652 // Check for unsequenced operations in the RHS, treating it as an
7653 // entirely separate evaluation.
7655 // FIXME: If there are operations in the RHS which are unsequenced
7656 // with respect to operations outside the RHS, and those operations
7657 // are unconditionally evaluated, diagnose them.
7658 WorkList.push_back(BO->getRHS());
7661 void VisitBinLAnd(BinaryOperator *BO) {
7662 EvaluationTracker Eval(*this);
7664 SequencedSubexpression Sequenced(*this);
7665 Visit(BO->getLHS());
7669 if (Eval.evaluate(BO->getLHS(), Result)) {
7671 Visit(BO->getRHS());
7673 WorkList.push_back(BO->getRHS());
7677 // Only visit the condition, unless we can be sure which subexpression will
7679 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
7680 EvaluationTracker Eval(*this);
7682 SequencedSubexpression Sequenced(*this);
7683 Visit(CO->getCond());
7687 if (Eval.evaluate(CO->getCond(), Result))
7688 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
7690 WorkList.push_back(CO->getTrueExpr());
7691 WorkList.push_back(CO->getFalseExpr());
7695 void VisitCallExpr(CallExpr *CE) {
7696 // C++11 [intro.execution]p15:
7697 // When calling a function [...], every value computation and side effect
7698 // associated with any argument expression, or with the postfix expression
7699 // designating the called function, is sequenced before execution of every
7700 // expression or statement in the body of the function [and thus before
7701 // the value computation of its result].
7702 SequencedSubexpression Sequenced(*this);
7703 Base::VisitCallExpr(CE);
7705 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7708 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
7709 // This is a call, so all subexpressions are sequenced before the result.
7710 SequencedSubexpression Sequenced(*this);
7712 if (!CCE->isListInitialization())
7713 return VisitExpr(CCE);
7715 // In C++11, list initializations are sequenced.
7716 SmallVector<SequenceTree::Seq, 32> Elts;
7717 SequenceTree::Seq Parent = Region;
7718 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7721 Region = Tree.allocate(Parent);
7722 Elts.push_back(Region);
7726 // Forget that the initializers are sequenced.
7728 for (unsigned I = 0; I < Elts.size(); ++I)
7729 Tree.merge(Elts[I]);
7732 void VisitInitListExpr(InitListExpr *ILE) {
7733 if (!SemaRef.getLangOpts().CPlusPlus11)
7734 return VisitExpr(ILE);
7736 // In C++11, list initializations are sequenced.
7737 SmallVector<SequenceTree::Seq, 32> Elts;
7738 SequenceTree::Seq Parent = Region;
7739 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7740 Expr *E = ILE->getInit(I);
7742 Region = Tree.allocate(Parent);
7743 Elts.push_back(Region);
7747 // Forget that the initializers are sequenced.
7749 for (unsigned I = 0; I < Elts.size(); ++I)
7750 Tree.merge(Elts[I]);
7755 void Sema::CheckUnsequencedOperations(Expr *E) {
7756 SmallVector<Expr *, 8> WorkList;
7757 WorkList.push_back(E);
7758 while (!WorkList.empty()) {
7759 Expr *Item = WorkList.pop_back_val();
7760 SequenceChecker(*this, Item, WorkList);
7764 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7766 CheckImplicitConversions(E, CheckLoc);
7767 CheckUnsequencedOperations(E);
7768 if (!IsConstexpr && !E->isValueDependent())
7769 CheckForIntOverflow(E);
7772 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7773 FieldDecl *BitField,
7775 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7778 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
7779 SourceLocation Loc) {
7780 if (!PType->isVariablyModifiedType())
7782 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
7783 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
7786 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
7787 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
7790 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
7791 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
7795 const ArrayType *AT = S.Context.getAsArrayType(PType);
7799 if (AT->getSizeModifier() != ArrayType::Star) {
7800 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
7804 S.Diag(Loc, diag::err_array_star_in_function_definition);
7807 /// CheckParmsForFunctionDef - Check that the parameters of the given
7808 /// function are appropriate for the definition of a function. This
7809 /// takes care of any checks that cannot be performed on the
7810 /// declaration itself, e.g., that the types of each of the function
7811 /// parameters are complete.
7812 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7813 ParmVarDecl *const *PEnd,
7814 bool CheckParameterNames) {
7815 bool HasInvalidParm = false;
7816 for (; P != PEnd; ++P) {
7817 ParmVarDecl *Param = *P;
7819 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7820 // function declarator that is part of a function definition of
7821 // that function shall not have incomplete type.
7823 // This is also C++ [dcl.fct]p6.
7824 if (!Param->isInvalidDecl() &&
7825 RequireCompleteType(Param->getLocation(), Param->getType(),
7826 diag::err_typecheck_decl_incomplete_type)) {
7827 Param->setInvalidDecl();
7828 HasInvalidParm = true;
7831 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7832 // declaration of each parameter shall include an identifier.
7833 if (CheckParameterNames &&
7834 Param->getIdentifier() == nullptr &&
7835 !Param->isImplicit() &&
7836 !getLangOpts().CPlusPlus)
7837 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
7840 // If the function declarator is not part of a definition of that
7841 // function, parameters may have incomplete type and may use the [*]
7842 // notation in their sequences of declarator specifiers to specify
7843 // variable length array types.
7844 QualType PType = Param->getOriginalType();
7845 // FIXME: This diagnostic should point the '[*]' if source-location
7846 // information is added for it.
7847 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
7849 // MSVC destroys objects passed by value in the callee. Therefore a
7850 // function definition which takes such a parameter must be able to call the
7851 // object's destructor. However, we don't perform any direct access check
7853 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7855 .areArgsDestroyedLeftToRightInCallee()) {
7856 if (!Param->isInvalidDecl()) {
7857 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7858 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7859 if (!ClassDecl->isInvalidDecl() &&
7860 !ClassDecl->hasIrrelevantDestructor() &&
7861 !ClassDecl->isDependentContext()) {
7862 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7863 MarkFunctionReferenced(Param->getLocation(), Destructor);
7864 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7871 return HasInvalidParm;
7874 /// CheckCastAlign - Implements -Wcast-align, which warns when a
7875 /// pointer cast increases the alignment requirements.
7876 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7877 // This is actually a lot of work to potentially be doing on every
7878 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
7879 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
7882 // Ignore dependent types.
7883 if (T->isDependentType() || Op->getType()->isDependentType())
7886 // Require that the destination be a pointer type.
7887 const PointerType *DestPtr = T->getAs<PointerType>();
7888 if (!DestPtr) return;
7890 // If the destination has alignment 1, we're done.
7891 QualType DestPointee = DestPtr->getPointeeType();
7892 if (DestPointee->isIncompleteType()) return;
7893 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7894 if (DestAlign.isOne()) return;
7896 // Require that the source be a pointer type.
7897 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7898 if (!SrcPtr) return;
7899 QualType SrcPointee = SrcPtr->getPointeeType();
7901 // Whitelist casts from cv void*. We already implicitly
7902 // whitelisted casts to cv void*, since they have alignment 1.
7903 // Also whitelist casts involving incomplete types, which implicitly
7905 if (SrcPointee->isIncompleteType()) return;
7907 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7908 if (SrcAlign >= DestAlign) return;
7910 Diag(TRange.getBegin(), diag::warn_cast_align)
7911 << Op->getType() << T
7912 << static_cast<unsigned>(SrcAlign.getQuantity())
7913 << static_cast<unsigned>(DestAlign.getQuantity())
7914 << TRange << Op->getSourceRange();
7917 static const Type* getElementType(const Expr *BaseExpr) {
7918 const Type* EltType = BaseExpr->getType().getTypePtr();
7919 if (EltType->isAnyPointerType())
7920 return EltType->getPointeeType().getTypePtr();
7921 else if (EltType->isArrayType())
7922 return EltType->getBaseElementTypeUnsafe();
7926 /// \brief Check whether this array fits the idiom of a size-one tail padded
7927 /// array member of a struct.
7929 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
7930 /// commonly used to emulate flexible arrays in C89 code.
7931 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7932 const NamedDecl *ND) {
7933 if (Size != 1 || !ND) return false;
7935 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7936 if (!FD) return false;
7938 // Don't consider sizes resulting from macro expansions or template argument
7939 // substitution to form C89 tail-padded arrays.
7941 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
7943 TypeLoc TL = TInfo->getTypeLoc();
7944 // Look through typedefs.
7945 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7946 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
7947 TInfo = TDL->getTypeSourceInfo();
7950 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7951 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
7952 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7958 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
7959 if (!RD) return false;
7960 if (RD->isUnion()) return false;
7961 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7962 if (!CRD->isStandardLayout()) return false;
7965 // See if this is the last field decl in the record.
7967 while ((D = D->getNextDeclInContext()))
7968 if (isa<FieldDecl>(D))
7973 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7974 const ArraySubscriptExpr *ASE,
7975 bool AllowOnePastEnd, bool IndexNegated) {
7976 IndexExpr = IndexExpr->IgnoreParenImpCasts();
7977 if (IndexExpr->isValueDependent())
7980 const Type *EffectiveType = getElementType(BaseExpr);
7981 BaseExpr = BaseExpr->IgnoreParenCasts();
7982 const ConstantArrayType *ArrayTy =
7983 Context.getAsConstantArrayType(BaseExpr->getType());
7988 if (!IndexExpr->EvaluateAsInt(index, Context))
7993 const NamedDecl *ND = nullptr;
7994 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7995 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7996 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7997 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7999 if (index.isUnsigned() || !index.isNegative()) {
8000 llvm::APInt size = ArrayTy->getSize();
8001 if (!size.isStrictlyPositive())
8004 const Type* BaseType = getElementType(BaseExpr);
8005 if (BaseType != EffectiveType) {
8006 // Make sure we're comparing apples to apples when comparing index to size
8007 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8008 uint64_t array_typesize = Context.getTypeSize(BaseType);
8009 // Handle ptrarith_typesize being zero, such as when casting to void*
8010 if (!ptrarith_typesize) ptrarith_typesize = 1;
8011 if (ptrarith_typesize != array_typesize) {
8012 // There's a cast to a different size type involved
8013 uint64_t ratio = array_typesize / ptrarith_typesize;
8014 // TODO: Be smarter about handling cases where array_typesize is not a
8015 // multiple of ptrarith_typesize
8016 if (ptrarith_typesize * ratio == array_typesize)
8017 size *= llvm::APInt(size.getBitWidth(), ratio);
8021 if (size.getBitWidth() > index.getBitWidth())
8022 index = index.zext(size.getBitWidth());
8023 else if (size.getBitWidth() < index.getBitWidth())
8024 size = size.zext(index.getBitWidth());
8026 // For array subscripting the index must be less than size, but for pointer
8027 // arithmetic also allow the index (offset) to be equal to size since
8028 // computing the next address after the end of the array is legal and
8029 // commonly done e.g. in C++ iterators and range-based for loops.
8030 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
8033 // Also don't warn for arrays of size 1 which are members of some
8034 // structure. These are often used to approximate flexible arrays in C89
8036 if (IsTailPaddedMemberArray(*this, size, ND))
8039 // Suppress the warning if the subscript expression (as identified by the
8040 // ']' location) and the index expression are both from macro expansions
8041 // within a system header.
8043 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8044 ASE->getRBracketLoc());
8045 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8046 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8047 IndexExpr->getLocStart());
8048 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
8053 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
8055 DiagID = diag::warn_array_index_exceeds_bounds;
8057 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8058 PDiag(DiagID) << index.toString(10, true)
8059 << size.toString(10, true)
8060 << (unsigned)size.getLimitedValue(~0U)
8061 << IndexExpr->getSourceRange());
8063 unsigned DiagID = diag::warn_array_index_precedes_bounds;
8065 DiagID = diag::warn_ptr_arith_precedes_bounds;
8066 if (index.isNegative()) index = -index;
8069 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8070 PDiag(DiagID) << index.toString(10, true)
8071 << IndexExpr->getSourceRange());
8075 // Try harder to find a NamedDecl to point at in the note.
8076 while (const ArraySubscriptExpr *ASE =
8077 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8078 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8079 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8080 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8081 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8082 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8086 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8087 PDiag(diag::note_array_index_out_of_bounds)
8088 << ND->getDeclName());
8091 void Sema::CheckArrayAccess(const Expr *expr) {
8092 int AllowOnePastEnd = 0;
8094 expr = expr->IgnoreParenImpCasts();
8095 switch (expr->getStmtClass()) {
8096 case Stmt::ArraySubscriptExprClass: {
8097 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
8098 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
8099 AllowOnePastEnd > 0);
8102 case Stmt::UnaryOperatorClass: {
8103 // Only unwrap the * and & unary operators
8104 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8105 expr = UO->getSubExpr();
8106 switch (UO->getOpcode()) {
8118 case Stmt::ConditionalOperatorClass: {
8119 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8120 if (const Expr *lhs = cond->getLHS())
8121 CheckArrayAccess(lhs);
8122 if (const Expr *rhs = cond->getRHS())
8123 CheckArrayAccess(rhs);
8132 //===--- CHECK: Objective-C retain cycles ----------------------------------//
8135 struct RetainCycleOwner {
8136 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
8142 void setLocsFrom(Expr *e) {
8143 Loc = e->getExprLoc();
8144 Range = e->getSourceRange();
8149 /// Consider whether capturing the given variable can possibly lead to
8151 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
8152 // In ARC, it's captured strongly iff the variable has __strong
8153 // lifetime. In MRR, it's captured strongly if the variable is
8154 // __block and has an appropriate type.
8155 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8158 owner.Variable = var;
8160 owner.setLocsFrom(ref);
8164 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
8166 e = e->IgnoreParens();
8167 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8168 switch (cast->getCastKind()) {
8170 case CK_LValueBitCast:
8171 case CK_LValueToRValue:
8172 case CK_ARCReclaimReturnedObject:
8173 e = cast->getSubExpr();
8181 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8182 ObjCIvarDecl *ivar = ref->getDecl();
8183 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8186 // Try to find a retain cycle in the base.
8187 if (!findRetainCycleOwner(S, ref->getBase(), owner))
8190 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8191 owner.Indirect = true;
8195 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8196 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8197 if (!var) return false;
8198 return considerVariable(var, ref, owner);
8201 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8202 if (member->isArrow()) return false;
8204 // Don't count this as an indirect ownership.
8205 e = member->getBase();
8209 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8210 // Only pay attention to pseudo-objects on property references.
8211 ObjCPropertyRefExpr *pre
8212 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8214 if (!pre) return false;
8215 if (pre->isImplicitProperty()) return false;
8216 ObjCPropertyDecl *property = pre->getExplicitProperty();
8217 if (!property->isRetaining() &&
8218 !(property->getPropertyIvarDecl() &&
8219 property->getPropertyIvarDecl()->getType()
8220 .getObjCLifetime() == Qualifiers::OCL_Strong))
8223 owner.Indirect = true;
8224 if (pre->isSuperReceiver()) {
8225 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8226 if (!owner.Variable)
8228 owner.Loc = pre->getLocation();
8229 owner.Range = pre->getSourceRange();
8232 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8244 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8245 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8246 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
8247 Context(Context), Variable(variable), Capturer(nullptr),
8248 VarWillBeReased(false) {}
8249 ASTContext &Context;
8252 bool VarWillBeReased;
8254 void VisitDeclRefExpr(DeclRefExpr *ref) {
8255 if (ref->getDecl() == Variable && !Capturer)
8259 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8260 if (Capturer) return;
8261 Visit(ref->getBase());
8262 if (Capturer && ref->isFreeIvar())
8266 void VisitBlockExpr(BlockExpr *block) {
8267 // Look inside nested blocks
8268 if (block->getBlockDecl()->capturesVariable(Variable))
8269 Visit(block->getBlockDecl()->getBody());
8272 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8273 if (Capturer) return;
8274 if (OVE->getSourceExpr())
8275 Visit(OVE->getSourceExpr());
8277 void VisitBinaryOperator(BinaryOperator *BinOp) {
8278 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8280 Expr *LHS = BinOp->getLHS();
8281 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8282 if (DRE->getDecl() != Variable)
8284 if (Expr *RHS = BinOp->getRHS()) {
8285 RHS = RHS->IgnoreParenCasts();
8288 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8295 /// Check whether the given argument is a block which captures a
8297 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8298 assert(owner.Variable && owner.Loc.isValid());
8300 e = e->IgnoreParenCasts();
8302 // Look through [^{...} copy] and Block_copy(^{...}).
8303 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8304 Selector Cmd = ME->getSelector();
8305 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8306 e = ME->getInstanceReceiver();
8309 e = e->IgnoreParenCasts();
8311 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8312 if (CE->getNumArgs() == 1) {
8313 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
8315 const IdentifierInfo *FnI = Fn->getIdentifier();
8316 if (FnI && FnI->isStr("_Block_copy")) {
8317 e = CE->getArg(0)->IgnoreParenCasts();
8323 BlockExpr *block = dyn_cast<BlockExpr>(e);
8324 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
8327 FindCaptureVisitor visitor(S.Context, owner.Variable);
8328 visitor.Visit(block->getBlockDecl()->getBody());
8329 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
8332 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8333 RetainCycleOwner &owner) {
8335 assert(owner.Variable && owner.Loc.isValid());
8337 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8338 << owner.Variable << capturer->getSourceRange();
8339 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8340 << owner.Indirect << owner.Range;
8343 /// Check for a keyword selector that starts with the word 'add' or
8345 static bool isSetterLikeSelector(Selector sel) {
8346 if (sel.isUnarySelector()) return false;
8348 StringRef str = sel.getNameForSlot(0);
8349 while (!str.empty() && str.front() == '_') str = str.substr(1);
8350 if (str.startswith("set"))
8351 str = str.substr(3);
8352 else if (str.startswith("add")) {
8353 // Specially whitelist 'addOperationWithBlock:'.
8354 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8356 str = str.substr(3);
8361 if (str.empty()) return true;
8362 return !isLowercase(str.front());
8365 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8366 ObjCMessageExpr *Message) {
8367 if (S.NSMutableArrayPointer.isNull()) {
8368 IdentifierInfo *NSMutableArrayId =
8369 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8370 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8371 Message->getLocStart(),
8372 Sema::LookupOrdinaryName);
8373 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8374 if (!InterfaceDecl) {
8377 QualType NSMutableArrayObject =
8378 S.Context.getObjCInterfaceType(InterfaceDecl);
8379 S.NSMutableArrayPointer =
8380 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8383 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8387 Selector Sel = Message->getSelector();
8389 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8390 S.NSAPIObj->getNSArrayMethodKind(Sel);
8395 NSAPI::NSArrayMethodKind MK = *MKOpt;
8398 case NSAPI::NSMutableArr_addObject:
8399 case NSAPI::NSMutableArr_insertObjectAtIndex:
8400 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8402 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8413 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8414 ObjCMessageExpr *Message) {
8416 if (S.NSMutableDictionaryPointer.isNull()) {
8417 IdentifierInfo *NSMutableDictionaryId =
8418 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8419 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8420 Message->getLocStart(),
8421 Sema::LookupOrdinaryName);
8422 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8423 if (!InterfaceDecl) {
8426 QualType NSMutableDictionaryObject =
8427 S.Context.getObjCInterfaceType(InterfaceDecl);
8428 S.NSMutableDictionaryPointer =
8429 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8432 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8436 Selector Sel = Message->getSelector();
8438 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8439 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8444 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8447 case NSAPI::NSMutableDict_setObjectForKey:
8448 case NSAPI::NSMutableDict_setValueForKey:
8449 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8459 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8461 ObjCInterfaceDecl *InterfaceDecl;
8462 if (S.NSMutableSetPointer.isNull()) {
8463 IdentifierInfo *NSMutableSetId =
8464 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8465 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8466 Message->getLocStart(),
8467 Sema::LookupOrdinaryName);
8468 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8469 if (InterfaceDecl) {
8470 QualType NSMutableSetObject =
8471 S.Context.getObjCInterfaceType(InterfaceDecl);
8472 S.NSMutableSetPointer =
8473 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8477 if (S.NSCountedSetPointer.isNull()) {
8478 IdentifierInfo *NSCountedSetId =
8479 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8480 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8481 Message->getLocStart(),
8482 Sema::LookupOrdinaryName);
8483 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8484 if (InterfaceDecl) {
8485 QualType NSCountedSetObject =
8486 S.Context.getObjCInterfaceType(InterfaceDecl);
8487 S.NSCountedSetPointer =
8488 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8492 if (S.NSMutableOrderedSetPointer.isNull()) {
8493 IdentifierInfo *NSOrderedSetId =
8494 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8495 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8496 Message->getLocStart(),
8497 Sema::LookupOrdinaryName);
8498 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8499 if (InterfaceDecl) {
8500 QualType NSOrderedSetObject =
8501 S.Context.getObjCInterfaceType(InterfaceDecl);
8502 S.NSMutableOrderedSetPointer =
8503 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8507 QualType ReceiverType = Message->getReceiverType();
8509 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8510 ReceiverType == S.NSMutableSetPointer;
8511 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8512 ReceiverType == S.NSMutableOrderedSetPointer;
8513 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8514 ReceiverType == S.NSCountedSetPointer;
8516 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8520 Selector Sel = Message->getSelector();
8522 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8527 NSAPI::NSSetMethodKind MK = *MKOpt;
8530 case NSAPI::NSMutableSet_addObject:
8531 case NSAPI::NSOrderedSet_setObjectAtIndex:
8532 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8533 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8535 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8542 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8543 if (!Message->isInstanceMessage()) {
8547 Optional<int> ArgOpt;
8549 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8550 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8551 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8555 int ArgIndex = *ArgOpt;
8557 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8558 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8559 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8562 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8563 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8564 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8567 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8568 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8569 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8570 ValueDecl *Decl = ReceiverRE->getDecl();
8571 Diag(Message->getSourceRange().getBegin(),
8572 diag::warn_objc_circular_container)
8574 Diag(Decl->getLocation(),
8575 diag::note_objc_circular_container_declared_here)
8579 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8580 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8581 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8582 ObjCIvarDecl *Decl = IvarRE->getDecl();
8583 Diag(Message->getSourceRange().getBegin(),
8584 diag::warn_objc_circular_container)
8586 Diag(Decl->getLocation(),
8587 diag::note_objc_circular_container_declared_here)
8595 /// Check a message send to see if it's likely to cause a retain cycle.
8596 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8597 // Only check instance methods whose selector looks like a setter.
8598 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8601 // Try to find a variable that the receiver is strongly owned by.
8602 RetainCycleOwner owner;
8603 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
8604 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
8607 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8608 owner.Variable = getCurMethodDecl()->getSelfDecl();
8609 owner.Loc = msg->getSuperLoc();
8610 owner.Range = msg->getSuperLoc();
8613 // Check whether the receiver is captured by any of the arguments.
8614 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8615 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8616 return diagnoseRetainCycle(*this, capturer, owner);
8619 /// Check a property assign to see if it's likely to cause a retain cycle.
8620 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8621 RetainCycleOwner owner;
8622 if (!findRetainCycleOwner(*this, receiver, owner))
8625 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8626 diagnoseRetainCycle(*this, capturer, owner);
8629 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8630 RetainCycleOwner Owner;
8631 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
8634 // Because we don't have an expression for the variable, we have to set the
8635 // location explicitly here.
8636 Owner.Loc = Var->getLocation();
8637 Owner.Range = Var->getSourceRange();
8639 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8640 diagnoseRetainCycle(*this, Capturer, Owner);
8643 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8644 Expr *RHS, bool isProperty) {
8645 // Check if RHS is an Objective-C object literal, which also can get
8646 // immediately zapped in a weak reference. Note that we explicitly
8647 // allow ObjCStringLiterals, since those are designed to never really die.
8648 RHS = RHS->IgnoreParenImpCasts();
8650 // This enum needs to match with the 'select' in
8651 // warn_objc_arc_literal_assign (off-by-1).
8652 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8653 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8656 S.Diag(Loc, diag::warn_arc_literal_assign)
8658 << (isProperty ? 0 : 1)
8659 << RHS->getSourceRange();
8664 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8665 Qualifiers::ObjCLifetime LT,
8666 Expr *RHS, bool isProperty) {
8667 // Strip off any implicit cast added to get to the one ARC-specific.
8668 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8669 if (cast->getCastKind() == CK_ARCConsumeObject) {
8670 S.Diag(Loc, diag::warn_arc_retained_assign)
8671 << (LT == Qualifiers::OCL_ExplicitNone)
8672 << (isProperty ? 0 : 1)
8673 << RHS->getSourceRange();
8676 RHS = cast->getSubExpr();
8679 if (LT == Qualifiers::OCL_Weak &&
8680 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8686 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8687 QualType LHS, Expr *RHS) {
8688 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8690 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8693 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8699 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8700 Expr *LHS, Expr *RHS) {
8702 // PropertyRef on LHS type need be directly obtained from
8703 // its declaration as it has a PseudoType.
8704 ObjCPropertyRefExpr *PRE
8705 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8706 if (PRE && !PRE->isImplicitProperty()) {
8707 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8709 LHSType = PD->getType();
8712 if (LHSType.isNull())
8713 LHSType = LHS->getType();
8715 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8717 if (LT == Qualifiers::OCL_Weak) {
8718 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
8719 getCurFunction()->markSafeWeakUse(LHS);
8722 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8725 // FIXME. Check for other life times.
8726 if (LT != Qualifiers::OCL_None)
8730 if (PRE->isImplicitProperty())
8732 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8736 unsigned Attributes = PD->getPropertyAttributes();
8737 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
8738 // when 'assign' attribute was not explicitly specified
8739 // by user, ignore it and rely on property type itself
8740 // for lifetime info.
8741 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8742 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8743 LHSType->isObjCRetainableType())
8746 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8747 if (cast->getCastKind() == CK_ARCConsumeObject) {
8748 Diag(Loc, diag::warn_arc_retained_property_assign)
8749 << RHS->getSourceRange();
8752 RHS = cast->getSubExpr();
8755 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
8756 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8762 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8765 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8766 SourceLocation StmtLoc,
8767 const NullStmt *Body) {
8768 // Do not warn if the body is a macro that expands to nothing, e.g:
8774 if (Body->hasLeadingEmptyMacro())
8777 // Get line numbers of statement and body.
8778 bool StmtLineInvalid;
8779 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
8781 if (StmtLineInvalid)
8784 bool BodyLineInvalid;
8785 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8787 if (BodyLineInvalid)
8790 // Warn if null statement and body are on the same line.
8791 if (StmtLine != BodyLine)
8796 } // Unnamed namespace
8798 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8801 // Since this is a syntactic check, don't emit diagnostic for template
8802 // instantiations, this just adds noise.
8803 if (CurrentInstantiationScope)
8806 // The body should be a null statement.
8807 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8811 // Do the usual checks.
8812 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8815 Diag(NBody->getSemiLoc(), DiagID);
8816 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8819 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8820 const Stmt *PossibleBody) {
8821 assert(!CurrentInstantiationScope); // Ensured by caller
8823 SourceLocation StmtLoc;
8826 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8827 StmtLoc = FS->getRParenLoc();
8828 Body = FS->getBody();
8829 DiagID = diag::warn_empty_for_body;
8830 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8831 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8832 Body = WS->getBody();
8833 DiagID = diag::warn_empty_while_body;
8835 return; // Neither `for' nor `while'.
8837 // The body should be a null statement.
8838 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8842 // Skip expensive checks if diagnostic is disabled.
8843 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
8846 // Do the usual checks.
8847 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8850 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8851 // noise level low, emit diagnostics only if for/while is followed by a
8852 // CompoundStmt, e.g.:
8853 // for (int i = 0; i < n; i++);
8857 // or if for/while is followed by a statement with more indentation
8858 // than for/while itself:
8859 // for (int i = 0; i < n; i++);
8861 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8862 if (!ProbableTypo) {
8863 bool BodyColInvalid;
8864 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8865 PossibleBody->getLocStart(),
8870 bool StmtColInvalid;
8871 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8877 if (BodyCol > StmtCol)
8878 ProbableTypo = true;
8882 Diag(NBody->getSemiLoc(), DiagID);
8883 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8887 //===--- CHECK: Warn on self move with std::move. -------------------------===//
8889 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8890 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8891 SourceLocation OpLoc) {
8893 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8896 if (!ActiveTemplateInstantiations.empty())
8899 // Strip parens and casts away.
8900 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8901 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8903 // Check for a call expression
8904 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8905 if (!CE || CE->getNumArgs() != 1)
8908 // Check for a call to std::move
8909 const FunctionDecl *FD = CE->getDirectCallee();
8910 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8911 !FD->getIdentifier()->isStr("move"))
8914 // Get argument from std::move
8915 RHSExpr = CE->getArg(0);
8917 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8918 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8920 // Two DeclRefExpr's, check that the decls are the same.
8921 if (LHSDeclRef && RHSDeclRef) {
8922 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8924 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8925 RHSDeclRef->getDecl()->getCanonicalDecl())
8928 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8929 << LHSExpr->getSourceRange()
8930 << RHSExpr->getSourceRange();
8934 // Member variables require a different approach to check for self moves.
8935 // MemberExpr's are the same if every nested MemberExpr refers to the same
8936 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8937 // the base Expr's are CXXThisExpr's.
8938 const Expr *LHSBase = LHSExpr;
8939 const Expr *RHSBase = RHSExpr;
8940 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8941 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8942 if (!LHSME || !RHSME)
8945 while (LHSME && RHSME) {
8946 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8947 RHSME->getMemberDecl()->getCanonicalDecl())
8950 LHSBase = LHSME->getBase();
8951 RHSBase = RHSME->getBase();
8952 LHSME = dyn_cast<MemberExpr>(LHSBase);
8953 RHSME = dyn_cast<MemberExpr>(RHSBase);
8956 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8957 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8958 if (LHSDeclRef && RHSDeclRef) {
8959 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8961 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8962 RHSDeclRef->getDecl()->getCanonicalDecl())
8965 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8966 << LHSExpr->getSourceRange()
8967 << RHSExpr->getSourceRange();
8971 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8972 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8973 << LHSExpr->getSourceRange()
8974 << RHSExpr->getSourceRange();
8977 //===--- Layout compatibility ----------------------------------------------//
8981 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8983 /// \brief Check if two enumeration types are layout-compatible.
8984 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8985 // C++11 [dcl.enum] p8:
8986 // Two enumeration types are layout-compatible if they have the same
8988 return ED1->isComplete() && ED2->isComplete() &&
8989 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8992 /// \brief Check if two fields are layout-compatible.
8993 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8994 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8997 if (Field1->isBitField() != Field2->isBitField())
9000 if (Field1->isBitField()) {
9001 // Make sure that the bit-fields are the same length.
9002 unsigned Bits1 = Field1->getBitWidthValue(C);
9003 unsigned Bits2 = Field2->getBitWidthValue(C);
9012 /// \brief Check if two standard-layout structs are layout-compatible.
9013 /// (C++11 [class.mem] p17)
9014 bool isLayoutCompatibleStruct(ASTContext &C,
9017 // If both records are C++ classes, check that base classes match.
9018 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9019 // If one of records is a CXXRecordDecl we are in C++ mode,
9020 // thus the other one is a CXXRecordDecl, too.
9021 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9022 // Check number of base classes.
9023 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9026 // Check the base classes.
9027 for (CXXRecordDecl::base_class_const_iterator
9028 Base1 = D1CXX->bases_begin(),
9029 BaseEnd1 = D1CXX->bases_end(),
9030 Base2 = D2CXX->bases_begin();
9033 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9036 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9037 // If only RD2 is a C++ class, it should have zero base classes.
9038 if (D2CXX->getNumBases() > 0)
9042 // Check the fields.
9043 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9044 Field2End = RD2->field_end(),
9045 Field1 = RD1->field_begin(),
9046 Field1End = RD1->field_end();
9047 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9048 if (!isLayoutCompatible(C, *Field1, *Field2))
9051 if (Field1 != Field1End || Field2 != Field2End)
9057 /// \brief Check if two standard-layout unions are layout-compatible.
9058 /// (C++11 [class.mem] p18)
9059 bool isLayoutCompatibleUnion(ASTContext &C,
9062 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
9063 for (auto *Field2 : RD2->fields())
9064 UnmatchedFields.insert(Field2);
9066 for (auto *Field1 : RD1->fields()) {
9067 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9068 I = UnmatchedFields.begin(),
9069 E = UnmatchedFields.end();
9071 for ( ; I != E; ++I) {
9072 if (isLayoutCompatible(C, Field1, *I)) {
9073 bool Result = UnmatchedFields.erase(*I);
9083 return UnmatchedFields.empty();
9086 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9087 if (RD1->isUnion() != RD2->isUnion())
9091 return isLayoutCompatibleUnion(C, RD1, RD2);
9093 return isLayoutCompatibleStruct(C, RD1, RD2);
9096 /// \brief Check if two types are layout-compatible in C++11 sense.
9097 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9098 if (T1.isNull() || T2.isNull())
9101 // C++11 [basic.types] p11:
9102 // If two types T1 and T2 are the same type, then T1 and T2 are
9103 // layout-compatible types.
9104 if (C.hasSameType(T1, T2))
9107 T1 = T1.getCanonicalType().getUnqualifiedType();
9108 T2 = T2.getCanonicalType().getUnqualifiedType();
9110 const Type::TypeClass TC1 = T1->getTypeClass();
9111 const Type::TypeClass TC2 = T2->getTypeClass();
9116 if (TC1 == Type::Enum) {
9117 return isLayoutCompatible(C,
9118 cast<EnumType>(T1)->getDecl(),
9119 cast<EnumType>(T2)->getDecl());
9120 } else if (TC1 == Type::Record) {
9121 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9124 return isLayoutCompatible(C,
9125 cast<RecordType>(T1)->getDecl(),
9126 cast<RecordType>(T2)->getDecl());
9133 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9136 /// \brief Given a type tag expression find the type tag itself.
9138 /// \param TypeExpr Type tag expression, as it appears in user's code.
9140 /// \param VD Declaration of an identifier that appears in a type tag.
9142 /// \param MagicValue Type tag magic value.
9143 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9144 const ValueDecl **VD, uint64_t *MagicValue) {
9149 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9151 switch (TypeExpr->getStmtClass()) {
9152 case Stmt::UnaryOperatorClass: {
9153 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9154 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9155 TypeExpr = UO->getSubExpr();
9161 case Stmt::DeclRefExprClass: {
9162 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9163 *VD = DRE->getDecl();
9167 case Stmt::IntegerLiteralClass: {
9168 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9169 llvm::APInt MagicValueAPInt = IL->getValue();
9170 if (MagicValueAPInt.getActiveBits() <= 64) {
9171 *MagicValue = MagicValueAPInt.getZExtValue();
9177 case Stmt::BinaryConditionalOperatorClass:
9178 case Stmt::ConditionalOperatorClass: {
9179 const AbstractConditionalOperator *ACO =
9180 cast<AbstractConditionalOperator>(TypeExpr);
9182 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9184 TypeExpr = ACO->getTrueExpr();
9186 TypeExpr = ACO->getFalseExpr();
9192 case Stmt::BinaryOperatorClass: {
9193 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9194 if (BO->getOpcode() == BO_Comma) {
9195 TypeExpr = BO->getRHS();
9207 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
9209 /// \param TypeExpr Expression that specifies a type tag.
9211 /// \param MagicValues Registered magic values.
9213 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9216 /// \param TypeInfo Information about the corresponding C type.
9218 /// \returns true if the corresponding C type was found.
9219 bool GetMatchingCType(
9220 const IdentifierInfo *ArgumentKind,
9221 const Expr *TypeExpr, const ASTContext &Ctx,
9222 const llvm::DenseMap<Sema::TypeTagMagicValue,
9223 Sema::TypeTagData> *MagicValues,
9224 bool &FoundWrongKind,
9225 Sema::TypeTagData &TypeInfo) {
9226 FoundWrongKind = false;
9228 // Variable declaration that has type_tag_for_datatype attribute.
9229 const ValueDecl *VD = nullptr;
9231 uint64_t MagicValue;
9233 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9237 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
9238 if (I->getArgumentKind() != ArgumentKind) {
9239 FoundWrongKind = true;
9242 TypeInfo.Type = I->getMatchingCType();
9243 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9244 TypeInfo.MustBeNull = I->getMustBeNull();
9253 llvm::DenseMap<Sema::TypeTagMagicValue,
9254 Sema::TypeTagData>::const_iterator I =
9255 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9256 if (I == MagicValues->end())
9259 TypeInfo = I->second;
9262 } // unnamed namespace
9264 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9265 uint64_t MagicValue, QualType Type,
9266 bool LayoutCompatible,
9268 if (!TypeTagForDatatypeMagicValues)
9269 TypeTagForDatatypeMagicValues.reset(
9270 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9272 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9273 (*TypeTagForDatatypeMagicValues)[Magic] =
9274 TypeTagData(Type, LayoutCompatible, MustBeNull);
9278 bool IsSameCharType(QualType T1, QualType T2) {
9279 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9283 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9287 BuiltinType::Kind T1Kind = BT1->getKind();
9288 BuiltinType::Kind T2Kind = BT2->getKind();
9290 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9291 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9292 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9293 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9295 } // unnamed namespace
9297 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9298 const Expr * const *ExprArgs) {
9299 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9300 bool IsPointerAttr = Attr->getIsPointer();
9302 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9303 bool FoundWrongKind;
9304 TypeTagData TypeInfo;
9305 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9306 TypeTagForDatatypeMagicValues.get(),
9307 FoundWrongKind, TypeInfo)) {
9309 Diag(TypeTagExpr->getExprLoc(),
9310 diag::warn_type_tag_for_datatype_wrong_kind)
9311 << TypeTagExpr->getSourceRange();
9315 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9316 if (IsPointerAttr) {
9317 // Skip implicit cast of pointer to `void *' (as a function argument).
9318 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
9319 if (ICE->getType()->isVoidPointerType() &&
9320 ICE->getCastKind() == CK_BitCast)
9321 ArgumentExpr = ICE->getSubExpr();
9323 QualType ArgumentType = ArgumentExpr->getType();
9325 // Passing a `void*' pointer shouldn't trigger a warning.
9326 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9329 if (TypeInfo.MustBeNull) {
9330 // Type tag with matching void type requires a null pointer.
9331 if (!ArgumentExpr->isNullPointerConstant(Context,
9332 Expr::NPC_ValueDependentIsNotNull)) {
9333 Diag(ArgumentExpr->getExprLoc(),
9334 diag::warn_type_safety_null_pointer_required)
9335 << ArgumentKind->getName()
9336 << ArgumentExpr->getSourceRange()
9337 << TypeTagExpr->getSourceRange();
9342 QualType RequiredType = TypeInfo.Type;
9344 RequiredType = Context.getPointerType(RequiredType);
9346 bool mismatch = false;
9347 if (!TypeInfo.LayoutCompatible) {
9348 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9350 // C++11 [basic.fundamental] p1:
9351 // Plain char, signed char, and unsigned char are three distinct types.
9353 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9354 // char' depending on the current char signedness mode.
9356 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9357 RequiredType->getPointeeType())) ||
9358 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9362 mismatch = !isLayoutCompatible(Context,
9363 ArgumentType->getPointeeType(),
9364 RequiredType->getPointeeType());
9366 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9369 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
9370 << ArgumentType << ArgumentKind
9371 << TypeInfo.LayoutCompatible << RequiredType
9372 << ArgumentExpr->getSourceRange()
9373 << TypeTagExpr->getSourceRange();