1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements extra semantic analysis beyond what is enforced 11 // by the C type system. 12 // 13 //===----------------------------------------------------------------------===// 14 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" 40 #include <limits> 41 using namespace clang; 42 using namespace sema; 43 44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 45 unsigned ByteNo) const { 46 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 47 Context.getTargetInfo()); 48 } 49 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; 55 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(); 60 61 // Highlight all the excess arguments. 62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 63 call->getArg(argCount - 1)->getLocEnd()); 64 65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 66 << 0 /*function call*/ << desiredArgCount << argCount 67 << call->getArg(1)->getSourceRange(); 68 } 69 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)) 74 return true; 75 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(); 82 return true; 83 } 84 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(); 91 return true; 92 } 93 94 TheCall->setType(Ty); 95 return false; 96 } 97 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)) 102 return true; 103 104 ExprResult Arg(TheCall->getArg(0)); 105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 106 if (ResultType.isNull()) 107 return true; 108 109 TheCall->setArg(0, Arg.get()); 110 TheCall->setType(ResultType); 111 return false; 112 } 113 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) 119 return; 120 121 const Expr *SizeArg = TheCall->getArg(SizeIdx); 122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 123 124 llvm::APSInt Size, DstSize; 125 126 // find out if both sizes are known at compile time 127 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 129 return; 130 131 if (Size.ule(DstSize)) 132 return; 133 134 // confirmed overflow so generate the diagnostic. 135 IdentifierInfo *FnName = FDecl->getIdentifier(); 136 SourceLocation SL = TheCall->getLocStart(); 137 SourceRange SR = TheCall->getSourceRange(); 138 139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 140 } 141 142 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 143 if (checkArgCount(S, BuiltinCall, 2)) 144 return true; 145 146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 148 Expr *Call = BuiltinCall->getArg(0); 149 Expr *Chain = BuiltinCall->getArg(1); 150 151 if (Call->getStmtClass() != Stmt::CallExprClass) { 152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 153 << Call->getSourceRange(); 154 return true; 155 } 156 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(); 161 return true; 162 } 163 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(); 169 return true; 170 } 171 172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 174 << Call->getSourceRange(); 175 return true; 176 } 177 178 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 179 if (ChainResult.isInvalid()) 180 return true; 181 if (!ChainResult.get()->getType()->isPointerType()) { 182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 183 << Chain->getSourceRange(); 184 return true; 185 } 186 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); 192 193 Builtin = 194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 195 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()); 201 202 return false; 203 } 204 205 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 206 Scope::ScopeFlags NeededScopeFlags, 207 unsigned DiagID) { 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()) 212 return false; 213 214 Scope *S = SemaRef.getCurScope(); 215 while (S && !S->isSEHExceptScope()) 216 S = S->getParent(); 217 if (!S || !(S->getFlags() & NeededScopeFlags)) { 218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 219 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 220 << DRE->getDecl()->getIdentifier(); 221 return true; 222 } 223 224 return false; 225 } 226 227 ExprResult 228 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 229 CallExpr *TheCall) { 230 ExprResult TheCallResult(TheCall); 231 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. 238 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; 243 244 llvm::APSInt Result; 245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 246 return true; 247 ICEArguments &= ~(1 << ArgNo); 248 } 249 250 switch (BuiltinID) { 251 case Builtin::BI__builtin___CFStringMakeConstantString: 252 assert(TheCall->getNumArgs() == 1 && 253 "Wrong # arguments to builtin CFStringMakeConstantString"); 254 if (CheckObjCString(TheCall->getArg(0))) 255 return ExprError(); 256 break; 257 case Builtin::BI__builtin_stdarg_start: 258 case Builtin::BI__builtin_va_start: 259 if (SemaBuiltinVAStart(TheCall)) 260 return ExprError(); 261 break; 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)) 267 return ExprError(); 268 break; 269 default: 270 if (SemaBuiltinVAStart(TheCall)) 271 return ExprError(); 272 break; 273 } 274 break; 275 } 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)) 283 return ExprError(); 284 break; 285 case Builtin::BI__builtin_fpclassify: 286 if (SemaBuiltinFPClassification(TheCall, 6)) 287 return ExprError(); 288 break; 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)) 295 return ExprError(); 296 break; 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)) 303 return ExprError(); 304 break; 305 case Builtin::BI__assume: 306 case Builtin::BI__builtin_assume: 307 if (SemaBuiltinAssume(TheCall)) 308 return ExprError(); 309 break; 310 case Builtin::BI__builtin_assume_aligned: 311 if (SemaBuiltinAssumeAligned(TheCall)) 312 return ExprError(); 313 break; 314 case Builtin::BI__builtin_object_size: 315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 316 return ExprError(); 317 break; 318 case Builtin::BI__builtin_longjmp: 319 if (SemaBuiltinLongjmp(TheCall)) 320 return ExprError(); 321 break; 322 323 case Builtin::BI__builtin_classify_type: 324 if (checkArgCount(*this, TheCall, 1)) return true; 325 TheCall->setType(Context.IntTy); 326 break; 327 case Builtin::BI__builtin_constant_p: 328 if (checkArgCount(*this, TheCall, 1)) return true; 329 TheCall->setType(Context.IntTy); 330 break; 331 case Builtin::BI__sync_fetch_and_add: 332 case Builtin::BI__sync_fetch_and_add_1: 333 case Builtin::BI__sync_fetch_and_add_2: 334 case Builtin::BI__sync_fetch_and_add_4: 335 case Builtin::BI__sync_fetch_and_add_8: 336 case Builtin::BI__sync_fetch_and_add_16: 337 case Builtin::BI__sync_fetch_and_sub: 338 case Builtin::BI__sync_fetch_and_sub_1: 339 case Builtin::BI__sync_fetch_and_sub_2: 340 case Builtin::BI__sync_fetch_and_sub_4: 341 case Builtin::BI__sync_fetch_and_sub_8: 342 case Builtin::BI__sync_fetch_and_sub_16: 343 case Builtin::BI__sync_fetch_and_or: 344 case Builtin::BI__sync_fetch_and_or_1: 345 case Builtin::BI__sync_fetch_and_or_2: 346 case Builtin::BI__sync_fetch_and_or_4: 347 case Builtin::BI__sync_fetch_and_or_8: 348 case Builtin::BI__sync_fetch_and_or_16: 349 case Builtin::BI__sync_fetch_and_and: 350 case Builtin::BI__sync_fetch_and_and_1: 351 case Builtin::BI__sync_fetch_and_and_2: 352 case Builtin::BI__sync_fetch_and_and_4: 353 case Builtin::BI__sync_fetch_and_and_8: 354 case Builtin::BI__sync_fetch_and_and_16: 355 case Builtin::BI__sync_fetch_and_xor: 356 case Builtin::BI__sync_fetch_and_xor_1: 357 case Builtin::BI__sync_fetch_and_xor_2: 358 case Builtin::BI__sync_fetch_and_xor_4: 359 case Builtin::BI__sync_fetch_and_xor_8: 360 case Builtin::BI__sync_fetch_and_xor_16: 361 case Builtin::BI__sync_fetch_and_nand: 362 case Builtin::BI__sync_fetch_and_nand_1: 363 case Builtin::BI__sync_fetch_and_nand_2: 364 case Builtin::BI__sync_fetch_and_nand_4: 365 case Builtin::BI__sync_fetch_and_nand_8: 366 case Builtin::BI__sync_fetch_and_nand_16: 367 case Builtin::BI__sync_add_and_fetch: 368 case Builtin::BI__sync_add_and_fetch_1: 369 case Builtin::BI__sync_add_and_fetch_2: 370 case Builtin::BI__sync_add_and_fetch_4: 371 case Builtin::BI__sync_add_and_fetch_8: 372 case Builtin::BI__sync_add_and_fetch_16: 373 case Builtin::BI__sync_sub_and_fetch: 374 case Builtin::BI__sync_sub_and_fetch_1: 375 case Builtin::BI__sync_sub_and_fetch_2: 376 case Builtin::BI__sync_sub_and_fetch_4: 377 case Builtin::BI__sync_sub_and_fetch_8: 378 case Builtin::BI__sync_sub_and_fetch_16: 379 case Builtin::BI__sync_and_and_fetch: 380 case Builtin::BI__sync_and_and_fetch_1: 381 case Builtin::BI__sync_and_and_fetch_2: 382 case Builtin::BI__sync_and_and_fetch_4: 383 case Builtin::BI__sync_and_and_fetch_8: 384 case Builtin::BI__sync_and_and_fetch_16: 385 case Builtin::BI__sync_or_and_fetch: 386 case Builtin::BI__sync_or_and_fetch_1: 387 case Builtin::BI__sync_or_and_fetch_2: 388 case Builtin::BI__sync_or_and_fetch_4: 389 case Builtin::BI__sync_or_and_fetch_8: 390 case Builtin::BI__sync_or_and_fetch_16: 391 case Builtin::BI__sync_xor_and_fetch: 392 case Builtin::BI__sync_xor_and_fetch_1: 393 case Builtin::BI__sync_xor_and_fetch_2: 394 case Builtin::BI__sync_xor_and_fetch_4: 395 case Builtin::BI__sync_xor_and_fetch_8: 396 case Builtin::BI__sync_xor_and_fetch_16: 397 case Builtin::BI__sync_nand_and_fetch: 398 case Builtin::BI__sync_nand_and_fetch_1: 399 case Builtin::BI__sync_nand_and_fetch_2: 400 case Builtin::BI__sync_nand_and_fetch_4: 401 case Builtin::BI__sync_nand_and_fetch_8: 402 case Builtin::BI__sync_nand_and_fetch_16: 403 case Builtin::BI__sync_val_compare_and_swap: 404 case Builtin::BI__sync_val_compare_and_swap_1: 405 case Builtin::BI__sync_val_compare_and_swap_2: 406 case Builtin::BI__sync_val_compare_and_swap_4: 407 case Builtin::BI__sync_val_compare_and_swap_8: 408 case Builtin::BI__sync_val_compare_and_swap_16: 409 case Builtin::BI__sync_bool_compare_and_swap: 410 case Builtin::BI__sync_bool_compare_and_swap_1: 411 case Builtin::BI__sync_bool_compare_and_swap_2: 412 case Builtin::BI__sync_bool_compare_and_swap_4: 413 case Builtin::BI__sync_bool_compare_and_swap_8: 414 case Builtin::BI__sync_bool_compare_and_swap_16: 415 case Builtin::BI__sync_lock_test_and_set: 416 case Builtin::BI__sync_lock_test_and_set_1: 417 case Builtin::BI__sync_lock_test_and_set_2: 418 case Builtin::BI__sync_lock_test_and_set_4: 419 case Builtin::BI__sync_lock_test_and_set_8: 420 case Builtin::BI__sync_lock_test_and_set_16: 421 case Builtin::BI__sync_lock_release: 422 case Builtin::BI__sync_lock_release_1: 423 case Builtin::BI__sync_lock_release_2: 424 case Builtin::BI__sync_lock_release_4: 425 case Builtin::BI__sync_lock_release_8: 426 case Builtin::BI__sync_lock_release_16: 427 case Builtin::BI__sync_swap: 428 case Builtin::BI__sync_swap_1: 429 case Builtin::BI__sync_swap_2: 430 case Builtin::BI__sync_swap_4: 431 case Builtin::BI__sync_swap_8: 432 case Builtin::BI__sync_swap_16: 433 return SemaBuiltinAtomicOverloaded(TheCallResult); 434 #define BUILTIN(ID, TYPE, ATTRS) 435 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 436 case Builtin::BI##ID: \ 437 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 438 #include "clang/Basic/Builtins.def" 439 case Builtin::BI__builtin_annotation: 440 if (SemaBuiltinAnnotation(*this, TheCall)) 441 return ExprError(); 442 break; 443 case Builtin::BI__builtin_addressof: 444 if (SemaBuiltinAddressof(*this, TheCall)) 445 return ExprError(); 446 break; 447 case Builtin::BI__builtin_operator_new: 448 case Builtin::BI__builtin_operator_delete: 449 if (!getLangOpts().CPlusPlus) { 450 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 451 << (BuiltinID == Builtin::BI__builtin_operator_new 452 ? "__builtin_operator_new" 453 : "__builtin_operator_delete") 454 << "C++"; 455 return ExprError(); 456 } 457 // CodeGen assumes it can find the global new and delete to call, 458 // so ensure that they are declared. 459 DeclareGlobalNewDelete(); 460 break; 461 462 // check secure string manipulation functions where overflows 463 // are detectable at compile time 464 case Builtin::BI__builtin___memcpy_chk: 465 case Builtin::BI__builtin___memmove_chk: 466 case Builtin::BI__builtin___memset_chk: 467 case Builtin::BI__builtin___strlcat_chk: 468 case Builtin::BI__builtin___strlcpy_chk: 469 case Builtin::BI__builtin___strncat_chk: 470 case Builtin::BI__builtin___strncpy_chk: 471 case Builtin::BI__builtin___stpncpy_chk: 472 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 473 break; 474 case Builtin::BI__builtin___memccpy_chk: 475 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 476 break; 477 case Builtin::BI__builtin___snprintf_chk: 478 case Builtin::BI__builtin___vsnprintf_chk: 479 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 480 break; 481 482 case Builtin::BI__builtin_call_with_static_chain: 483 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 484 return ExprError(); 485 break; 486 487 case Builtin::BI__exception_code: 488 case Builtin::BI_exception_code: { 489 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 490 diag::err_seh___except_block)) 491 return ExprError(); 492 break; 493 } 494 case Builtin::BI__exception_info: 495 case Builtin::BI_exception_info: { 496 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 497 diag::err_seh___except_filter)) 498 return ExprError(); 499 break; 500 } 501 502 } 503 504 // Since the target specific builtins for each arch overlap, only check those 505 // of the arch we are compiling for. 506 if (BuiltinID >= Builtin::FirstTSBuiltin) { 507 switch (Context.getTargetInfo().getTriple().getArch()) { 508 case llvm::Triple::arm: 509 case llvm::Triple::armeb: 510 case llvm::Triple::thumb: 511 case llvm::Triple::thumbeb: 512 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 513 return ExprError(); 514 break; 515 case llvm::Triple::aarch64: 516 case llvm::Triple::aarch64_be: 517 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 518 return ExprError(); 519 break; 520 case llvm::Triple::mips: 521 case llvm::Triple::mipsel: 522 case llvm::Triple::mips64: 523 case llvm::Triple::mips64el: 524 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 525 return ExprError(); 526 break; 527 case llvm::Triple::x86: 528 case llvm::Triple::x86_64: 529 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 530 return ExprError(); 531 break; 532 default: 533 break; 534 } 535 } 536 537 return TheCallResult; 538 } 539 540 // Get the valid immediate range for the specified NEON type code. 541 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 542 NeonTypeFlags Type(t); 543 int IsQuad = ForceQuad ? true : Type.isQuad(); 544 switch (Type.getEltType()) { 545 case NeonTypeFlags::Int8: 546 case NeonTypeFlags::Poly8: 547 return shift ? 7 : (8 << IsQuad) - 1; 548 case NeonTypeFlags::Int16: 549 case NeonTypeFlags::Poly16: 550 return shift ? 15 : (4 << IsQuad) - 1; 551 case NeonTypeFlags::Int32: 552 return shift ? 31 : (2 << IsQuad) - 1; 553 case NeonTypeFlags::Int64: 554 case NeonTypeFlags::Poly64: 555 return shift ? 63 : (1 << IsQuad) - 1; 556 case NeonTypeFlags::Poly128: 557 return shift ? 127 : (1 << IsQuad) - 1; 558 case NeonTypeFlags::Float16: 559 assert(!shift && "cannot shift float types!"); 560 return (4 << IsQuad) - 1; 561 case NeonTypeFlags::Float32: 562 assert(!shift && "cannot shift float types!"); 563 return (2 << IsQuad) - 1; 564 case NeonTypeFlags::Float64: 565 assert(!shift && "cannot shift float types!"); 566 return (1 << IsQuad) - 1; 567 } 568 llvm_unreachable("Invalid NeonTypeFlag!"); 569 } 570 571 /// getNeonEltType - Return the QualType corresponding to the elements of 572 /// the vector type specified by the NeonTypeFlags. This is used to check 573 /// the pointer arguments for Neon load/store intrinsics. 574 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 575 bool IsPolyUnsigned, bool IsInt64Long) { 576 switch (Flags.getEltType()) { 577 case NeonTypeFlags::Int8: 578 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 579 case NeonTypeFlags::Int16: 580 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 581 case NeonTypeFlags::Int32: 582 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 583 case NeonTypeFlags::Int64: 584 if (IsInt64Long) 585 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 586 else 587 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 588 : Context.LongLongTy; 589 case NeonTypeFlags::Poly8: 590 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 591 case NeonTypeFlags::Poly16: 592 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 593 case NeonTypeFlags::Poly64: 594 return Context.UnsignedLongTy; 595 case NeonTypeFlags::Poly128: 596 break; 597 case NeonTypeFlags::Float16: 598 return Context.HalfTy; 599 case NeonTypeFlags::Float32: 600 return Context.FloatTy; 601 case NeonTypeFlags::Float64: 602 return Context.DoubleTy; 603 } 604 llvm_unreachable("Invalid NeonTypeFlag!"); 605 } 606 607 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 608 llvm::APSInt Result; 609 uint64_t mask = 0; 610 unsigned TV = 0; 611 int PtrArgNum = -1; 612 bool HasConstPtr = false; 613 switch (BuiltinID) { 614 #define GET_NEON_OVERLOAD_CHECK 615 #include "clang/Basic/arm_neon.inc" 616 #undef GET_NEON_OVERLOAD_CHECK 617 } 618 619 // For NEON intrinsics which are overloaded on vector element type, validate 620 // the immediate which specifies which variant to emit. 621 unsigned ImmArg = TheCall->getNumArgs()-1; 622 if (mask) { 623 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 624 return true; 625 626 TV = Result.getLimitedValue(64); 627 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 628 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 629 << TheCall->getArg(ImmArg)->getSourceRange(); 630 } 631 632 if (PtrArgNum >= 0) { 633 // Check that pointer arguments have the specified type. 634 Expr *Arg = TheCall->getArg(PtrArgNum); 635 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 636 Arg = ICE->getSubExpr(); 637 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 638 QualType RHSTy = RHS.get()->getType(); 639 640 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 641 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64; 642 bool IsInt64Long = 643 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 644 QualType EltTy = 645 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 646 if (HasConstPtr) 647 EltTy = EltTy.withConst(); 648 QualType LHSTy = Context.getPointerType(EltTy); 649 AssignConvertType ConvTy; 650 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 651 if (RHS.isInvalid()) 652 return true; 653 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 654 RHS.get(), AA_Assigning)) 655 return true; 656 } 657 658 // For NEON intrinsics which take an immediate value as part of the 659 // instruction, range check them here. 660 unsigned i = 0, l = 0, u = 0; 661 switch (BuiltinID) { 662 default: 663 return false; 664 #define GET_NEON_IMMEDIATE_CHECK 665 #include "clang/Basic/arm_neon.inc" 666 #undef GET_NEON_IMMEDIATE_CHECK 667 } 668 669 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 670 } 671 672 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 673 unsigned MaxWidth) { 674 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 675 BuiltinID == ARM::BI__builtin_arm_ldaex || 676 BuiltinID == ARM::BI__builtin_arm_strex || 677 BuiltinID == ARM::BI__builtin_arm_stlex || 678 BuiltinID == AArch64::BI__builtin_arm_ldrex || 679 BuiltinID == AArch64::BI__builtin_arm_ldaex || 680 BuiltinID == AArch64::BI__builtin_arm_strex || 681 BuiltinID == AArch64::BI__builtin_arm_stlex) && 682 "unexpected ARM builtin"); 683 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 684 BuiltinID == ARM::BI__builtin_arm_ldaex || 685 BuiltinID == AArch64::BI__builtin_arm_ldrex || 686 BuiltinID == AArch64::BI__builtin_arm_ldaex; 687 688 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 689 690 // Ensure that we have the proper number of arguments. 691 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 692 return true; 693 694 // Inspect the pointer argument of the atomic builtin. This should always be 695 // a pointer type, whose element is an integral scalar or pointer type. 696 // Because it is a pointer type, we don't have to worry about any implicit 697 // casts here. 698 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 699 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 700 if (PointerArgRes.isInvalid()) 701 return true; 702 PointerArg = PointerArgRes.get(); 703 704 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 705 if (!pointerType) { 706 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 707 << PointerArg->getType() << PointerArg->getSourceRange(); 708 return true; 709 } 710 711 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 712 // task is to insert the appropriate casts into the AST. First work out just 713 // what the appropriate type is. 714 QualType ValType = pointerType->getPointeeType(); 715 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 716 if (IsLdrex) 717 AddrType.addConst(); 718 719 // Issue a warning if the cast is dodgy. 720 CastKind CastNeeded = CK_NoOp; 721 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 722 CastNeeded = CK_BitCast; 723 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 724 << PointerArg->getType() 725 << Context.getPointerType(AddrType) 726 << AA_Passing << PointerArg->getSourceRange(); 727 } 728 729 // Finally, do the cast and replace the argument with the corrected version. 730 AddrType = Context.getPointerType(AddrType); 731 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 732 if (PointerArgRes.isInvalid()) 733 return true; 734 PointerArg = PointerArgRes.get(); 735 736 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 737 738 // In general, we allow ints, floats and pointers to be loaded and stored. 739 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 740 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 742 << PointerArg->getType() << PointerArg->getSourceRange(); 743 return true; 744 } 745 746 // But ARM doesn't have instructions to deal with 128-bit versions. 747 if (Context.getTypeSize(ValType) > MaxWidth) { 748 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 749 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 750 << PointerArg->getType() << PointerArg->getSourceRange(); 751 return true; 752 } 753 754 switch (ValType.getObjCLifetime()) { 755 case Qualifiers::OCL_None: 756 case Qualifiers::OCL_ExplicitNone: 757 // okay 758 break; 759 760 case Qualifiers::OCL_Weak: 761 case Qualifiers::OCL_Strong: 762 case Qualifiers::OCL_Autoreleasing: 763 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 764 << ValType << PointerArg->getSourceRange(); 765 return true; 766 } 767 768 769 if (IsLdrex) { 770 TheCall->setType(ValType); 771 return false; 772 } 773 774 // Initialize the argument to be stored. 775 ExprResult ValArg = TheCall->getArg(0); 776 InitializedEntity Entity = InitializedEntity::InitializeParameter( 777 Context, ValType, /*consume*/ false); 778 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 779 if (ValArg.isInvalid()) 780 return true; 781 TheCall->setArg(0, ValArg.get()); 782 783 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 784 // but the custom checker bypasses all default analysis. 785 TheCall->setType(Context.IntTy); 786 return false; 787 } 788 789 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 790 llvm::APSInt Result; 791 792 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 793 BuiltinID == ARM::BI__builtin_arm_ldaex || 794 BuiltinID == ARM::BI__builtin_arm_strex || 795 BuiltinID == ARM::BI__builtin_arm_stlex) { 796 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 797 } 798 799 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 801 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 802 } 803 804 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 805 return true; 806 807 // For intrinsics which take an immediate value as part of the instruction, 808 // range check them here. 809 unsigned i = 0, l = 0, u = 0; 810 switch (BuiltinID) { 811 default: return false; 812 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break; 813 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break; 814 case ARM::BI__builtin_arm_vcvtr_f: 815 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break; 816 case ARM::BI__builtin_arm_dmb: 817 case ARM::BI__builtin_arm_dsb: 818 case ARM::BI__builtin_arm_isb: 819 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break; 820 } 821 822 // FIXME: VFP Intrinsics should error if VFP not present. 823 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 824 } 825 826 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 827 CallExpr *TheCall) { 828 llvm::APSInt Result; 829 830 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 831 BuiltinID == AArch64::BI__builtin_arm_ldaex || 832 BuiltinID == AArch64::BI__builtin_arm_strex || 833 BuiltinID == AArch64::BI__builtin_arm_stlex) { 834 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 835 } 836 837 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 838 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 840 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 841 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 842 } 843 844 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 845 return true; 846 847 // For intrinsics which take an immediate value as part of the instruction, 848 // range check them here. 849 unsigned i = 0, l = 0, u = 0; 850 switch (BuiltinID) { 851 default: return false; 852 case AArch64::BI__builtin_arm_dmb: 853 case AArch64::BI__builtin_arm_dsb: 854 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 855 } 856 857 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 858 } 859 860 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 861 unsigned i = 0, l = 0, u = 0; 862 switch (BuiltinID) { 863 default: return false; 864 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 865 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 866 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 867 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 868 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 869 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 870 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 871 } 872 873 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 874 } 875 876 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 877 unsigned i = 0, l = 0, u = 0; 878 switch (BuiltinID) { 879 default: return false; 880 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break; 881 case X86::BI__builtin_ia32_vextractf128_pd256: 882 case X86::BI__builtin_ia32_vextractf128_ps256: 883 case X86::BI__builtin_ia32_vextractf128_si256: 884 case X86::BI__builtin_ia32_extract128i256: i = 1, l = 0, u = 1; break; 885 case X86::BI__builtin_ia32_insert128i256: i = 2, l = 0; u = 1; break; 886 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break; 887 case X86::BI__builtin_ia32_vpermil2pd: 888 case X86::BI__builtin_ia32_vpermil2pd256: 889 case X86::BI__builtin_ia32_vpermil2ps: 890 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break; 891 case X86::BI__builtin_ia32_cmpb128_mask: 892 case X86::BI__builtin_ia32_cmpw128_mask: 893 case X86::BI__builtin_ia32_cmpd128_mask: 894 case X86::BI__builtin_ia32_cmpq128_mask: 895 case X86::BI__builtin_ia32_cmpb256_mask: 896 case X86::BI__builtin_ia32_cmpw256_mask: 897 case X86::BI__builtin_ia32_cmpd256_mask: 898 case X86::BI__builtin_ia32_cmpq256_mask: 899 case X86::BI__builtin_ia32_cmpb512_mask: 900 case X86::BI__builtin_ia32_cmpw512_mask: 901 case X86::BI__builtin_ia32_cmpd512_mask: 902 case X86::BI__builtin_ia32_cmpq512_mask: 903 case X86::BI__builtin_ia32_ucmpb128_mask: 904 case X86::BI__builtin_ia32_ucmpw128_mask: 905 case X86::BI__builtin_ia32_ucmpd128_mask: 906 case X86::BI__builtin_ia32_ucmpq128_mask: 907 case X86::BI__builtin_ia32_ucmpb256_mask: 908 case X86::BI__builtin_ia32_ucmpw256_mask: 909 case X86::BI__builtin_ia32_ucmpd256_mask: 910 case X86::BI__builtin_ia32_ucmpq256_mask: 911 case X86::BI__builtin_ia32_ucmpb512_mask: 912 case X86::BI__builtin_ia32_ucmpw512_mask: 913 case X86::BI__builtin_ia32_ucmpd512_mask: 914 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break; 915 case X86::BI__builtin_ia32_roundps: 916 case X86::BI__builtin_ia32_roundpd: 917 case X86::BI__builtin_ia32_roundps256: 918 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break; 919 case X86::BI__builtin_ia32_roundss: 920 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break; 921 case X86::BI__builtin_ia32_cmpps: 922 case X86::BI__builtin_ia32_cmpss: 923 case X86::BI__builtin_ia32_cmppd: 924 case X86::BI__builtin_ia32_cmpsd: 925 case X86::BI__builtin_ia32_cmpps256: 926 case X86::BI__builtin_ia32_cmppd256: 927 case X86::BI__builtin_ia32_cmpps512_mask: 928 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break; 929 case X86::BI__builtin_ia32_vpcomub: 930 case X86::BI__builtin_ia32_vpcomuw: 931 case X86::BI__builtin_ia32_vpcomud: 932 case X86::BI__builtin_ia32_vpcomuq: 933 case X86::BI__builtin_ia32_vpcomb: 934 case X86::BI__builtin_ia32_vpcomw: 935 case X86::BI__builtin_ia32_vpcomd: 936 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break; 937 } 938 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 939 } 940 941 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 942 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 943 /// Returns true when the format fits the function and the FormatStringInfo has 944 /// been populated. 945 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 946 FormatStringInfo *FSI) { 947 FSI->HasVAListArg = Format->getFirstArg() == 0; 948 FSI->FormatIdx = Format->getFormatIdx() - 1; 949 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 950 951 // The way the format attribute works in GCC, the implicit this argument 952 // of member functions is counted. However, it doesn't appear in our own 953 // lists, so decrement format_idx in that case. 954 if (IsCXXMember) { 955 if(FSI->FormatIdx == 0) 956 return false; 957 --FSI->FormatIdx; 958 if (FSI->FirstDataArg != 0) 959 --FSI->FirstDataArg; 960 } 961 return true; 962 } 963 964 /// Checks if a the given expression evaluates to null. 965 /// 966 /// \brief Returns true if the value evaluates to null. 967 static bool CheckNonNullExpr(Sema &S, 968 const Expr *Expr) { 969 // As a special case, transparent unions initialized with zero are 970 // considered null for the purposes of the nonnull attribute. 971 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 972 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 973 if (const CompoundLiteralExpr *CLE = 974 dyn_cast<CompoundLiteralExpr>(Expr)) 975 if (const InitListExpr *ILE = 976 dyn_cast<InitListExpr>(CLE->getInitializer())) 977 Expr = ILE->getInit(0); 978 } 979 980 bool Result; 981 return (!Expr->isValueDependent() && 982 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 983 !Result); 984 } 985 986 static void CheckNonNullArgument(Sema &S, 987 const Expr *ArgExpr, 988 SourceLocation CallSiteLoc) { 989 if (CheckNonNullExpr(S, ArgExpr)) 990 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 991 } 992 993 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 994 FormatStringInfo FSI; 995 if ((GetFormatStringType(Format) == FST_NSString) && 996 getFormatStringInfo(Format, false, &FSI)) { 997 Idx = FSI.FormatIdx; 998 return true; 999 } 1000 return false; 1001 } 1002 /// \brief Diagnose use of %s directive in an NSString which is being passed 1003 /// as formatting string to formatting method. 1004 static void 1005 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 1006 const NamedDecl *FDecl, 1007 Expr **Args, 1008 unsigned NumArgs) { 1009 unsigned Idx = 0; 1010 bool Format = false; 1011 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 1012 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 1013 Idx = 2; 1014 Format = true; 1015 } 1016 else 1017 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 1018 if (S.GetFormatNSStringIdx(I, Idx)) { 1019 Format = true; 1020 break; 1021 } 1022 } 1023 if (!Format || NumArgs <= Idx) 1024 return; 1025 const Expr *FormatExpr = Args[Idx]; 1026 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 1027 FormatExpr = CSCE->getSubExpr(); 1028 const StringLiteral *FormatString; 1029 if (const ObjCStringLiteral *OSL = 1030 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 1031 FormatString = OSL->getString(); 1032 else 1033 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 1034 if (!FormatString) 1035 return; 1036 if (S.FormatStringHasSArg(FormatString)) { 1037 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 1038 << "%s" << 1 << 1; 1039 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 1040 << FDecl->getDeclName(); 1041 } 1042 } 1043 1044 static void CheckNonNullArguments(Sema &S, 1045 const NamedDecl *FDecl, 1046 ArrayRef<const Expr *> Args, 1047 SourceLocation CallSiteLoc) { 1048 // Check the attributes attached to the method/function itself. 1049 llvm::SmallBitVector NonNullArgs; 1050 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 1051 if (!NonNull->args_size()) { 1052 // Easy case: all pointer arguments are nonnull. 1053 for (const auto *Arg : Args) 1054 if (S.isValidPointerAttrType(Arg->getType())) 1055 CheckNonNullArgument(S, Arg, CallSiteLoc); 1056 return; 1057 } 1058 1059 for (unsigned Val : NonNull->args()) { 1060 if (Val >= Args.size()) 1061 continue; 1062 if (NonNullArgs.empty()) 1063 NonNullArgs.resize(Args.size()); 1064 NonNullArgs.set(Val); 1065 } 1066 } 1067 1068 // Check the attributes on the parameters. 1069 ArrayRef<ParmVarDecl*> parms; 1070 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 1071 parms = FD->parameters(); 1072 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl)) 1073 parms = MD->parameters(); 1074 1075 unsigned ArgIndex = 0; 1076 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 1077 I != E; ++I, ++ArgIndex) { 1078 const ParmVarDecl *PVD = *I; 1079 if (PVD->hasAttr<NonNullAttr>() || 1080 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex])) 1081 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 1082 } 1083 1084 // In case this is a variadic call, check any remaining arguments. 1085 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex) 1086 if (NonNullArgs[ArgIndex]) 1087 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 1088 } 1089 1090 /// Handles the checks for format strings, non-POD arguments to vararg 1091 /// functions, and NULL arguments passed to non-NULL parameters. 1092 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args, 1093 unsigned NumParams, bool IsMemberFunction, 1094 SourceLocation Loc, SourceRange Range, 1095 VariadicCallType CallType) { 1096 // FIXME: We should check as much as we can in the template definition. 1097 if (CurContext->isDependentContext()) 1098 return; 1099 1100 // Printf and scanf checking. 1101 llvm::SmallBitVector CheckedVarArgs; 1102 if (FDecl) { 1103 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 1104 // Only create vector if there are format attributes. 1105 CheckedVarArgs.resize(Args.size()); 1106 1107 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 1108 CheckedVarArgs); 1109 } 1110 } 1111 1112 // Refuse POD arguments that weren't caught by the format string 1113 // checks above. 1114 if (CallType != VariadicDoesNotApply) { 1115 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 1116 // Args[ArgIdx] can be null in malformed code. 1117 if (const Expr *Arg = Args[ArgIdx]) { 1118 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 1119 checkVariadicArgument(Arg, CallType); 1120 } 1121 } 1122 } 1123 1124 if (FDecl) { 1125 CheckNonNullArguments(*this, FDecl, Args, Loc); 1126 1127 // Type safety checking. 1128 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 1129 CheckArgumentWithTypeTag(I, Args.data()); 1130 } 1131 } 1132 1133 /// CheckConstructorCall - Check a constructor call for correctness and safety 1134 /// properties not enforced by the C type system. 1135 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 1136 ArrayRef<const Expr *> Args, 1137 const FunctionProtoType *Proto, 1138 SourceLocation Loc) { 1139 VariadicCallType CallType = 1140 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 1141 checkCall(FDecl, Args, Proto->getNumParams(), 1142 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType); 1143 } 1144 1145 /// CheckFunctionCall - Check a direct function call for various correctness 1146 /// and safety properties not strictly enforced by the C type system. 1147 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 1148 const FunctionProtoType *Proto) { 1149 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 1150 isa<CXXMethodDecl>(FDecl); 1151 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 1152 IsMemberOperatorCall; 1153 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 1154 TheCall->getCallee()); 1155 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 1156 Expr** Args = TheCall->getArgs(); 1157 unsigned NumArgs = TheCall->getNumArgs(); 1158 if (IsMemberOperatorCall) { 1159 // If this is a call to a member operator, hide the first argument 1160 // from checkCall. 1161 // FIXME: Our choice of AST representation here is less than ideal. 1162 ++Args; 1163 --NumArgs; 1164 } 1165 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams, 1166 IsMemberFunction, TheCall->getRParenLoc(), 1167 TheCall->getCallee()->getSourceRange(), CallType); 1168 1169 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 1170 // None of the checks below are needed for functions that don't have 1171 // simple names (e.g., C++ conversion functions). 1172 if (!FnInfo) 1173 return false; 1174 1175 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo); 1176 if (getLangOpts().ObjC1) 1177 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 1178 1179 unsigned CMId = FDecl->getMemoryFunctionKind(); 1180 if (CMId == 0) 1181 return false; 1182 1183 // Handle memory setting and copying functions. 1184 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 1185 CheckStrlcpycatArguments(TheCall, FnInfo); 1186 else if (CMId == Builtin::BIstrncat) 1187 CheckStrncatArguments(TheCall, FnInfo); 1188 else 1189 CheckMemaccessArguments(TheCall, CMId, FnInfo); 1190 1191 return false; 1192 } 1193 1194 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 1195 ArrayRef<const Expr *> Args) { 1196 VariadicCallType CallType = 1197 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 1198 1199 checkCall(Method, Args, Method->param_size(), 1200 /*IsMemberFunction=*/false, 1201 lbrac, Method->getSourceRange(), CallType); 1202 1203 return false; 1204 } 1205 1206 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 1207 const FunctionProtoType *Proto) { 1208 const VarDecl *V = dyn_cast<VarDecl>(NDecl); 1209 if (!V) 1210 return false; 1211 1212 QualType Ty = V->getType(); 1213 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType()) 1214 return false; 1215 1216 VariadicCallType CallType; 1217 if (!Proto || !Proto->isVariadic()) { 1218 CallType = VariadicDoesNotApply; 1219 } else if (Ty->isBlockPointerType()) { 1220 CallType = VariadicBlock; 1221 } else { // Ty->isFunctionPointerType() 1222 CallType = VariadicFunction; 1223 } 1224 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 1225 1226 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(), 1227 TheCall->getNumArgs()), 1228 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 1229 TheCall->getCallee()->getSourceRange(), CallType); 1230 1231 return false; 1232 } 1233 1234 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 1235 /// such as function pointers returned from functions. 1236 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 1237 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 1238 TheCall->getCallee()); 1239 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 1240 1241 checkCall(/*FDecl=*/nullptr, 1242 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 1243 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 1244 TheCall->getCallee()->getSourceRange(), CallType); 1245 1246 return false; 1247 } 1248 1249 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 1250 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed || 1251 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst) 1252 return false; 1253 1254 switch (Op) { 1255 case AtomicExpr::AO__c11_atomic_init: 1256 llvm_unreachable("There is no ordering argument for an init"); 1257 1258 case AtomicExpr::AO__c11_atomic_load: 1259 case AtomicExpr::AO__atomic_load_n: 1260 case AtomicExpr::AO__atomic_load: 1261 return Ordering != AtomicExpr::AO_ABI_memory_order_release && 1262 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel; 1263 1264 case AtomicExpr::AO__c11_atomic_store: 1265 case AtomicExpr::AO__atomic_store: 1266 case AtomicExpr::AO__atomic_store_n: 1267 return Ordering != AtomicExpr::AO_ABI_memory_order_consume && 1268 Ordering != AtomicExpr::AO_ABI_memory_order_acquire && 1269 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel; 1270 1271 default: 1272 return true; 1273 } 1274 } 1275 1276 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 1277 AtomicExpr::AtomicOp Op) { 1278 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 1279 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1280 1281 // All these operations take one of the following forms: 1282 enum { 1283 // C __c11_atomic_init(A *, C) 1284 Init, 1285 // C __c11_atomic_load(A *, int) 1286 Load, 1287 // void __atomic_load(A *, CP, int) 1288 Copy, 1289 // C __c11_atomic_add(A *, M, int) 1290 Arithmetic, 1291 // C __atomic_exchange_n(A *, CP, int) 1292 Xchg, 1293 // void __atomic_exchange(A *, C *, CP, int) 1294 GNUXchg, 1295 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 1296 C11CmpXchg, 1297 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 1298 GNUCmpXchg 1299 } Form = Init; 1300 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 }; 1301 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 }; 1302 // where: 1303 // C is an appropriate type, 1304 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 1305 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 1306 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 1307 // the int parameters are for orderings. 1308 1309 assert(AtomicExpr::AO__c11_atomic_init == 0 && 1310 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load 1311 && "need to update code for modified C11 atomics"); 1312 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init && 1313 Op <= AtomicExpr::AO__c11_atomic_fetch_xor; 1314 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 1315 Op == AtomicExpr::AO__atomic_store_n || 1316 Op == AtomicExpr::AO__atomic_exchange_n || 1317 Op == AtomicExpr::AO__atomic_compare_exchange_n; 1318 bool IsAddSub = false; 1319 1320 switch (Op) { 1321 case AtomicExpr::AO__c11_atomic_init: 1322 Form = Init; 1323 break; 1324 1325 case AtomicExpr::AO__c11_atomic_load: 1326 case AtomicExpr::AO__atomic_load_n: 1327 Form = Load; 1328 break; 1329 1330 case AtomicExpr::AO__c11_atomic_store: 1331 case AtomicExpr::AO__atomic_load: 1332 case AtomicExpr::AO__atomic_store: 1333 case AtomicExpr::AO__atomic_store_n: 1334 Form = Copy; 1335 break; 1336 1337 case AtomicExpr::AO__c11_atomic_fetch_add: 1338 case AtomicExpr::AO__c11_atomic_fetch_sub: 1339 case AtomicExpr::AO__atomic_fetch_add: 1340 case AtomicExpr::AO__atomic_fetch_sub: 1341 case AtomicExpr::AO__atomic_add_fetch: 1342 case AtomicExpr::AO__atomic_sub_fetch: 1343 IsAddSub = true; 1344 // Fall through. 1345 case AtomicExpr::AO__c11_atomic_fetch_and: 1346 case AtomicExpr::AO__c11_atomic_fetch_or: 1347 case AtomicExpr::AO__c11_atomic_fetch_xor: 1348 case AtomicExpr::AO__atomic_fetch_and: 1349 case AtomicExpr::AO__atomic_fetch_or: 1350 case AtomicExpr::AO__atomic_fetch_xor: 1351 case AtomicExpr::AO__atomic_fetch_nand: 1352 case AtomicExpr::AO__atomic_and_fetch: 1353 case AtomicExpr::AO__atomic_or_fetch: 1354 case AtomicExpr::AO__atomic_xor_fetch: 1355 case AtomicExpr::AO__atomic_nand_fetch: 1356 Form = Arithmetic; 1357 break; 1358 1359 case AtomicExpr::AO__c11_atomic_exchange: 1360 case AtomicExpr::AO__atomic_exchange_n: 1361 Form = Xchg; 1362 break; 1363 1364 case AtomicExpr::AO__atomic_exchange: 1365 Form = GNUXchg; 1366 break; 1367 1368 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 1369 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 1370 Form = C11CmpXchg; 1371 break; 1372 1373 case AtomicExpr::AO__atomic_compare_exchange: 1374 case AtomicExpr::AO__atomic_compare_exchange_n: 1375 Form = GNUCmpXchg; 1376 break; 1377 } 1378 1379 // Check we have the right number of arguments. 1380 if (TheCall->getNumArgs() < NumArgs[Form]) { 1381 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 1382 << 0 << NumArgs[Form] << TheCall->getNumArgs() 1383 << TheCall->getCallee()->getSourceRange(); 1384 return ExprError(); 1385 } else if (TheCall->getNumArgs() > NumArgs[Form]) { 1386 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(), 1387 diag::err_typecheck_call_too_many_args) 1388 << 0 << NumArgs[Form] << TheCall->getNumArgs() 1389 << TheCall->getCallee()->getSourceRange(); 1390 return ExprError(); 1391 } 1392 1393 // Inspect the first argument of the atomic operation. 1394 Expr *Ptr = TheCall->getArg(0); 1395 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get(); 1396 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 1397 if (!pointerType) { 1398 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1399 << Ptr->getType() << Ptr->getSourceRange(); 1400 return ExprError(); 1401 } 1402 1403 // For a __c11 builtin, this should be a pointer to an _Atomic type. 1404 QualType AtomTy = pointerType->getPointeeType(); // 'A' 1405 QualType ValType = AtomTy; // 'C' 1406 if (IsC11) { 1407 if (!AtomTy->isAtomicType()) { 1408 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 1409 << Ptr->getType() << Ptr->getSourceRange(); 1410 return ExprError(); 1411 } 1412 if (AtomTy.isConstQualified()) { 1413 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 1414 << Ptr->getType() << Ptr->getSourceRange(); 1415 return ExprError(); 1416 } 1417 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 1418 } 1419 1420 // For an arithmetic operation, the implied arithmetic must be well-formed. 1421 if (Form == Arithmetic) { 1422 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 1423 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) { 1424 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1425 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1426 return ExprError(); 1427 } 1428 if (!IsAddSub && !ValType->isIntegerType()) { 1429 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 1430 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1431 return ExprError(); 1432 } 1433 if (IsC11 && ValType->isPointerType() && 1434 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 1435 diag::err_incomplete_type)) { 1436 return ExprError(); 1437 } 1438 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 1439 // For __atomic_*_n operations, the value type must be a scalar integral or 1440 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 1441 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 1442 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 1443 return ExprError(); 1444 } 1445 1446 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 1447 !AtomTy->isScalarType()) { 1448 // For GNU atomics, require a trivially-copyable type. This is not part of 1449 // the GNU atomics specification, but we enforce it for sanity. 1450 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 1451 << Ptr->getType() << Ptr->getSourceRange(); 1452 return ExprError(); 1453 } 1454 1455 // FIXME: For any builtin other than a load, the ValType must not be 1456 // const-qualified. 1457 1458 switch (ValType.getObjCLifetime()) { 1459 case Qualifiers::OCL_None: 1460 case Qualifiers::OCL_ExplicitNone: 1461 // okay 1462 break; 1463 1464 case Qualifiers::OCL_Weak: 1465 case Qualifiers::OCL_Strong: 1466 case Qualifiers::OCL_Autoreleasing: 1467 // FIXME: Can this happen? By this point, ValType should be known 1468 // to be trivially copyable. 1469 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1470 << ValType << Ptr->getSourceRange(); 1471 return ExprError(); 1472 } 1473 1474 QualType ResultType = ValType; 1475 if (Form == Copy || Form == GNUXchg || Form == Init) 1476 ResultType = Context.VoidTy; 1477 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 1478 ResultType = Context.BoolTy; 1479 1480 // The type of a parameter passed 'by value'. In the GNU atomics, such 1481 // arguments are actually passed as pointers. 1482 QualType ByValType = ValType; // 'CP' 1483 if (!IsC11 && !IsN) 1484 ByValType = Ptr->getType(); 1485 1486 // The first argument --- the pointer --- has a fixed type; we 1487 // deduce the types of the rest of the arguments accordingly. Walk 1488 // the remaining arguments, converting them to the deduced value type. 1489 for (unsigned i = 1; i != NumArgs[Form]; ++i) { 1490 QualType Ty; 1491 if (i < NumVals[Form] + 1) { 1492 switch (i) { 1493 case 1: 1494 // The second argument is the non-atomic operand. For arithmetic, this 1495 // is always passed by value, and for a compare_exchange it is always 1496 // passed by address. For the rest, GNU uses by-address and C11 uses 1497 // by-value. 1498 assert(Form != Load); 1499 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 1500 Ty = ValType; 1501 else if (Form == Copy || Form == Xchg) 1502 Ty = ByValType; 1503 else if (Form == Arithmetic) 1504 Ty = Context.getPointerDiffType(); 1505 else 1506 Ty = Context.getPointerType(ValType.getUnqualifiedType()); 1507 break; 1508 case 2: 1509 // The third argument to compare_exchange / GNU exchange is a 1510 // (pointer to a) desired value. 1511 Ty = ByValType; 1512 break; 1513 case 3: 1514 // The fourth argument to GNU compare_exchange is a 'weak' flag. 1515 Ty = Context.BoolTy; 1516 break; 1517 } 1518 } else { 1519 // The order(s) are always converted to int. 1520 Ty = Context.IntTy; 1521 } 1522 1523 InitializedEntity Entity = 1524 InitializedEntity::InitializeParameter(Context, Ty, false); 1525 ExprResult Arg = TheCall->getArg(i); 1526 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1527 if (Arg.isInvalid()) 1528 return true; 1529 TheCall->setArg(i, Arg.get()); 1530 } 1531 1532 // Permute the arguments into a 'consistent' order. 1533 SmallVector<Expr*, 5> SubExprs; 1534 SubExprs.push_back(Ptr); 1535 switch (Form) { 1536 case Init: 1537 // Note, AtomicExpr::getVal1() has a special case for this atomic. 1538 SubExprs.push_back(TheCall->getArg(1)); // Val1 1539 break; 1540 case Load: 1541 SubExprs.push_back(TheCall->getArg(1)); // Order 1542 break; 1543 case Copy: 1544 case Arithmetic: 1545 case Xchg: 1546 SubExprs.push_back(TheCall->getArg(2)); // Order 1547 SubExprs.push_back(TheCall->getArg(1)); // Val1 1548 break; 1549 case GNUXchg: 1550 // Note, AtomicExpr::getVal2() has a special case for this atomic. 1551 SubExprs.push_back(TheCall->getArg(3)); // Order 1552 SubExprs.push_back(TheCall->getArg(1)); // Val1 1553 SubExprs.push_back(TheCall->getArg(2)); // Val2 1554 break; 1555 case C11CmpXchg: 1556 SubExprs.push_back(TheCall->getArg(3)); // Order 1557 SubExprs.push_back(TheCall->getArg(1)); // Val1 1558 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 1559 SubExprs.push_back(TheCall->getArg(2)); // Val2 1560 break; 1561 case GNUCmpXchg: 1562 SubExprs.push_back(TheCall->getArg(4)); // Order 1563 SubExprs.push_back(TheCall->getArg(1)); // Val1 1564 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 1565 SubExprs.push_back(TheCall->getArg(2)); // Val2 1566 SubExprs.push_back(TheCall->getArg(3)); // Weak 1567 break; 1568 } 1569 1570 if (SubExprs.size() >= 2 && Form != Init) { 1571 llvm::APSInt Result(32); 1572 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 1573 !isValidOrderingForOp(Result.getSExtValue(), Op)) 1574 Diag(SubExprs[1]->getLocStart(), 1575 diag::warn_atomic_op_has_invalid_memory_order) 1576 << SubExprs[1]->getSourceRange(); 1577 } 1578 1579 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 1580 SubExprs, ResultType, Op, 1581 TheCall->getRParenLoc()); 1582 1583 if ((Op == AtomicExpr::AO__c11_atomic_load || 1584 (Op == AtomicExpr::AO__c11_atomic_store)) && 1585 Context.AtomicUsesUnsupportedLibcall(AE)) 1586 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) << 1587 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1); 1588 1589 return AE; 1590 } 1591 1592 1593 /// checkBuiltinArgument - Given a call to a builtin function, perform 1594 /// normal type-checking on the given argument, updating the call in 1595 /// place. This is useful when a builtin function requires custom 1596 /// type-checking for some of its arguments but not necessarily all of 1597 /// them. 1598 /// 1599 /// Returns true on error. 1600 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 1601 FunctionDecl *Fn = E->getDirectCallee(); 1602 assert(Fn && "builtin call without direct callee!"); 1603 1604 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 1605 InitializedEntity Entity = 1606 InitializedEntity::InitializeParameter(S.Context, Param); 1607 1608 ExprResult Arg = E->getArg(0); 1609 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 1610 if (Arg.isInvalid()) 1611 return true; 1612 1613 E->setArg(ArgIndex, Arg.get()); 1614 return false; 1615 } 1616 1617 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 1618 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 1619 /// type of its first argument. The main ActOnCallExpr routines have already 1620 /// promoted the types of arguments because all of these calls are prototyped as 1621 /// void(...). 1622 /// 1623 /// This function goes through and does final semantic checking for these 1624 /// builtins, 1625 ExprResult 1626 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 1627 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 1628 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1629 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 1630 1631 // Ensure that we have at least one argument to do type inference from. 1632 if (TheCall->getNumArgs() < 1) { 1633 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1634 << 0 << 1 << TheCall->getNumArgs() 1635 << TheCall->getCallee()->getSourceRange(); 1636 return ExprError(); 1637 } 1638 1639 // Inspect the first argument of the atomic builtin. This should always be 1640 // a pointer type, whose element is an integral scalar or pointer type. 1641 // Because it is a pointer type, we don't have to worry about any implicit 1642 // casts here. 1643 // FIXME: We don't allow floating point scalars as input. 1644 Expr *FirstArg = TheCall->getArg(0); 1645 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 1646 if (FirstArgResult.isInvalid()) 1647 return ExprError(); 1648 FirstArg = FirstArgResult.get(); 1649 TheCall->setArg(0, FirstArg); 1650 1651 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 1652 if (!pointerType) { 1653 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1654 << FirstArg->getType() << FirstArg->getSourceRange(); 1655 return ExprError(); 1656 } 1657 1658 QualType ValType = pointerType->getPointeeType(); 1659 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1660 !ValType->isBlockPointerType()) { 1661 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 1662 << FirstArg->getType() << FirstArg->getSourceRange(); 1663 return ExprError(); 1664 } 1665 1666 switch (ValType.getObjCLifetime()) { 1667 case Qualifiers::OCL_None: 1668 case Qualifiers::OCL_ExplicitNone: 1669 // okay 1670 break; 1671 1672 case Qualifiers::OCL_Weak: 1673 case Qualifiers::OCL_Strong: 1674 case Qualifiers::OCL_Autoreleasing: 1675 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1676 << ValType << FirstArg->getSourceRange(); 1677 return ExprError(); 1678 } 1679 1680 // Strip any qualifiers off ValType. 1681 ValType = ValType.getUnqualifiedType(); 1682 1683 // The majority of builtins return a value, but a few have special return 1684 // types, so allow them to override appropriately below. 1685 QualType ResultType = ValType; 1686 1687 // We need to figure out which concrete builtin this maps onto. For example, 1688 // __sync_fetch_and_add with a 2 byte object turns into 1689 // __sync_fetch_and_add_2. 1690 #define BUILTIN_ROW(x) \ 1691 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 1692 Builtin::BI##x##_8, Builtin::BI##x##_16 } 1693 1694 static const unsigned BuiltinIndices[][5] = { 1695 BUILTIN_ROW(__sync_fetch_and_add), 1696 BUILTIN_ROW(__sync_fetch_and_sub), 1697 BUILTIN_ROW(__sync_fetch_and_or), 1698 BUILTIN_ROW(__sync_fetch_and_and), 1699 BUILTIN_ROW(__sync_fetch_and_xor), 1700 BUILTIN_ROW(__sync_fetch_and_nand), 1701 1702 BUILTIN_ROW(__sync_add_and_fetch), 1703 BUILTIN_ROW(__sync_sub_and_fetch), 1704 BUILTIN_ROW(__sync_and_and_fetch), 1705 BUILTIN_ROW(__sync_or_and_fetch), 1706 BUILTIN_ROW(__sync_xor_and_fetch), 1707 BUILTIN_ROW(__sync_nand_and_fetch), 1708 1709 BUILTIN_ROW(__sync_val_compare_and_swap), 1710 BUILTIN_ROW(__sync_bool_compare_and_swap), 1711 BUILTIN_ROW(__sync_lock_test_and_set), 1712 BUILTIN_ROW(__sync_lock_release), 1713 BUILTIN_ROW(__sync_swap) 1714 }; 1715 #undef BUILTIN_ROW 1716 1717 // Determine the index of the size. 1718 unsigned SizeIndex; 1719 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 1720 case 1: SizeIndex = 0; break; 1721 case 2: SizeIndex = 1; break; 1722 case 4: SizeIndex = 2; break; 1723 case 8: SizeIndex = 3; break; 1724 case 16: SizeIndex = 4; break; 1725 default: 1726 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 1727 << FirstArg->getType() << FirstArg->getSourceRange(); 1728 return ExprError(); 1729 } 1730 1731 // Each of these builtins has one pointer argument, followed by some number of 1732 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 1733 // that we ignore. Find out which row of BuiltinIndices to read from as well 1734 // as the number of fixed args. 1735 unsigned BuiltinID = FDecl->getBuiltinID(); 1736 unsigned BuiltinIndex, NumFixed = 1; 1737 bool WarnAboutSemanticsChange = false; 1738 switch (BuiltinID) { 1739 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 1740 case Builtin::BI__sync_fetch_and_add: 1741 case Builtin::BI__sync_fetch_and_add_1: 1742 case Builtin::BI__sync_fetch_and_add_2: 1743 case Builtin::BI__sync_fetch_and_add_4: 1744 case Builtin::BI__sync_fetch_and_add_8: 1745 case Builtin::BI__sync_fetch_and_add_16: 1746 BuiltinIndex = 0; 1747 break; 1748 1749 case Builtin::BI__sync_fetch_and_sub: 1750 case Builtin::BI__sync_fetch_and_sub_1: 1751 case Builtin::BI__sync_fetch_and_sub_2: 1752 case Builtin::BI__sync_fetch_and_sub_4: 1753 case Builtin::BI__sync_fetch_and_sub_8: 1754 case Builtin::BI__sync_fetch_and_sub_16: 1755 BuiltinIndex = 1; 1756 break; 1757 1758 case Builtin::BI__sync_fetch_and_or: 1759 case Builtin::BI__sync_fetch_and_or_1: 1760 case Builtin::BI__sync_fetch_and_or_2: 1761 case Builtin::BI__sync_fetch_and_or_4: 1762 case Builtin::BI__sync_fetch_and_or_8: 1763 case Builtin::BI__sync_fetch_and_or_16: 1764 BuiltinIndex = 2; 1765 break; 1766 1767 case Builtin::BI__sync_fetch_and_and: 1768 case Builtin::BI__sync_fetch_and_and_1: 1769 case Builtin::BI__sync_fetch_and_and_2: 1770 case Builtin::BI__sync_fetch_and_and_4: 1771 case Builtin::BI__sync_fetch_and_and_8: 1772 case Builtin::BI__sync_fetch_and_and_16: 1773 BuiltinIndex = 3; 1774 break; 1775 1776 case Builtin::BI__sync_fetch_and_xor: 1777 case Builtin::BI__sync_fetch_and_xor_1: 1778 case Builtin::BI__sync_fetch_and_xor_2: 1779 case Builtin::BI__sync_fetch_and_xor_4: 1780 case Builtin::BI__sync_fetch_and_xor_8: 1781 case Builtin::BI__sync_fetch_and_xor_16: 1782 BuiltinIndex = 4; 1783 break; 1784 1785 case Builtin::BI__sync_fetch_and_nand: 1786 case Builtin::BI__sync_fetch_and_nand_1: 1787 case Builtin::BI__sync_fetch_and_nand_2: 1788 case Builtin::BI__sync_fetch_and_nand_4: 1789 case Builtin::BI__sync_fetch_and_nand_8: 1790 case Builtin::BI__sync_fetch_and_nand_16: 1791 BuiltinIndex = 5; 1792 WarnAboutSemanticsChange = true; 1793 break; 1794 1795 case Builtin::BI__sync_add_and_fetch: 1796 case Builtin::BI__sync_add_and_fetch_1: 1797 case Builtin::BI__sync_add_and_fetch_2: 1798 case Builtin::BI__sync_add_and_fetch_4: 1799 case Builtin::BI__sync_add_and_fetch_8: 1800 case Builtin::BI__sync_add_and_fetch_16: 1801 BuiltinIndex = 6; 1802 break; 1803 1804 case Builtin::BI__sync_sub_and_fetch: 1805 case Builtin::BI__sync_sub_and_fetch_1: 1806 case Builtin::BI__sync_sub_and_fetch_2: 1807 case Builtin::BI__sync_sub_and_fetch_4: 1808 case Builtin::BI__sync_sub_and_fetch_8: 1809 case Builtin::BI__sync_sub_and_fetch_16: 1810 BuiltinIndex = 7; 1811 break; 1812 1813 case Builtin::BI__sync_and_and_fetch: 1814 case Builtin::BI__sync_and_and_fetch_1: 1815 case Builtin::BI__sync_and_and_fetch_2: 1816 case Builtin::BI__sync_and_and_fetch_4: 1817 case Builtin::BI__sync_and_and_fetch_8: 1818 case Builtin::BI__sync_and_and_fetch_16: 1819 BuiltinIndex = 8; 1820 break; 1821 1822 case Builtin::BI__sync_or_and_fetch: 1823 case Builtin::BI__sync_or_and_fetch_1: 1824 case Builtin::BI__sync_or_and_fetch_2: 1825 case Builtin::BI__sync_or_and_fetch_4: 1826 case Builtin::BI__sync_or_and_fetch_8: 1827 case Builtin::BI__sync_or_and_fetch_16: 1828 BuiltinIndex = 9; 1829 break; 1830 1831 case Builtin::BI__sync_xor_and_fetch: 1832 case Builtin::BI__sync_xor_and_fetch_1: 1833 case Builtin::BI__sync_xor_and_fetch_2: 1834 case Builtin::BI__sync_xor_and_fetch_4: 1835 case Builtin::BI__sync_xor_and_fetch_8: 1836 case Builtin::BI__sync_xor_and_fetch_16: 1837 BuiltinIndex = 10; 1838 break; 1839 1840 case Builtin::BI__sync_nand_and_fetch: 1841 case Builtin::BI__sync_nand_and_fetch_1: 1842 case Builtin::BI__sync_nand_and_fetch_2: 1843 case Builtin::BI__sync_nand_and_fetch_4: 1844 case Builtin::BI__sync_nand_and_fetch_8: 1845 case Builtin::BI__sync_nand_and_fetch_16: 1846 BuiltinIndex = 11; 1847 WarnAboutSemanticsChange = true; 1848 break; 1849 1850 case Builtin::BI__sync_val_compare_and_swap: 1851 case Builtin::BI__sync_val_compare_and_swap_1: 1852 case Builtin::BI__sync_val_compare_and_swap_2: 1853 case Builtin::BI__sync_val_compare_and_swap_4: 1854 case Builtin::BI__sync_val_compare_and_swap_8: 1855 case Builtin::BI__sync_val_compare_and_swap_16: 1856 BuiltinIndex = 12; 1857 NumFixed = 2; 1858 break; 1859 1860 case Builtin::BI__sync_bool_compare_and_swap: 1861 case Builtin::BI__sync_bool_compare_and_swap_1: 1862 case Builtin::BI__sync_bool_compare_and_swap_2: 1863 case Builtin::BI__sync_bool_compare_and_swap_4: 1864 case Builtin::BI__sync_bool_compare_and_swap_8: 1865 case Builtin::BI__sync_bool_compare_and_swap_16: 1866 BuiltinIndex = 13; 1867 NumFixed = 2; 1868 ResultType = Context.BoolTy; 1869 break; 1870 1871 case Builtin::BI__sync_lock_test_and_set: 1872 case Builtin::BI__sync_lock_test_and_set_1: 1873 case Builtin::BI__sync_lock_test_and_set_2: 1874 case Builtin::BI__sync_lock_test_and_set_4: 1875 case Builtin::BI__sync_lock_test_and_set_8: 1876 case Builtin::BI__sync_lock_test_and_set_16: 1877 BuiltinIndex = 14; 1878 break; 1879 1880 case Builtin::BI__sync_lock_release: 1881 case Builtin::BI__sync_lock_release_1: 1882 case Builtin::BI__sync_lock_release_2: 1883 case Builtin::BI__sync_lock_release_4: 1884 case Builtin::BI__sync_lock_release_8: 1885 case Builtin::BI__sync_lock_release_16: 1886 BuiltinIndex = 15; 1887 NumFixed = 0; 1888 ResultType = Context.VoidTy; 1889 break; 1890 1891 case Builtin::BI__sync_swap: 1892 case Builtin::BI__sync_swap_1: 1893 case Builtin::BI__sync_swap_2: 1894 case Builtin::BI__sync_swap_4: 1895 case Builtin::BI__sync_swap_8: 1896 case Builtin::BI__sync_swap_16: 1897 BuiltinIndex = 16; 1898 break; 1899 } 1900 1901 // Now that we know how many fixed arguments we expect, first check that we 1902 // have at least that many. 1903 if (TheCall->getNumArgs() < 1+NumFixed) { 1904 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 1905 << 0 << 1+NumFixed << TheCall->getNumArgs() 1906 << TheCall->getCallee()->getSourceRange(); 1907 return ExprError(); 1908 } 1909 1910 if (WarnAboutSemanticsChange) { 1911 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 1912 << TheCall->getCallee()->getSourceRange(); 1913 } 1914 1915 // Get the decl for the concrete builtin from this, we can tell what the 1916 // concrete integer type we should convert to is. 1917 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 1918 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID); 1919 FunctionDecl *NewBuiltinDecl; 1920 if (NewBuiltinID == BuiltinID) 1921 NewBuiltinDecl = FDecl; 1922 else { 1923 // Perform builtin lookup to avoid redeclaring it. 1924 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 1925 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 1926 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 1927 assert(Res.getFoundDecl()); 1928 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 1929 if (!NewBuiltinDecl) 1930 return ExprError(); 1931 } 1932 1933 // The first argument --- the pointer --- has a fixed type; we 1934 // deduce the types of the rest of the arguments accordingly. Walk 1935 // the remaining arguments, converting them to the deduced value type. 1936 for (unsigned i = 0; i != NumFixed; ++i) { 1937 ExprResult Arg = TheCall->getArg(i+1); 1938 1939 // GCC does an implicit conversion to the pointer or integer ValType. This 1940 // can fail in some cases (1i -> int**), check for this error case now. 1941 // Initialize the argument. 1942 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1943 ValType, /*consume*/ false); 1944 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 1945 if (Arg.isInvalid()) 1946 return ExprError(); 1947 1948 // Okay, we have something that *can* be converted to the right type. Check 1949 // to see if there is a potentially weird extension going on here. This can 1950 // happen when you do an atomic operation on something like an char* and 1951 // pass in 42. The 42 gets converted to char. This is even more strange 1952 // for things like 45.123 -> char, etc. 1953 // FIXME: Do this check. 1954 TheCall->setArg(i+1, Arg.get()); 1955 } 1956 1957 ASTContext& Context = this->getASTContext(); 1958 1959 // Create a new DeclRefExpr to refer to the new decl. 1960 DeclRefExpr* NewDRE = DeclRefExpr::Create( 1961 Context, 1962 DRE->getQualifierLoc(), 1963 SourceLocation(), 1964 NewBuiltinDecl, 1965 /*enclosing*/ false, 1966 DRE->getLocation(), 1967 Context.BuiltinFnTy, 1968 DRE->getValueKind()); 1969 1970 // Set the callee in the CallExpr. 1971 // FIXME: This loses syntactic information. 1972 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 1973 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 1974 CK_BuiltinFnToFnPtr); 1975 TheCall->setCallee(PromotedCall.get()); 1976 1977 // Change the result type of the call to match the original value type. This 1978 // is arbitrary, but the codegen for these builtins ins design to handle it 1979 // gracefully. 1980 TheCall->setType(ResultType); 1981 1982 return TheCallResult; 1983 } 1984 1985 /// CheckObjCString - Checks that the argument to the builtin 1986 /// CFString constructor is correct 1987 /// Note: It might also make sense to do the UTF-16 conversion here (would 1988 /// simplify the backend). 1989 bool Sema::CheckObjCString(Expr *Arg) { 1990 Arg = Arg->IgnoreParenCasts(); 1991 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 1992 1993 if (!Literal || !Literal->isAscii()) { 1994 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 1995 << Arg->getSourceRange(); 1996 return true; 1997 } 1998 1999 if (Literal->containsNonAsciiOrNull()) { 2000 StringRef String = Literal->getString(); 2001 unsigned NumBytes = String.size(); 2002 SmallVector<UTF16, 128> ToBuf(NumBytes); 2003 const UTF8 *FromPtr = (const UTF8 *)String.data(); 2004 UTF16 *ToPtr = &ToBuf[0]; 2005 2006 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2007 &ToPtr, ToPtr + NumBytes, 2008 strictConversion); 2009 // Check for conversion failure. 2010 if (Result != conversionOK) 2011 Diag(Arg->getLocStart(), 2012 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 2013 } 2014 return false; 2015 } 2016 2017 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. 2018 /// Emit an error and return true on failure, return false on success. 2019 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) { 2020 Expr *Fn = TheCall->getCallee(); 2021 if (TheCall->getNumArgs() > 2) { 2022 Diag(TheCall->getArg(2)->getLocStart(), 2023 diag::err_typecheck_call_too_many_args) 2024 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 2025 << Fn->getSourceRange() 2026 << SourceRange(TheCall->getArg(2)->getLocStart(), 2027 (*(TheCall->arg_end()-1))->getLocEnd()); 2028 return true; 2029 } 2030 2031 if (TheCall->getNumArgs() < 2) { 2032 return Diag(TheCall->getLocEnd(), 2033 diag::err_typecheck_call_too_few_args_at_least) 2034 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 2035 } 2036 2037 // Type-check the first argument normally. 2038 if (checkBuiltinArgument(*this, TheCall, 0)) 2039 return true; 2040 2041 // Determine whether the current function is variadic or not. 2042 BlockScopeInfo *CurBlock = getCurBlock(); 2043 bool isVariadic; 2044 if (CurBlock) 2045 isVariadic = CurBlock->TheDecl->isVariadic(); 2046 else if (FunctionDecl *FD = getCurFunctionDecl()) 2047 isVariadic = FD->isVariadic(); 2048 else 2049 isVariadic = getCurMethodDecl()->isVariadic(); 2050 2051 if (!isVariadic) { 2052 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 2053 return true; 2054 } 2055 2056 // Verify that the second argument to the builtin is the last argument of the 2057 // current function or method. 2058 bool SecondArgIsLastNamedArgument = false; 2059 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 2060 2061 // These are valid if SecondArgIsLastNamedArgument is false after the next 2062 // block. 2063 QualType Type; 2064 SourceLocation ParamLoc; 2065 2066 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 2067 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 2068 // FIXME: This isn't correct for methods (results in bogus warning). 2069 // Get the last formal in the current function. 2070 const ParmVarDecl *LastArg; 2071 if (CurBlock) 2072 LastArg = *(CurBlock->TheDecl->param_end()-1); 2073 else if (FunctionDecl *FD = getCurFunctionDecl()) 2074 LastArg = *(FD->param_end()-1); 2075 else 2076 LastArg = *(getCurMethodDecl()->param_end()-1); 2077 SecondArgIsLastNamedArgument = PV == LastArg; 2078 2079 Type = PV->getType(); 2080 ParamLoc = PV->getLocation(); 2081 } 2082 } 2083 2084 if (!SecondArgIsLastNamedArgument) 2085 Diag(TheCall->getArg(1)->getLocStart(), 2086 diag::warn_second_parameter_of_va_start_not_last_named_argument); 2087 else if (Type->isReferenceType()) { 2088 Diag(Arg->getLocStart(), 2089 diag::warn_va_start_of_reference_type_is_undefined); 2090 Diag(ParamLoc, diag::note_parameter_type) << Type; 2091 } 2092 2093 TheCall->setType(Context.VoidTy); 2094 return false; 2095 } 2096 2097 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) { 2098 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 2099 // const char *named_addr); 2100 2101 Expr *Func = Call->getCallee(); 2102 2103 if (Call->getNumArgs() < 3) 2104 return Diag(Call->getLocEnd(), 2105 diag::err_typecheck_call_too_few_args_at_least) 2106 << 0 /*function call*/ << 3 << Call->getNumArgs(); 2107 2108 // Determine whether the current function is variadic or not. 2109 bool IsVariadic; 2110 if (BlockScopeInfo *CurBlock = getCurBlock()) 2111 IsVariadic = CurBlock->TheDecl->isVariadic(); 2112 else if (FunctionDecl *FD = getCurFunctionDecl()) 2113 IsVariadic = FD->isVariadic(); 2114 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 2115 IsVariadic = MD->isVariadic(); 2116 else 2117 llvm_unreachable("unexpected statement type"); 2118 2119 if (!IsVariadic) { 2120 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function); 2121 return true; 2122 } 2123 2124 // Type-check the first argument normally. 2125 if (checkBuiltinArgument(*this, Call, 0)) 2126 return true; 2127 2128 const struct { 2129 unsigned ArgNo; 2130 QualType Type; 2131 } ArgumentTypes[] = { 2132 { 1, Context.getPointerType(Context.CharTy.withConst()) }, 2133 { 2, Context.getSizeType() }, 2134 }; 2135 2136 for (const auto &AT : ArgumentTypes) { 2137 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens(); 2138 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType()) 2139 continue; 2140 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible) 2141 << Arg->getType() << AT.Type << 1 /* different class */ 2142 << 0 /* qualifier difference */ << 3 /* parameter mismatch */ 2143 << AT.ArgNo + 1 << Arg->getType() << AT.Type; 2144 } 2145 2146 return false; 2147 } 2148 2149 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 2150 /// friends. This is declared to take (...), so we have to check everything. 2151 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 2152 if (TheCall->getNumArgs() < 2) 2153 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2154 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 2155 if (TheCall->getNumArgs() > 2) 2156 return Diag(TheCall->getArg(2)->getLocStart(), 2157 diag::err_typecheck_call_too_many_args) 2158 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 2159 << SourceRange(TheCall->getArg(2)->getLocStart(), 2160 (*(TheCall->arg_end()-1))->getLocEnd()); 2161 2162 ExprResult OrigArg0 = TheCall->getArg(0); 2163 ExprResult OrigArg1 = TheCall->getArg(1); 2164 2165 // Do standard promotions between the two arguments, returning their common 2166 // type. 2167 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 2168 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 2169 return true; 2170 2171 // Make sure any conversions are pushed back into the call; this is 2172 // type safe since unordered compare builtins are declared as "_Bool 2173 // foo(...)". 2174 TheCall->setArg(0, OrigArg0.get()); 2175 TheCall->setArg(1, OrigArg1.get()); 2176 2177 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 2178 return false; 2179 2180 // If the common type isn't a real floating type, then the arguments were 2181 // invalid for this operation. 2182 if (Res.isNull() || !Res->isRealFloatingType()) 2183 return Diag(OrigArg0.get()->getLocStart(), 2184 diag::err_typecheck_call_invalid_ordered_compare) 2185 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 2186 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 2187 2188 return false; 2189 } 2190 2191 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 2192 /// __builtin_isnan and friends. This is declared to take (...), so we have 2193 /// to check everything. We expect the last argument to be a floating point 2194 /// value. 2195 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 2196 if (TheCall->getNumArgs() < NumArgs) 2197 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 2198 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 2199 if (TheCall->getNumArgs() > NumArgs) 2200 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 2201 diag::err_typecheck_call_too_many_args) 2202 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 2203 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 2204 (*(TheCall->arg_end()-1))->getLocEnd()); 2205 2206 Expr *OrigArg = TheCall->getArg(NumArgs-1); 2207 2208 if (OrigArg->isTypeDependent()) 2209 return false; 2210 2211 // This operation requires a non-_Complex floating-point number. 2212 if (!OrigArg->getType()->isRealFloatingType()) 2213 return Diag(OrigArg->getLocStart(), 2214 diag::err_typecheck_call_invalid_unary_fp) 2215 << OrigArg->getType() << OrigArg->getSourceRange(); 2216 2217 // If this is an implicit conversion from float -> double, remove it. 2218 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 2219 Expr *CastArg = Cast->getSubExpr(); 2220 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 2221 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) && 2222 "promotion from float to double is the only expected cast here"); 2223 Cast->setSubExpr(nullptr); 2224 TheCall->setArg(NumArgs-1, CastArg); 2225 } 2226 } 2227 2228 return false; 2229 } 2230 2231 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 2232 // This is declared to take (...), so we have to check everything. 2233 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 2234 if (TheCall->getNumArgs() < 2) 2235 return ExprError(Diag(TheCall->getLocEnd(), 2236 diag::err_typecheck_call_too_few_args_at_least) 2237 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 2238 << TheCall->getSourceRange()); 2239 2240 // Determine which of the following types of shufflevector we're checking: 2241 // 1) unary, vector mask: (lhs, mask) 2242 // 2) binary, vector mask: (lhs, rhs, mask) 2243 // 3) binary, scalar mask: (lhs, rhs, index, ..., index) 2244 QualType resType = TheCall->getArg(0)->getType(); 2245 unsigned numElements = 0; 2246 2247 if (!TheCall->getArg(0)->isTypeDependent() && 2248 !TheCall->getArg(1)->isTypeDependent()) { 2249 QualType LHSType = TheCall->getArg(0)->getType(); 2250 QualType RHSType = TheCall->getArg(1)->getType(); 2251 2252 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 2253 return ExprError(Diag(TheCall->getLocStart(), 2254 diag::err_shufflevector_non_vector) 2255 << SourceRange(TheCall->getArg(0)->getLocStart(), 2256 TheCall->getArg(1)->getLocEnd())); 2257 2258 numElements = LHSType->getAs<VectorType>()->getNumElements(); 2259 unsigned numResElements = TheCall->getNumArgs() - 2; 2260 2261 // Check to see if we have a call with 2 vector arguments, the unary shuffle 2262 // with mask. If so, verify that RHS is an integer vector type with the 2263 // same number of elts as lhs. 2264 if (TheCall->getNumArgs() == 2) { 2265 if (!RHSType->hasIntegerRepresentation() || 2266 RHSType->getAs<VectorType>()->getNumElements() != numElements) 2267 return ExprError(Diag(TheCall->getLocStart(), 2268 diag::err_shufflevector_incompatible_vector) 2269 << SourceRange(TheCall->getArg(1)->getLocStart(), 2270 TheCall->getArg(1)->getLocEnd())); 2271 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 2272 return ExprError(Diag(TheCall->getLocStart(), 2273 diag::err_shufflevector_incompatible_vector) 2274 << SourceRange(TheCall->getArg(0)->getLocStart(), 2275 TheCall->getArg(1)->getLocEnd())); 2276 } else if (numElements != numResElements) { 2277 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 2278 resType = Context.getVectorType(eltType, numResElements, 2279 VectorType::GenericVector); 2280 } 2281 } 2282 2283 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 2284 if (TheCall->getArg(i)->isTypeDependent() || 2285 TheCall->getArg(i)->isValueDependent()) 2286 continue; 2287 2288 llvm::APSInt Result(32); 2289 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 2290 return ExprError(Diag(TheCall->getLocStart(), 2291 diag::err_shufflevector_nonconstant_argument) 2292 << TheCall->getArg(i)->getSourceRange()); 2293 2294 // Allow -1 which will be translated to undef in the IR. 2295 if (Result.isSigned() && Result.isAllOnesValue()) 2296 continue; 2297 2298 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 2299 return ExprError(Diag(TheCall->getLocStart(), 2300 diag::err_shufflevector_argument_too_large) 2301 << TheCall->getArg(i)->getSourceRange()); 2302 } 2303 2304 SmallVector<Expr*, 32> exprs; 2305 2306 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 2307 exprs.push_back(TheCall->getArg(i)); 2308 TheCall->setArg(i, nullptr); 2309 } 2310 2311 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 2312 TheCall->getCallee()->getLocStart(), 2313 TheCall->getRParenLoc()); 2314 } 2315 2316 /// SemaConvertVectorExpr - Handle __builtin_convertvector 2317 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 2318 SourceLocation BuiltinLoc, 2319 SourceLocation RParenLoc) { 2320 ExprValueKind VK = VK_RValue; 2321 ExprObjectKind OK = OK_Ordinary; 2322 QualType DstTy = TInfo->getType(); 2323 QualType SrcTy = E->getType(); 2324 2325 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 2326 return ExprError(Diag(BuiltinLoc, 2327 diag::err_convertvector_non_vector) 2328 << E->getSourceRange()); 2329 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 2330 return ExprError(Diag(BuiltinLoc, 2331 diag::err_convertvector_non_vector_type)); 2332 2333 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 2334 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 2335 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 2336 if (SrcElts != DstElts) 2337 return ExprError(Diag(BuiltinLoc, 2338 diag::err_convertvector_incompatible_vector) 2339 << E->getSourceRange()); 2340 } 2341 2342 return new (Context) 2343 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 2344 } 2345 2346 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 2347 // This is declared to take (const void*, ...) and can take two 2348 // optional constant int args. 2349 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 2350 unsigned NumArgs = TheCall->getNumArgs(); 2351 2352 if (NumArgs > 3) 2353 return Diag(TheCall->getLocEnd(), 2354 diag::err_typecheck_call_too_many_args_at_most) 2355 << 0 /*function call*/ << 3 << NumArgs 2356 << TheCall->getSourceRange(); 2357 2358 // Argument 0 is checked for us and the remaining arguments must be 2359 // constant integers. 2360 for (unsigned i = 1; i != NumArgs; ++i) 2361 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 2362 return true; 2363 2364 return false; 2365 } 2366 2367 /// SemaBuiltinAssume - Handle __assume (MS Extension). 2368 // __assume does not evaluate its arguments, and should warn if its argument 2369 // has side effects. 2370 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 2371 Expr *Arg = TheCall->getArg(0); 2372 if (Arg->isInstantiationDependent()) return false; 2373 2374 if (Arg->HasSideEffects(Context)) 2375 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 2376 << Arg->getSourceRange() 2377 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 2378 2379 return false; 2380 } 2381 2382 /// Handle __builtin_assume_aligned. This is declared 2383 /// as (const void*, size_t, ...) and can take one optional constant int arg. 2384 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 2385 unsigned NumArgs = TheCall->getNumArgs(); 2386 2387 if (NumArgs > 3) 2388 return Diag(TheCall->getLocEnd(), 2389 diag::err_typecheck_call_too_many_args_at_most) 2390 << 0 /*function call*/ << 3 << NumArgs 2391 << TheCall->getSourceRange(); 2392 2393 // The alignment must be a constant integer. 2394 Expr *Arg = TheCall->getArg(1); 2395 2396 // We can't check the value of a dependent argument. 2397 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 2398 llvm::APSInt Result; 2399 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 2400 return true; 2401 2402 if (!Result.isPowerOf2()) 2403 return Diag(TheCall->getLocStart(), 2404 diag::err_alignment_not_power_of_two) 2405 << Arg->getSourceRange(); 2406 } 2407 2408 if (NumArgs > 2) { 2409 ExprResult Arg(TheCall->getArg(2)); 2410 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 2411 Context.getSizeType(), false); 2412 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 2413 if (Arg.isInvalid()) return true; 2414 TheCall->setArg(2, Arg.get()); 2415 } 2416 2417 return false; 2418 } 2419 2420 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 2421 /// TheCall is a constant expression. 2422 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 2423 llvm::APSInt &Result) { 2424 Expr *Arg = TheCall->getArg(ArgNum); 2425 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2426 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 2427 2428 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 2429 2430 if (!Arg->isIntegerConstantExpr(Result, Context)) 2431 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 2432 << FDecl->getDeclName() << Arg->getSourceRange(); 2433 2434 return false; 2435 } 2436 2437 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 2438 /// TheCall is a constant expression in the range [Low, High]. 2439 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 2440 int Low, int High) { 2441 llvm::APSInt Result; 2442 2443 // We can't check the value of a dependent argument. 2444 Expr *Arg = TheCall->getArg(ArgNum); 2445 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2446 return false; 2447 2448 // Check constant-ness first. 2449 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2450 return true; 2451 2452 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 2453 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 2454 << Low << High << Arg->getSourceRange(); 2455 2456 return false; 2457 } 2458 2459 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 2460 /// This checks that val is a constant 1. 2461 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 2462 Expr *Arg = TheCall->getArg(1); 2463 llvm::APSInt Result; 2464 2465 // TODO: This is less than ideal. Overload this to take a value. 2466 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 2467 return true; 2468 2469 if (Result != 1) 2470 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 2471 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 2472 2473 return false; 2474 } 2475 2476 namespace { 2477 enum StringLiteralCheckType { 2478 SLCT_NotALiteral, 2479 SLCT_UncheckedLiteral, 2480 SLCT_CheckedLiteral 2481 }; 2482 } 2483 2484 // Determine if an expression is a string literal or constant string. 2485 // If this function returns false on the arguments to a function expecting a 2486 // format string, we will usually need to emit a warning. 2487 // True string literals are then checked by CheckFormatString. 2488 static StringLiteralCheckType 2489 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 2490 bool HasVAListArg, unsigned format_idx, 2491 unsigned firstDataArg, Sema::FormatStringType Type, 2492 Sema::VariadicCallType CallType, bool InFunctionCall, 2493 llvm::SmallBitVector &CheckedVarArgs) { 2494 tryAgain: 2495 if (E->isTypeDependent() || E->isValueDependent()) 2496 return SLCT_NotALiteral; 2497 2498 E = E->IgnoreParenCasts(); 2499 2500 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 2501 // Technically -Wformat-nonliteral does not warn about this case. 2502 // The behavior of printf and friends in this case is implementation 2503 // dependent. Ideally if the format string cannot be null then 2504 // it should have a 'nonnull' attribute in the function prototype. 2505 return SLCT_UncheckedLiteral; 2506 2507 switch (E->getStmtClass()) { 2508 case Stmt::BinaryConditionalOperatorClass: 2509 case Stmt::ConditionalOperatorClass: { 2510 // The expression is a literal if both sub-expressions were, and it was 2511 // completely checked only if both sub-expressions were checked. 2512 const AbstractConditionalOperator *C = 2513 cast<AbstractConditionalOperator>(E); 2514 StringLiteralCheckType Left = 2515 checkFormatStringExpr(S, C->getTrueExpr(), Args, 2516 HasVAListArg, format_idx, firstDataArg, 2517 Type, CallType, InFunctionCall, CheckedVarArgs); 2518 if (Left == SLCT_NotALiteral) 2519 return SLCT_NotALiteral; 2520 StringLiteralCheckType Right = 2521 checkFormatStringExpr(S, C->getFalseExpr(), Args, 2522 HasVAListArg, format_idx, firstDataArg, 2523 Type, CallType, InFunctionCall, CheckedVarArgs); 2524 return Left < Right ? Left : Right; 2525 } 2526 2527 case Stmt::ImplicitCastExprClass: { 2528 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 2529 goto tryAgain; 2530 } 2531 2532 case Stmt::OpaqueValueExprClass: 2533 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 2534 E = src; 2535 goto tryAgain; 2536 } 2537 return SLCT_NotALiteral; 2538 2539 case Stmt::PredefinedExprClass: 2540 // While __func__, etc., are technically not string literals, they 2541 // cannot contain format specifiers and thus are not a security 2542 // liability. 2543 return SLCT_UncheckedLiteral; 2544 2545 case Stmt::DeclRefExprClass: { 2546 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 2547 2548 // As an exception, do not flag errors for variables binding to 2549 // const string literals. 2550 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 2551 bool isConstant = false; 2552 QualType T = DR->getType(); 2553 2554 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 2555 isConstant = AT->getElementType().isConstant(S.Context); 2556 } else if (const PointerType *PT = T->getAs<PointerType>()) { 2557 isConstant = T.isConstant(S.Context) && 2558 PT->getPointeeType().isConstant(S.Context); 2559 } else if (T->isObjCObjectPointerType()) { 2560 // In ObjC, there is usually no "const ObjectPointer" type, 2561 // so don't check if the pointee type is constant. 2562 isConstant = T.isConstant(S.Context); 2563 } 2564 2565 if (isConstant) { 2566 if (const Expr *Init = VD->getAnyInitializer()) { 2567 // Look through initializers like const char c[] = { "foo" } 2568 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2569 if (InitList->isStringLiteralInit()) 2570 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 2571 } 2572 return checkFormatStringExpr(S, Init, Args, 2573 HasVAListArg, format_idx, 2574 firstDataArg, Type, CallType, 2575 /*InFunctionCall*/false, CheckedVarArgs); 2576 } 2577 } 2578 2579 // For vprintf* functions (i.e., HasVAListArg==true), we add a 2580 // special check to see if the format string is a function parameter 2581 // of the function calling the printf function. If the function 2582 // has an attribute indicating it is a printf-like function, then we 2583 // should suppress warnings concerning non-literals being used in a call 2584 // to a vprintf function. For example: 2585 // 2586 // void 2587 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 2588 // va_list ap; 2589 // va_start(ap, fmt); 2590 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 2591 // ... 2592 // } 2593 if (HasVAListArg) { 2594 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 2595 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 2596 int PVIndex = PV->getFunctionScopeIndex() + 1; 2597 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 2598 // adjust for implicit parameter 2599 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 2600 if (MD->isInstance()) 2601 ++PVIndex; 2602 // We also check if the formats are compatible. 2603 // We can't pass a 'scanf' string to a 'printf' function. 2604 if (PVIndex == PVFormat->getFormatIdx() && 2605 Type == S.GetFormatStringType(PVFormat)) 2606 return SLCT_UncheckedLiteral; 2607 } 2608 } 2609 } 2610 } 2611 } 2612 2613 return SLCT_NotALiteral; 2614 } 2615 2616 case Stmt::CallExprClass: 2617 case Stmt::CXXMemberCallExprClass: { 2618 const CallExpr *CE = cast<CallExpr>(E); 2619 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 2620 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 2621 unsigned ArgIndex = FA->getFormatIdx(); 2622 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 2623 if (MD->isInstance()) 2624 --ArgIndex; 2625 const Expr *Arg = CE->getArg(ArgIndex - 1); 2626 2627 return checkFormatStringExpr(S, Arg, Args, 2628 HasVAListArg, format_idx, firstDataArg, 2629 Type, CallType, InFunctionCall, 2630 CheckedVarArgs); 2631 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 2632 unsigned BuiltinID = FD->getBuiltinID(); 2633 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 2634 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 2635 const Expr *Arg = CE->getArg(0); 2636 return checkFormatStringExpr(S, Arg, Args, 2637 HasVAListArg, format_idx, 2638 firstDataArg, Type, CallType, 2639 InFunctionCall, CheckedVarArgs); 2640 } 2641 } 2642 } 2643 2644 return SLCT_NotALiteral; 2645 } 2646 case Stmt::ObjCStringLiteralClass: 2647 case Stmt::StringLiteralClass: { 2648 const StringLiteral *StrE = nullptr; 2649 2650 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 2651 StrE = ObjCFExpr->getString(); 2652 else 2653 StrE = cast<StringLiteral>(E); 2654 2655 if (StrE) { 2656 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg, 2657 Type, InFunctionCall, CallType, CheckedVarArgs); 2658 return SLCT_CheckedLiteral; 2659 } 2660 2661 return SLCT_NotALiteral; 2662 } 2663 2664 default: 2665 return SLCT_NotALiteral; 2666 } 2667 } 2668 2669 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 2670 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 2671 .Case("scanf", FST_Scanf) 2672 .Cases("printf", "printf0", FST_Printf) 2673 .Cases("NSString", "CFString", FST_NSString) 2674 .Case("strftime", FST_Strftime) 2675 .Case("strfmon", FST_Strfmon) 2676 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 2677 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 2678 .Case("os_trace", FST_OSTrace) 2679 .Default(FST_Unknown); 2680 } 2681 2682 /// CheckFormatArguments - Check calls to printf and scanf (and similar 2683 /// functions) for correct use of format strings. 2684 /// Returns true if a format string has been fully checked. 2685 bool Sema::CheckFormatArguments(const FormatAttr *Format, 2686 ArrayRef<const Expr *> Args, 2687 bool IsCXXMember, 2688 VariadicCallType CallType, 2689 SourceLocation Loc, SourceRange Range, 2690 llvm::SmallBitVector &CheckedVarArgs) { 2691 FormatStringInfo FSI; 2692 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 2693 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 2694 FSI.FirstDataArg, GetFormatStringType(Format), 2695 CallType, Loc, Range, CheckedVarArgs); 2696 return false; 2697 } 2698 2699 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 2700 bool HasVAListArg, unsigned format_idx, 2701 unsigned firstDataArg, FormatStringType Type, 2702 VariadicCallType CallType, 2703 SourceLocation Loc, SourceRange Range, 2704 llvm::SmallBitVector &CheckedVarArgs) { 2705 // CHECK: printf/scanf-like function is called with no format string. 2706 if (format_idx >= Args.size()) { 2707 Diag(Loc, diag::warn_missing_format_string) << Range; 2708 return false; 2709 } 2710 2711 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 2712 2713 // CHECK: format string is not a string literal. 2714 // 2715 // Dynamically generated format strings are difficult to 2716 // automatically vet at compile time. Requiring that format strings 2717 // are string literals: (1) permits the checking of format strings by 2718 // the compiler and thereby (2) can practically remove the source of 2719 // many format string exploits. 2720 2721 // Format string can be either ObjC string (e.g. @"%d") or 2722 // C string (e.g. "%d") 2723 // ObjC string uses the same format specifiers as C string, so we can use 2724 // the same format string checking logic for both ObjC and C strings. 2725 StringLiteralCheckType CT = 2726 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 2727 format_idx, firstDataArg, Type, CallType, 2728 /*IsFunctionCall*/true, CheckedVarArgs); 2729 if (CT != SLCT_NotALiteral) 2730 // Literal format string found, check done! 2731 return CT == SLCT_CheckedLiteral; 2732 2733 // Strftime is particular as it always uses a single 'time' argument, 2734 // so it is safe to pass a non-literal string. 2735 if (Type == FST_Strftime) 2736 return false; 2737 2738 // Do not emit diag when the string param is a macro expansion and the 2739 // format is either NSString or CFString. This is a hack to prevent 2740 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 2741 // which are usually used in place of NS and CF string literals. 2742 if (Type == FST_NSString && 2743 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart())) 2744 return false; 2745 2746 // If there are no arguments specified, warn with -Wformat-security, otherwise 2747 // warn only with -Wformat-nonliteral. 2748 if (Args.size() == firstDataArg) 2749 Diag(Args[format_idx]->getLocStart(), 2750 diag::warn_format_nonliteral_noargs) 2751 << OrigFormatExpr->getSourceRange(); 2752 else 2753 Diag(Args[format_idx]->getLocStart(), 2754 diag::warn_format_nonliteral) 2755 << OrigFormatExpr->getSourceRange(); 2756 return false; 2757 } 2758 2759 namespace { 2760 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 2761 protected: 2762 Sema &S; 2763 const StringLiteral *FExpr; 2764 const Expr *OrigFormatExpr; 2765 const unsigned FirstDataArg; 2766 const unsigned NumDataArgs; 2767 const char *Beg; // Start of format string. 2768 const bool HasVAListArg; 2769 ArrayRef<const Expr *> Args; 2770 unsigned FormatIdx; 2771 llvm::SmallBitVector CoveredArgs; 2772 bool usesPositionalArgs; 2773 bool atFirstArg; 2774 bool inFunctionCall; 2775 Sema::VariadicCallType CallType; 2776 llvm::SmallBitVector &CheckedVarArgs; 2777 public: 2778 CheckFormatHandler(Sema &s, const StringLiteral *fexpr, 2779 const Expr *origFormatExpr, unsigned firstDataArg, 2780 unsigned numDataArgs, const char *beg, bool hasVAListArg, 2781 ArrayRef<const Expr *> Args, 2782 unsigned formatIdx, bool inFunctionCall, 2783 Sema::VariadicCallType callType, 2784 llvm::SmallBitVector &CheckedVarArgs) 2785 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), 2786 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), 2787 Beg(beg), HasVAListArg(hasVAListArg), 2788 Args(Args), FormatIdx(formatIdx), 2789 usesPositionalArgs(false), atFirstArg(true), 2790 inFunctionCall(inFunctionCall), CallType(callType), 2791 CheckedVarArgs(CheckedVarArgs) { 2792 CoveredArgs.resize(numDataArgs); 2793 CoveredArgs.reset(); 2794 } 2795 2796 void DoneProcessing(); 2797 2798 void HandleIncompleteSpecifier(const char *startSpecifier, 2799 unsigned specifierLen) override; 2800 2801 void HandleInvalidLengthModifier( 2802 const analyze_format_string::FormatSpecifier &FS, 2803 const analyze_format_string::ConversionSpecifier &CS, 2804 const char *startSpecifier, unsigned specifierLen, 2805 unsigned DiagID); 2806 2807 void HandleNonStandardLengthModifier( 2808 const analyze_format_string::FormatSpecifier &FS, 2809 const char *startSpecifier, unsigned specifierLen); 2810 2811 void HandleNonStandardConversionSpecifier( 2812 const analyze_format_string::ConversionSpecifier &CS, 2813 const char *startSpecifier, unsigned specifierLen); 2814 2815 void HandlePosition(const char *startPos, unsigned posLen) override; 2816 2817 void HandleInvalidPosition(const char *startSpecifier, 2818 unsigned specifierLen, 2819 analyze_format_string::PositionContext p) override; 2820 2821 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 2822 2823 void HandleNullChar(const char *nullCharacter) override; 2824 2825 template <typename Range> 2826 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall, 2827 const Expr *ArgumentExpr, 2828 PartialDiagnostic PDiag, 2829 SourceLocation StringLoc, 2830 bool IsStringLocation, Range StringRange, 2831 ArrayRef<FixItHint> Fixit = None); 2832 2833 protected: 2834 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 2835 const char *startSpec, 2836 unsigned specifierLen, 2837 const char *csStart, unsigned csLen); 2838 2839 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 2840 const char *startSpec, 2841 unsigned specifierLen); 2842 2843 SourceRange getFormatStringRange(); 2844 CharSourceRange getSpecifierRange(const char *startSpecifier, 2845 unsigned specifierLen); 2846 SourceLocation getLocationOfByte(const char *x); 2847 2848 const Expr *getDataArg(unsigned i) const; 2849 2850 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 2851 const analyze_format_string::ConversionSpecifier &CS, 2852 const char *startSpecifier, unsigned specifierLen, 2853 unsigned argIndex); 2854 2855 template <typename Range> 2856 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 2857 bool IsStringLocation, Range StringRange, 2858 ArrayRef<FixItHint> Fixit = None); 2859 }; 2860 } 2861 2862 SourceRange CheckFormatHandler::getFormatStringRange() { 2863 return OrigFormatExpr->getSourceRange(); 2864 } 2865 2866 CharSourceRange CheckFormatHandler:: 2867 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 2868 SourceLocation Start = getLocationOfByte(startSpecifier); 2869 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 2870 2871 // Advance the end SourceLocation by one due to half-open ranges. 2872 End = End.getLocWithOffset(1); 2873 2874 return CharSourceRange::getCharRange(Start, End); 2875 } 2876 2877 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 2878 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 2879 } 2880 2881 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 2882 unsigned specifierLen){ 2883 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 2884 getLocationOfByte(startSpecifier), 2885 /*IsStringLocation*/true, 2886 getSpecifierRange(startSpecifier, specifierLen)); 2887 } 2888 2889 void CheckFormatHandler::HandleInvalidLengthModifier( 2890 const analyze_format_string::FormatSpecifier &FS, 2891 const analyze_format_string::ConversionSpecifier &CS, 2892 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 2893 using namespace analyze_format_string; 2894 2895 const LengthModifier &LM = FS.getLengthModifier(); 2896 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2897 2898 // See if we know how to fix this length modifier. 2899 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2900 if (FixedLM) { 2901 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2902 getLocationOfByte(LM.getStart()), 2903 /*IsStringLocation*/true, 2904 getSpecifierRange(startSpecifier, specifierLen)); 2905 2906 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2907 << FixedLM->toString() 2908 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2909 2910 } else { 2911 FixItHint Hint; 2912 if (DiagID == diag::warn_format_nonsensical_length) 2913 Hint = FixItHint::CreateRemoval(LMRange); 2914 2915 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 2916 getLocationOfByte(LM.getStart()), 2917 /*IsStringLocation*/true, 2918 getSpecifierRange(startSpecifier, specifierLen), 2919 Hint); 2920 } 2921 } 2922 2923 void CheckFormatHandler::HandleNonStandardLengthModifier( 2924 const analyze_format_string::FormatSpecifier &FS, 2925 const char *startSpecifier, unsigned specifierLen) { 2926 using namespace analyze_format_string; 2927 2928 const LengthModifier &LM = FS.getLengthModifier(); 2929 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 2930 2931 // See if we know how to fix this length modifier. 2932 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 2933 if (FixedLM) { 2934 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2935 << LM.toString() << 0, 2936 getLocationOfByte(LM.getStart()), 2937 /*IsStringLocation*/true, 2938 getSpecifierRange(startSpecifier, specifierLen)); 2939 2940 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 2941 << FixedLM->toString() 2942 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 2943 2944 } else { 2945 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2946 << LM.toString() << 0, 2947 getLocationOfByte(LM.getStart()), 2948 /*IsStringLocation*/true, 2949 getSpecifierRange(startSpecifier, specifierLen)); 2950 } 2951 } 2952 2953 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 2954 const analyze_format_string::ConversionSpecifier &CS, 2955 const char *startSpecifier, unsigned specifierLen) { 2956 using namespace analyze_format_string; 2957 2958 // See if we know how to fix this conversion specifier. 2959 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 2960 if (FixedCS) { 2961 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2962 << CS.toString() << /*conversion specifier*/1, 2963 getLocationOfByte(CS.getStart()), 2964 /*IsStringLocation*/true, 2965 getSpecifierRange(startSpecifier, specifierLen)); 2966 2967 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 2968 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 2969 << FixedCS->toString() 2970 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 2971 } else { 2972 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 2973 << CS.toString() << /*conversion specifier*/1, 2974 getLocationOfByte(CS.getStart()), 2975 /*IsStringLocation*/true, 2976 getSpecifierRange(startSpecifier, specifierLen)); 2977 } 2978 } 2979 2980 void CheckFormatHandler::HandlePosition(const char *startPos, 2981 unsigned posLen) { 2982 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 2983 getLocationOfByte(startPos), 2984 /*IsStringLocation*/true, 2985 getSpecifierRange(startPos, posLen)); 2986 } 2987 2988 void 2989 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 2990 analyze_format_string::PositionContext p) { 2991 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 2992 << (unsigned) p, 2993 getLocationOfByte(startPos), /*IsStringLocation*/true, 2994 getSpecifierRange(startPos, posLen)); 2995 } 2996 2997 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 2998 unsigned posLen) { 2999 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 3000 getLocationOfByte(startPos), 3001 /*IsStringLocation*/true, 3002 getSpecifierRange(startPos, posLen)); 3003 } 3004 3005 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 3006 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 3007 // The presence of a null character is likely an error. 3008 EmitFormatDiagnostic( 3009 S.PDiag(diag::warn_printf_format_string_contains_null_char), 3010 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 3011 getFormatStringRange()); 3012 } 3013 } 3014 3015 // Note that this may return NULL if there was an error parsing or building 3016 // one of the argument expressions. 3017 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 3018 return Args[FirstDataArg + i]; 3019 } 3020 3021 void CheckFormatHandler::DoneProcessing() { 3022 // Does the number of data arguments exceed the number of 3023 // format conversions in the format string? 3024 if (!HasVAListArg) { 3025 // Find any arguments that weren't covered. 3026 CoveredArgs.flip(); 3027 signed notCoveredArg = CoveredArgs.find_first(); 3028 if (notCoveredArg >= 0) { 3029 assert((unsigned)notCoveredArg < NumDataArgs); 3030 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) { 3031 SourceLocation Loc = E->getLocStart(); 3032 if (!S.getSourceManager().isInSystemMacro(Loc)) { 3033 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used), 3034 Loc, /*IsStringLocation*/false, 3035 getFormatStringRange()); 3036 } 3037 } 3038 } 3039 } 3040 } 3041 3042 bool 3043 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 3044 SourceLocation Loc, 3045 const char *startSpec, 3046 unsigned specifierLen, 3047 const char *csStart, 3048 unsigned csLen) { 3049 3050 bool keepGoing = true; 3051 if (argIndex < NumDataArgs) { 3052 // Consider the argument coverered, even though the specifier doesn't 3053 // make sense. 3054 CoveredArgs.set(argIndex); 3055 } 3056 else { 3057 // If argIndex exceeds the number of data arguments we 3058 // don't issue a warning because that is just a cascade of warnings (and 3059 // they may have intended '%%' anyway). We don't want to continue processing 3060 // the format string after this point, however, as we will like just get 3061 // gibberish when trying to match arguments. 3062 keepGoing = false; 3063 } 3064 3065 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion) 3066 << StringRef(csStart, csLen), 3067 Loc, /*IsStringLocation*/true, 3068 getSpecifierRange(startSpec, specifierLen)); 3069 3070 return keepGoing; 3071 } 3072 3073 void 3074 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 3075 const char *startSpec, 3076 unsigned specifierLen) { 3077 EmitFormatDiagnostic( 3078 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 3079 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 3080 } 3081 3082 bool 3083 CheckFormatHandler::CheckNumArgs( 3084 const analyze_format_string::FormatSpecifier &FS, 3085 const analyze_format_string::ConversionSpecifier &CS, 3086 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 3087 3088 if (argIndex >= NumDataArgs) { 3089 PartialDiagnostic PDiag = FS.usesPositionalArg() 3090 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 3091 << (argIndex+1) << NumDataArgs) 3092 : S.PDiag(diag::warn_printf_insufficient_data_args); 3093 EmitFormatDiagnostic( 3094 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 3095 getSpecifierRange(startSpecifier, specifierLen)); 3096 return false; 3097 } 3098 return true; 3099 } 3100 3101 template<typename Range> 3102 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 3103 SourceLocation Loc, 3104 bool IsStringLocation, 3105 Range StringRange, 3106 ArrayRef<FixItHint> FixIt) { 3107 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 3108 Loc, IsStringLocation, StringRange, FixIt); 3109 } 3110 3111 /// \brief If the format string is not within the funcion call, emit a note 3112 /// so that the function call and string are in diagnostic messages. 3113 /// 3114 /// \param InFunctionCall if true, the format string is within the function 3115 /// call and only one diagnostic message will be produced. Otherwise, an 3116 /// extra note will be emitted pointing to location of the format string. 3117 /// 3118 /// \param ArgumentExpr the expression that is passed as the format string 3119 /// argument in the function call. Used for getting locations when two 3120 /// diagnostics are emitted. 3121 /// 3122 /// \param PDiag the callee should already have provided any strings for the 3123 /// diagnostic message. This function only adds locations and fixits 3124 /// to diagnostics. 3125 /// 3126 /// \param Loc primary location for diagnostic. If two diagnostics are 3127 /// required, one will be at Loc and a new SourceLocation will be created for 3128 /// the other one. 3129 /// 3130 /// \param IsStringLocation if true, Loc points to the format string should be 3131 /// used for the note. Otherwise, Loc points to the argument list and will 3132 /// be used with PDiag. 3133 /// 3134 /// \param StringRange some or all of the string to highlight. This is 3135 /// templated so it can accept either a CharSourceRange or a SourceRange. 3136 /// 3137 /// \param FixIt optional fix it hint for the format string. 3138 template<typename Range> 3139 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall, 3140 const Expr *ArgumentExpr, 3141 PartialDiagnostic PDiag, 3142 SourceLocation Loc, 3143 bool IsStringLocation, 3144 Range StringRange, 3145 ArrayRef<FixItHint> FixIt) { 3146 if (InFunctionCall) { 3147 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 3148 D << StringRange; 3149 D << FixIt; 3150 } else { 3151 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 3152 << ArgumentExpr->getSourceRange(); 3153 3154 const Sema::SemaDiagnosticBuilder &Note = 3155 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 3156 diag::note_format_string_defined); 3157 3158 Note << StringRange; 3159 Note << FixIt; 3160 } 3161 } 3162 3163 //===--- CHECK: Printf format string checking ------------------------------===// 3164 3165 namespace { 3166 class CheckPrintfHandler : public CheckFormatHandler { 3167 bool ObjCContext; 3168 public: 3169 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 3170 const Expr *origFormatExpr, unsigned firstDataArg, 3171 unsigned numDataArgs, bool isObjC, 3172 const char *beg, bool hasVAListArg, 3173 ArrayRef<const Expr *> Args, 3174 unsigned formatIdx, bool inFunctionCall, 3175 Sema::VariadicCallType CallType, 3176 llvm::SmallBitVector &CheckedVarArgs) 3177 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 3178 numDataArgs, beg, hasVAListArg, Args, 3179 formatIdx, inFunctionCall, CallType, CheckedVarArgs), 3180 ObjCContext(isObjC) 3181 {} 3182 3183 3184 bool HandleInvalidPrintfConversionSpecifier( 3185 const analyze_printf::PrintfSpecifier &FS, 3186 const char *startSpecifier, 3187 unsigned specifierLen) override; 3188 3189 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 3190 const char *startSpecifier, 3191 unsigned specifierLen) override; 3192 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 3193 const char *StartSpecifier, 3194 unsigned SpecifierLen, 3195 const Expr *E); 3196 3197 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 3198 const char *startSpecifier, unsigned specifierLen); 3199 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 3200 const analyze_printf::OptionalAmount &Amt, 3201 unsigned type, 3202 const char *startSpecifier, unsigned specifierLen); 3203 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 3204 const analyze_printf::OptionalFlag &flag, 3205 const char *startSpecifier, unsigned specifierLen); 3206 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 3207 const analyze_printf::OptionalFlag &ignoredFlag, 3208 const analyze_printf::OptionalFlag &flag, 3209 const char *startSpecifier, unsigned specifierLen); 3210 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 3211 const Expr *E); 3212 3213 }; 3214 } 3215 3216 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 3217 const analyze_printf::PrintfSpecifier &FS, 3218 const char *startSpecifier, 3219 unsigned specifierLen) { 3220 const analyze_printf::PrintfConversionSpecifier &CS = 3221 FS.getConversionSpecifier(); 3222 3223 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 3224 getLocationOfByte(CS.getStart()), 3225 startSpecifier, specifierLen, 3226 CS.getStart(), CS.getLength()); 3227 } 3228 3229 bool CheckPrintfHandler::HandleAmount( 3230 const analyze_format_string::OptionalAmount &Amt, 3231 unsigned k, const char *startSpecifier, 3232 unsigned specifierLen) { 3233 3234 if (Amt.hasDataArgument()) { 3235 if (!HasVAListArg) { 3236 unsigned argIndex = Amt.getArgIndex(); 3237 if (argIndex >= NumDataArgs) { 3238 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 3239 << k, 3240 getLocationOfByte(Amt.getStart()), 3241 /*IsStringLocation*/true, 3242 getSpecifierRange(startSpecifier, specifierLen)); 3243 // Don't do any more checking. We will just emit 3244 // spurious errors. 3245 return false; 3246 } 3247 3248 // Type check the data argument. It should be an 'int'. 3249 // Although not in conformance with C99, we also allow the argument to be 3250 // an 'unsigned int' as that is a reasonably safe case. GCC also 3251 // doesn't emit a warning for that case. 3252 CoveredArgs.set(argIndex); 3253 const Expr *Arg = getDataArg(argIndex); 3254 if (!Arg) 3255 return false; 3256 3257 QualType T = Arg->getType(); 3258 3259 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 3260 assert(AT.isValid()); 3261 3262 if (!AT.matchesType(S.Context, T)) { 3263 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 3264 << k << AT.getRepresentativeTypeName(S.Context) 3265 << T << Arg->getSourceRange(), 3266 getLocationOfByte(Amt.getStart()), 3267 /*IsStringLocation*/true, 3268 getSpecifierRange(startSpecifier, specifierLen)); 3269 // Don't do any more checking. We will just emit 3270 // spurious errors. 3271 return false; 3272 } 3273 } 3274 } 3275 return true; 3276 } 3277 3278 void CheckPrintfHandler::HandleInvalidAmount( 3279 const analyze_printf::PrintfSpecifier &FS, 3280 const analyze_printf::OptionalAmount &Amt, 3281 unsigned type, 3282 const char *startSpecifier, 3283 unsigned specifierLen) { 3284 const analyze_printf::PrintfConversionSpecifier &CS = 3285 FS.getConversionSpecifier(); 3286 3287 FixItHint fixit = 3288 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 3289 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 3290 Amt.getConstantLength())) 3291 : FixItHint(); 3292 3293 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 3294 << type << CS.toString(), 3295 getLocationOfByte(Amt.getStart()), 3296 /*IsStringLocation*/true, 3297 getSpecifierRange(startSpecifier, specifierLen), 3298 fixit); 3299 } 3300 3301 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 3302 const analyze_printf::OptionalFlag &flag, 3303 const char *startSpecifier, 3304 unsigned specifierLen) { 3305 // Warn about pointless flag with a fixit removal. 3306 const analyze_printf::PrintfConversionSpecifier &CS = 3307 FS.getConversionSpecifier(); 3308 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 3309 << flag.toString() << CS.toString(), 3310 getLocationOfByte(flag.getPosition()), 3311 /*IsStringLocation*/true, 3312 getSpecifierRange(startSpecifier, specifierLen), 3313 FixItHint::CreateRemoval( 3314 getSpecifierRange(flag.getPosition(), 1))); 3315 } 3316 3317 void CheckPrintfHandler::HandleIgnoredFlag( 3318 const analyze_printf::PrintfSpecifier &FS, 3319 const analyze_printf::OptionalFlag &ignoredFlag, 3320 const analyze_printf::OptionalFlag &flag, 3321 const char *startSpecifier, 3322 unsigned specifierLen) { 3323 // Warn about ignored flag with a fixit removal. 3324 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 3325 << ignoredFlag.toString() << flag.toString(), 3326 getLocationOfByte(ignoredFlag.getPosition()), 3327 /*IsStringLocation*/true, 3328 getSpecifierRange(startSpecifier, specifierLen), 3329 FixItHint::CreateRemoval( 3330 getSpecifierRange(ignoredFlag.getPosition(), 1))); 3331 } 3332 3333 // Determines if the specified is a C++ class or struct containing 3334 // a member with the specified name and kind (e.g. a CXXMethodDecl named 3335 // "c_str()"). 3336 template<typename MemberKind> 3337 static llvm::SmallPtrSet<MemberKind*, 1> 3338 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 3339 const RecordType *RT = Ty->getAs<RecordType>(); 3340 llvm::SmallPtrSet<MemberKind*, 1> Results; 3341 3342 if (!RT) 3343 return Results; 3344 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 3345 if (!RD || !RD->getDefinition()) 3346 return Results; 3347 3348 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 3349 Sema::LookupMemberName); 3350 R.suppressDiagnostics(); 3351 3352 // We just need to include all members of the right kind turned up by the 3353 // filter, at this point. 3354 if (S.LookupQualifiedName(R, RT->getDecl())) 3355 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3356 NamedDecl *decl = (*I)->getUnderlyingDecl(); 3357 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 3358 Results.insert(FK); 3359 } 3360 return Results; 3361 } 3362 3363 /// Check if we could call '.c_str()' on an object. 3364 /// 3365 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 3366 /// allow the call, or if it would be ambiguous). 3367 bool Sema::hasCStrMethod(const Expr *E) { 3368 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 3369 MethodSet Results = 3370 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 3371 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 3372 MI != ME; ++MI) 3373 if ((*MI)->getMinRequiredArguments() == 0) 3374 return true; 3375 return false; 3376 } 3377 3378 // Check if a (w)string was passed when a (w)char* was needed, and offer a 3379 // better diagnostic if so. AT is assumed to be valid. 3380 // Returns true when a c_str() conversion method is found. 3381 bool CheckPrintfHandler::checkForCStrMembers( 3382 const analyze_printf::ArgType &AT, const Expr *E) { 3383 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 3384 3385 MethodSet Results = 3386 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 3387 3388 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 3389 MI != ME; ++MI) { 3390 const CXXMethodDecl *Method = *MI; 3391 if (Method->getMinRequiredArguments() == 0 && 3392 AT.matchesType(S.Context, Method->getReturnType())) { 3393 // FIXME: Suggest parens if the expression needs them. 3394 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 3395 S.Diag(E->getLocStart(), diag::note_printf_c_str) 3396 << "c_str()" 3397 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 3398 return true; 3399 } 3400 } 3401 3402 return false; 3403 } 3404 3405 bool 3406 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 3407 &FS, 3408 const char *startSpecifier, 3409 unsigned specifierLen) { 3410 3411 using namespace analyze_format_string; 3412 using namespace analyze_printf; 3413 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 3414 3415 if (FS.consumesDataArgument()) { 3416 if (atFirstArg) { 3417 atFirstArg = false; 3418 usesPositionalArgs = FS.usesPositionalArg(); 3419 } 3420 else if (usesPositionalArgs != FS.usesPositionalArg()) { 3421 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 3422 startSpecifier, specifierLen); 3423 return false; 3424 } 3425 } 3426 3427 // First check if the field width, precision, and conversion specifier 3428 // have matching data arguments. 3429 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 3430 startSpecifier, specifierLen)) { 3431 return false; 3432 } 3433 3434 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 3435 startSpecifier, specifierLen)) { 3436 return false; 3437 } 3438 3439 if (!CS.consumesDataArgument()) { 3440 // FIXME: Technically specifying a precision or field width here 3441 // makes no sense. Worth issuing a warning at some point. 3442 return true; 3443 } 3444 3445 // Consume the argument. 3446 unsigned argIndex = FS.getArgIndex(); 3447 if (argIndex < NumDataArgs) { 3448 // The check to see if the argIndex is valid will come later. 3449 // We set the bit here because we may exit early from this 3450 // function if we encounter some other error. 3451 CoveredArgs.set(argIndex); 3452 } 3453 3454 // FreeBSD kernel extensions. 3455 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 3456 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 3457 // We need at least two arguments. 3458 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 3459 return false; 3460 3461 // Claim the second argument. 3462 CoveredArgs.set(argIndex + 1); 3463 3464 // Type check the first argument (int for %b, pointer for %D) 3465 const Expr *Ex = getDataArg(argIndex); 3466 const analyze_printf::ArgType &AT = 3467 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 3468 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 3469 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 3470 EmitFormatDiagnostic( 3471 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3472 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 3473 << false << Ex->getSourceRange(), 3474 Ex->getLocStart(), /*IsStringLocation*/false, 3475 getSpecifierRange(startSpecifier, specifierLen)); 3476 3477 // Type check the second argument (char * for both %b and %D) 3478 Ex = getDataArg(argIndex + 1); 3479 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 3480 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 3481 EmitFormatDiagnostic( 3482 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3483 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 3484 << false << Ex->getSourceRange(), 3485 Ex->getLocStart(), /*IsStringLocation*/false, 3486 getSpecifierRange(startSpecifier, specifierLen)); 3487 3488 return true; 3489 } 3490 3491 // Check for using an Objective-C specific conversion specifier 3492 // in a non-ObjC literal. 3493 if (!ObjCContext && CS.isObjCArg()) { 3494 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 3495 specifierLen); 3496 } 3497 3498 // Check for invalid use of field width 3499 if (!FS.hasValidFieldWidth()) { 3500 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 3501 startSpecifier, specifierLen); 3502 } 3503 3504 // Check for invalid use of precision 3505 if (!FS.hasValidPrecision()) { 3506 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 3507 startSpecifier, specifierLen); 3508 } 3509 3510 // Check each flag does not conflict with any other component. 3511 if (!FS.hasValidThousandsGroupingPrefix()) 3512 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 3513 if (!FS.hasValidLeadingZeros()) 3514 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 3515 if (!FS.hasValidPlusPrefix()) 3516 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 3517 if (!FS.hasValidSpacePrefix()) 3518 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 3519 if (!FS.hasValidAlternativeForm()) 3520 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 3521 if (!FS.hasValidLeftJustified()) 3522 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 3523 3524 // Check that flags are not ignored by another flag 3525 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 3526 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 3527 startSpecifier, specifierLen); 3528 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 3529 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 3530 startSpecifier, specifierLen); 3531 3532 // Check the length modifier is valid with the given conversion specifier. 3533 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 3534 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3535 diag::warn_format_nonsensical_length); 3536 else if (!FS.hasStandardLengthModifier()) 3537 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 3538 else if (!FS.hasStandardLengthConversionCombination()) 3539 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 3540 diag::warn_format_non_standard_conversion_spec); 3541 3542 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 3543 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 3544 3545 // The remaining checks depend on the data arguments. 3546 if (HasVAListArg) 3547 return true; 3548 3549 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 3550 return false; 3551 3552 const Expr *Arg = getDataArg(argIndex); 3553 if (!Arg) 3554 return true; 3555 3556 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 3557 } 3558 3559 static bool requiresParensToAddCast(const Expr *E) { 3560 // FIXME: We should have a general way to reason about operator 3561 // precedence and whether parens are actually needed here. 3562 // Take care of a few common cases where they aren't. 3563 const Expr *Inside = E->IgnoreImpCasts(); 3564 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 3565 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 3566 3567 switch (Inside->getStmtClass()) { 3568 case Stmt::ArraySubscriptExprClass: 3569 case Stmt::CallExprClass: 3570 case Stmt::CharacterLiteralClass: 3571 case Stmt::CXXBoolLiteralExprClass: 3572 case Stmt::DeclRefExprClass: 3573 case Stmt::FloatingLiteralClass: 3574 case Stmt::IntegerLiteralClass: 3575 case Stmt::MemberExprClass: 3576 case Stmt::ObjCArrayLiteralClass: 3577 case Stmt::ObjCBoolLiteralExprClass: 3578 case Stmt::ObjCBoxedExprClass: 3579 case Stmt::ObjCDictionaryLiteralClass: 3580 case Stmt::ObjCEncodeExprClass: 3581 case Stmt::ObjCIvarRefExprClass: 3582 case Stmt::ObjCMessageExprClass: 3583 case Stmt::ObjCPropertyRefExprClass: 3584 case Stmt::ObjCStringLiteralClass: 3585 case Stmt::ObjCSubscriptRefExprClass: 3586 case Stmt::ParenExprClass: 3587 case Stmt::StringLiteralClass: 3588 case Stmt::UnaryOperatorClass: 3589 return false; 3590 default: 3591 return true; 3592 } 3593 } 3594 3595 static std::pair<QualType, StringRef> 3596 shouldNotPrintDirectly(const ASTContext &Context, 3597 QualType IntendedTy, 3598 const Expr *E) { 3599 // Use a 'while' to peel off layers of typedefs. 3600 QualType TyTy = IntendedTy; 3601 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 3602 StringRef Name = UserTy->getDecl()->getName(); 3603 QualType CastTy = llvm::StringSwitch<QualType>(Name) 3604 .Case("NSInteger", Context.LongTy) 3605 .Case("NSUInteger", Context.UnsignedLongTy) 3606 .Case("SInt32", Context.IntTy) 3607 .Case("UInt32", Context.UnsignedIntTy) 3608 .Default(QualType()); 3609 3610 if (!CastTy.isNull()) 3611 return std::make_pair(CastTy, Name); 3612 3613 TyTy = UserTy->desugar(); 3614 } 3615 3616 // Strip parens if necessary. 3617 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 3618 return shouldNotPrintDirectly(Context, 3619 PE->getSubExpr()->getType(), 3620 PE->getSubExpr()); 3621 3622 // If this is a conditional expression, then its result type is constructed 3623 // via usual arithmetic conversions and thus there might be no necessary 3624 // typedef sugar there. Recurse to operands to check for NSInteger & 3625 // Co. usage condition. 3626 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3627 QualType TrueTy, FalseTy; 3628 StringRef TrueName, FalseName; 3629 3630 std::tie(TrueTy, TrueName) = 3631 shouldNotPrintDirectly(Context, 3632 CO->getTrueExpr()->getType(), 3633 CO->getTrueExpr()); 3634 std::tie(FalseTy, FalseName) = 3635 shouldNotPrintDirectly(Context, 3636 CO->getFalseExpr()->getType(), 3637 CO->getFalseExpr()); 3638 3639 if (TrueTy == FalseTy) 3640 return std::make_pair(TrueTy, TrueName); 3641 else if (TrueTy.isNull()) 3642 return std::make_pair(FalseTy, FalseName); 3643 else if (FalseTy.isNull()) 3644 return std::make_pair(TrueTy, TrueName); 3645 } 3646 3647 return std::make_pair(QualType(), StringRef()); 3648 } 3649 3650 bool 3651 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 3652 const char *StartSpecifier, 3653 unsigned SpecifierLen, 3654 const Expr *E) { 3655 using namespace analyze_format_string; 3656 using namespace analyze_printf; 3657 // Now type check the data expression that matches the 3658 // format specifier. 3659 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 3660 ObjCContext); 3661 if (!AT.isValid()) 3662 return true; 3663 3664 QualType ExprTy = E->getType(); 3665 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 3666 ExprTy = TET->getUnderlyingExpr()->getType(); 3667 } 3668 3669 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 3670 3671 if (match == analyze_printf::ArgType::Match) { 3672 return true; 3673 } 3674 3675 // Look through argument promotions for our error message's reported type. 3676 // This includes the integral and floating promotions, but excludes array 3677 // and function pointer decay; seeing that an argument intended to be a 3678 // string has type 'char [6]' is probably more confusing than 'char *'. 3679 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 3680 if (ICE->getCastKind() == CK_IntegralCast || 3681 ICE->getCastKind() == CK_FloatingCast) { 3682 E = ICE->getSubExpr(); 3683 ExprTy = E->getType(); 3684 3685 // Check if we didn't match because of an implicit cast from a 'char' 3686 // or 'short' to an 'int'. This is done because printf is a varargs 3687 // function. 3688 if (ICE->getType() == S.Context.IntTy || 3689 ICE->getType() == S.Context.UnsignedIntTy) { 3690 // All further checking is done on the subexpression. 3691 if (AT.matchesType(S.Context, ExprTy)) 3692 return true; 3693 } 3694 } 3695 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 3696 // Special case for 'a', which has type 'int' in C. 3697 // Note, however, that we do /not/ want to treat multibyte constants like 3698 // 'MooV' as characters! This form is deprecated but still exists. 3699 if (ExprTy == S.Context.IntTy) 3700 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 3701 ExprTy = S.Context.CharTy; 3702 } 3703 3704 // Look through enums to their underlying type. 3705 bool IsEnum = false; 3706 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 3707 ExprTy = EnumTy->getDecl()->getIntegerType(); 3708 IsEnum = true; 3709 } 3710 3711 // %C in an Objective-C context prints a unichar, not a wchar_t. 3712 // If the argument is an integer of some kind, believe the %C and suggest 3713 // a cast instead of changing the conversion specifier. 3714 QualType IntendedTy = ExprTy; 3715 if (ObjCContext && 3716 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 3717 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 3718 !ExprTy->isCharType()) { 3719 // 'unichar' is defined as a typedef of unsigned short, but we should 3720 // prefer using the typedef if it is visible. 3721 IntendedTy = S.Context.UnsignedShortTy; 3722 3723 // While we are here, check if the value is an IntegerLiteral that happens 3724 // to be within the valid range. 3725 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 3726 const llvm::APInt &V = IL->getValue(); 3727 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 3728 return true; 3729 } 3730 3731 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 3732 Sema::LookupOrdinaryName); 3733 if (S.LookupName(Result, S.getCurScope())) { 3734 NamedDecl *ND = Result.getFoundDecl(); 3735 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 3736 if (TD->getUnderlyingType() == IntendedTy) 3737 IntendedTy = S.Context.getTypedefType(TD); 3738 } 3739 } 3740 } 3741 3742 // Special-case some of Darwin's platform-independence types by suggesting 3743 // casts to primitive types that are known to be large enough. 3744 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 3745 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 3746 QualType CastTy; 3747 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 3748 if (!CastTy.isNull()) { 3749 IntendedTy = CastTy; 3750 ShouldNotPrintDirectly = true; 3751 } 3752 } 3753 3754 // We may be able to offer a FixItHint if it is a supported type. 3755 PrintfSpecifier fixedFS = FS; 3756 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 3757 S.Context, ObjCContext); 3758 3759 if (success) { 3760 // Get the fix string from the fixed format specifier 3761 SmallString<16> buf; 3762 llvm::raw_svector_ostream os(buf); 3763 fixedFS.toString(os); 3764 3765 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 3766 3767 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 3768 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 3769 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 3770 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 3771 } 3772 // In this case, the specifier is wrong and should be changed to match 3773 // the argument. 3774 EmitFormatDiagnostic(S.PDiag(diag) 3775 << AT.getRepresentativeTypeName(S.Context) 3776 << IntendedTy << IsEnum << E->getSourceRange(), 3777 E->getLocStart(), 3778 /*IsStringLocation*/ false, SpecRange, 3779 FixItHint::CreateReplacement(SpecRange, os.str())); 3780 3781 } else { 3782 // The canonical type for formatting this value is different from the 3783 // actual type of the expression. (This occurs, for example, with Darwin's 3784 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 3785 // should be printed as 'long' for 64-bit compatibility.) 3786 // Rather than emitting a normal format/argument mismatch, we want to 3787 // add a cast to the recommended type (and correct the format string 3788 // if necessary). 3789 SmallString<16> CastBuf; 3790 llvm::raw_svector_ostream CastFix(CastBuf); 3791 CastFix << "("; 3792 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 3793 CastFix << ")"; 3794 3795 SmallVector<FixItHint,4> Hints; 3796 if (!AT.matchesType(S.Context, IntendedTy)) 3797 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 3798 3799 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 3800 // If there's already a cast present, just replace it. 3801 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 3802 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 3803 3804 } else if (!requiresParensToAddCast(E)) { 3805 // If the expression has high enough precedence, 3806 // just write the C-style cast. 3807 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 3808 CastFix.str())); 3809 } else { 3810 // Otherwise, add parens around the expression as well as the cast. 3811 CastFix << "("; 3812 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 3813 CastFix.str())); 3814 3815 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 3816 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 3817 } 3818 3819 if (ShouldNotPrintDirectly) { 3820 // The expression has a type that should not be printed directly. 3821 // We extract the name from the typedef because we don't want to show 3822 // the underlying type in the diagnostic. 3823 StringRef Name; 3824 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 3825 Name = TypedefTy->getDecl()->getName(); 3826 else 3827 Name = CastTyName; 3828 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 3829 << Name << IntendedTy << IsEnum 3830 << E->getSourceRange(), 3831 E->getLocStart(), /*IsStringLocation=*/false, 3832 SpecRange, Hints); 3833 } else { 3834 // In this case, the expression could be printed using a different 3835 // specifier, but we've decided that the specifier is probably correct 3836 // and we should cast instead. Just use the normal warning message. 3837 EmitFormatDiagnostic( 3838 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 3839 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 3840 << E->getSourceRange(), 3841 E->getLocStart(), /*IsStringLocation*/false, 3842 SpecRange, Hints); 3843 } 3844 } 3845 } else { 3846 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 3847 SpecifierLen); 3848 // Since the warning for passing non-POD types to variadic functions 3849 // was deferred until now, we emit a warning for non-POD 3850 // arguments here. 3851 switch (S.isValidVarArgType(ExprTy)) { 3852 case Sema::VAK_Valid: 3853 case Sema::VAK_ValidInCXX11: { 3854 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 3855 if (match == analyze_printf::ArgType::NoMatchPedantic) { 3856 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 3857 } 3858 3859 EmitFormatDiagnostic( 3860 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 3861 << IsEnum << CSR << E->getSourceRange(), 3862 E->getLocStart(), /*IsStringLocation*/ false, CSR); 3863 break; 3864 } 3865 case Sema::VAK_Undefined: 3866 case Sema::VAK_MSVCUndefined: 3867 EmitFormatDiagnostic( 3868 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 3869 << S.getLangOpts().CPlusPlus11 3870 << ExprTy 3871 << CallType 3872 << AT.getRepresentativeTypeName(S.Context) 3873 << CSR 3874 << E->getSourceRange(), 3875 E->getLocStart(), /*IsStringLocation*/false, CSR); 3876 checkForCStrMembers(AT, E); 3877 break; 3878 3879 case Sema::VAK_Invalid: 3880 if (ExprTy->isObjCObjectType()) 3881 EmitFormatDiagnostic( 3882 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 3883 << S.getLangOpts().CPlusPlus11 3884 << ExprTy 3885 << CallType 3886 << AT.getRepresentativeTypeName(S.Context) 3887 << CSR 3888 << E->getSourceRange(), 3889 E->getLocStart(), /*IsStringLocation*/false, CSR); 3890 else 3891 // FIXME: If this is an initializer list, suggest removing the braces 3892 // or inserting a cast to the target type. 3893 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 3894 << isa<InitListExpr>(E) << ExprTy << CallType 3895 << AT.getRepresentativeTypeName(S.Context) 3896 << E->getSourceRange(); 3897 break; 3898 } 3899 3900 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 3901 "format string specifier index out of range"); 3902 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 3903 } 3904 3905 return true; 3906 } 3907 3908 //===--- CHECK: Scanf format string checking ------------------------------===// 3909 3910 namespace { 3911 class CheckScanfHandler : public CheckFormatHandler { 3912 public: 3913 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 3914 const Expr *origFormatExpr, unsigned firstDataArg, 3915 unsigned numDataArgs, const char *beg, bool hasVAListArg, 3916 ArrayRef<const Expr *> Args, 3917 unsigned formatIdx, bool inFunctionCall, 3918 Sema::VariadicCallType CallType, 3919 llvm::SmallBitVector &CheckedVarArgs) 3920 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 3921 numDataArgs, beg, hasVAListArg, 3922 Args, formatIdx, inFunctionCall, CallType, 3923 CheckedVarArgs) 3924 {} 3925 3926 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 3927 const char *startSpecifier, 3928 unsigned specifierLen) override; 3929 3930 bool HandleInvalidScanfConversionSpecifier( 3931 const analyze_scanf::ScanfSpecifier &FS, 3932 const char *startSpecifier, 3933 unsigned specifierLen) override; 3934 3935 void HandleIncompleteScanList(const char *start, const char *end) override; 3936 }; 3937 } 3938 3939 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 3940 const char *end) { 3941 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 3942 getLocationOfByte(end), /*IsStringLocation*/true, 3943 getSpecifierRange(start, end - start)); 3944 } 3945 3946 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 3947 const analyze_scanf::ScanfSpecifier &FS, 3948 const char *startSpecifier, 3949 unsigned specifierLen) { 3950 3951 const analyze_scanf::ScanfConversionSpecifier &CS = 3952 FS.getConversionSpecifier(); 3953 3954 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 3955 getLocationOfByte(CS.getStart()), 3956 startSpecifier, specifierLen, 3957 CS.getStart(), CS.getLength()); 3958 } 3959 3960 bool CheckScanfHandler::HandleScanfSpecifier( 3961 const analyze_scanf::ScanfSpecifier &FS, 3962 const char *startSpecifier, 3963 unsigned specifierLen) { 3964 3965 using namespace analyze_scanf; 3966 using namespace analyze_format_string; 3967 3968 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 3969 3970 // Handle case where '%' and '*' don't consume an argument. These shouldn't 3971 // be used to decide if we are using positional arguments consistently. 3972 if (FS.consumesDataArgument()) { 3973 if (atFirstArg) { 3974 atFirstArg = false; 3975 usesPositionalArgs = FS.usesPositionalArg(); 3976 } 3977 else if (usesPositionalArgs != FS.usesPositionalArg()) { 3978 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 3979 startSpecifier, specifierLen); 3980 return false; 3981 } 3982 } 3983 3984 // Check if the field with is non-zero. 3985 const OptionalAmount &Amt = FS.getFieldWidth(); 3986 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 3987 if (Amt.getConstantAmount() == 0) { 3988 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 3989 Amt.getConstantLength()); 3990 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 3991 getLocationOfByte(Amt.getStart()), 3992 /*IsStringLocation*/true, R, 3993 FixItHint::CreateRemoval(R)); 3994 } 3995 } 3996 3997 if (!FS.consumesDataArgument()) { 3998 // FIXME: Technically specifying a precision or field width here 3999 // makes no sense. Worth issuing a warning at some point. 4000 return true; 4001 } 4002 4003 // Consume the argument. 4004 unsigned argIndex = FS.getArgIndex(); 4005 if (argIndex < NumDataArgs) { 4006 // The check to see if the argIndex is valid will come later. 4007 // We set the bit here because we may exit early from this 4008 // function if we encounter some other error. 4009 CoveredArgs.set(argIndex); 4010 } 4011 4012 // Check the length modifier is valid with the given conversion specifier. 4013 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 4014 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 4015 diag::warn_format_nonsensical_length); 4016 else if (!FS.hasStandardLengthModifier()) 4017 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 4018 else if (!FS.hasStandardLengthConversionCombination()) 4019 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 4020 diag::warn_format_non_standard_conversion_spec); 4021 4022 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 4023 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 4024 4025 // The remaining checks depend on the data arguments. 4026 if (HasVAListArg) 4027 return true; 4028 4029 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 4030 return false; 4031 4032 // Check that the argument type matches the format specifier. 4033 const Expr *Ex = getDataArg(argIndex); 4034 if (!Ex) 4035 return true; 4036 4037 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 4038 4039 if (!AT.isValid()) { 4040 return true; 4041 } 4042 4043 analyze_format_string::ArgType::MatchKind match = 4044 AT.matchesType(S.Context, Ex->getType()); 4045 if (match == analyze_format_string::ArgType::Match) { 4046 return true; 4047 } 4048 4049 ScanfSpecifier fixedFS = FS; 4050 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 4051 S.getLangOpts(), S.Context); 4052 4053 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 4054 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 4055 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 4056 } 4057 4058 if (success) { 4059 // Get the fix string from the fixed format specifier. 4060 SmallString<128> buf; 4061 llvm::raw_svector_ostream os(buf); 4062 fixedFS.toString(os); 4063 4064 EmitFormatDiagnostic( 4065 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 4066 << Ex->getType() << false << Ex->getSourceRange(), 4067 Ex->getLocStart(), 4068 /*IsStringLocation*/ false, 4069 getSpecifierRange(startSpecifier, specifierLen), 4070 FixItHint::CreateReplacement( 4071 getSpecifierRange(startSpecifier, specifierLen), os.str())); 4072 } else { 4073 EmitFormatDiagnostic(S.PDiag(diag) 4074 << AT.getRepresentativeTypeName(S.Context) 4075 << Ex->getType() << false << Ex->getSourceRange(), 4076 Ex->getLocStart(), 4077 /*IsStringLocation*/ false, 4078 getSpecifierRange(startSpecifier, specifierLen)); 4079 } 4080 4081 return true; 4082 } 4083 4084 void Sema::CheckFormatString(const StringLiteral *FExpr, 4085 const Expr *OrigFormatExpr, 4086 ArrayRef<const Expr *> Args, 4087 bool HasVAListArg, unsigned format_idx, 4088 unsigned firstDataArg, FormatStringType Type, 4089 bool inFunctionCall, VariadicCallType CallType, 4090 llvm::SmallBitVector &CheckedVarArgs) { 4091 4092 // CHECK: is the format string a wide literal? 4093 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 4094 CheckFormatHandler::EmitFormatDiagnostic( 4095 *this, inFunctionCall, Args[format_idx], 4096 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 4097 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 4098 return; 4099 } 4100 4101 // Str - The format string. NOTE: this is NOT null-terminated! 4102 StringRef StrRef = FExpr->getString(); 4103 const char *Str = StrRef.data(); 4104 // Account for cases where the string literal is truncated in a declaration. 4105 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 4106 assert(T && "String literal not of constant array type!"); 4107 size_t TypeSize = T->getSize().getZExtValue(); 4108 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 4109 const unsigned numDataArgs = Args.size() - firstDataArg; 4110 4111 // Emit a warning if the string literal is truncated and does not contain an 4112 // embedded null character. 4113 if (TypeSize <= StrRef.size() && 4114 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 4115 CheckFormatHandler::EmitFormatDiagnostic( 4116 *this, inFunctionCall, Args[format_idx], 4117 PDiag(diag::warn_printf_format_string_not_null_terminated), 4118 FExpr->getLocStart(), 4119 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 4120 return; 4121 } 4122 4123 // CHECK: empty format string? 4124 if (StrLen == 0 && numDataArgs > 0) { 4125 CheckFormatHandler::EmitFormatDiagnostic( 4126 *this, inFunctionCall, Args[format_idx], 4127 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 4128 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 4129 return; 4130 } 4131 4132 if (Type == FST_Printf || Type == FST_NSString || 4133 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) { 4134 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, 4135 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace), 4136 Str, HasVAListArg, Args, format_idx, 4137 inFunctionCall, CallType, CheckedVarArgs); 4138 4139 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 4140 getLangOpts(), 4141 Context.getTargetInfo(), 4142 Type == FST_FreeBSDKPrintf)) 4143 H.DoneProcessing(); 4144 } else if (Type == FST_Scanf) { 4145 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 4146 Str, HasVAListArg, Args, format_idx, 4147 inFunctionCall, CallType, CheckedVarArgs); 4148 4149 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 4150 getLangOpts(), 4151 Context.getTargetInfo())) 4152 H.DoneProcessing(); 4153 } // TODO: handle other formats 4154 } 4155 4156 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 4157 // Str - The format string. NOTE: this is NOT null-terminated! 4158 StringRef StrRef = FExpr->getString(); 4159 const char *Str = StrRef.data(); 4160 // Account for cases where the string literal is truncated in a declaration. 4161 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 4162 assert(T && "String literal not of constant array type!"); 4163 size_t TypeSize = T->getSize().getZExtValue(); 4164 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 4165 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 4166 getLangOpts(), 4167 Context.getTargetInfo()); 4168 } 4169 4170 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 4171 4172 // Returns the related absolute value function that is larger, of 0 if one 4173 // does not exist. 4174 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 4175 switch (AbsFunction) { 4176 default: 4177 return 0; 4178 4179 case Builtin::BI__builtin_abs: 4180 return Builtin::BI__builtin_labs; 4181 case Builtin::BI__builtin_labs: 4182 return Builtin::BI__builtin_llabs; 4183 case Builtin::BI__builtin_llabs: 4184 return 0; 4185 4186 case Builtin::BI__builtin_fabsf: 4187 return Builtin::BI__builtin_fabs; 4188 case Builtin::BI__builtin_fabs: 4189 return Builtin::BI__builtin_fabsl; 4190 case Builtin::BI__builtin_fabsl: 4191 return 0; 4192 4193 case Builtin::BI__builtin_cabsf: 4194 return Builtin::BI__builtin_cabs; 4195 case Builtin::BI__builtin_cabs: 4196 return Builtin::BI__builtin_cabsl; 4197 case Builtin::BI__builtin_cabsl: 4198 return 0; 4199 4200 case Builtin::BIabs: 4201 return Builtin::BIlabs; 4202 case Builtin::BIlabs: 4203 return Builtin::BIllabs; 4204 case Builtin::BIllabs: 4205 return 0; 4206 4207 case Builtin::BIfabsf: 4208 return Builtin::BIfabs; 4209 case Builtin::BIfabs: 4210 return Builtin::BIfabsl; 4211 case Builtin::BIfabsl: 4212 return 0; 4213 4214 case Builtin::BIcabsf: 4215 return Builtin::BIcabs; 4216 case Builtin::BIcabs: 4217 return Builtin::BIcabsl; 4218 case Builtin::BIcabsl: 4219 return 0; 4220 } 4221 } 4222 4223 // Returns the argument type of the absolute value function. 4224 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 4225 unsigned AbsType) { 4226 if (AbsType == 0) 4227 return QualType(); 4228 4229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 4230 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 4231 if (Error != ASTContext::GE_None) 4232 return QualType(); 4233 4234 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 4235 if (!FT) 4236 return QualType(); 4237 4238 if (FT->getNumParams() != 1) 4239 return QualType(); 4240 4241 return FT->getParamType(0); 4242 } 4243 4244 // Returns the best absolute value function, or zero, based on type and 4245 // current absolute value function. 4246 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 4247 unsigned AbsFunctionKind) { 4248 unsigned BestKind = 0; 4249 uint64_t ArgSize = Context.getTypeSize(ArgType); 4250 for (unsigned Kind = AbsFunctionKind; Kind != 0; 4251 Kind = getLargerAbsoluteValueFunction(Kind)) { 4252 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 4253 if (Context.getTypeSize(ParamType) >= ArgSize) { 4254 if (BestKind == 0) 4255 BestKind = Kind; 4256 else if (Context.hasSameType(ParamType, ArgType)) { 4257 BestKind = Kind; 4258 break; 4259 } 4260 } 4261 } 4262 return BestKind; 4263 } 4264 4265 enum AbsoluteValueKind { 4266 AVK_Integer, 4267 AVK_Floating, 4268 AVK_Complex 4269 }; 4270 4271 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 4272 if (T->isIntegralOrEnumerationType()) 4273 return AVK_Integer; 4274 if (T->isRealFloatingType()) 4275 return AVK_Floating; 4276 if (T->isAnyComplexType()) 4277 return AVK_Complex; 4278 4279 llvm_unreachable("Type not integer, floating, or complex"); 4280 } 4281 4282 // Changes the absolute value function to a different type. Preserves whether 4283 // the function is a builtin. 4284 static unsigned changeAbsFunction(unsigned AbsKind, 4285 AbsoluteValueKind ValueKind) { 4286 switch (ValueKind) { 4287 case AVK_Integer: 4288 switch (AbsKind) { 4289 default: 4290 return 0; 4291 case Builtin::BI__builtin_fabsf: 4292 case Builtin::BI__builtin_fabs: 4293 case Builtin::BI__builtin_fabsl: 4294 case Builtin::BI__builtin_cabsf: 4295 case Builtin::BI__builtin_cabs: 4296 case Builtin::BI__builtin_cabsl: 4297 return Builtin::BI__builtin_abs; 4298 case Builtin::BIfabsf: 4299 case Builtin::BIfabs: 4300 case Builtin::BIfabsl: 4301 case Builtin::BIcabsf: 4302 case Builtin::BIcabs: 4303 case Builtin::BIcabsl: 4304 return Builtin::BIabs; 4305 } 4306 case AVK_Floating: 4307 switch (AbsKind) { 4308 default: 4309 return 0; 4310 case Builtin::BI__builtin_abs: 4311 case Builtin::BI__builtin_labs: 4312 case Builtin::BI__builtin_llabs: 4313 case Builtin::BI__builtin_cabsf: 4314 case Builtin::BI__builtin_cabs: 4315 case Builtin::BI__builtin_cabsl: 4316 return Builtin::BI__builtin_fabsf; 4317 case Builtin::BIabs: 4318 case Builtin::BIlabs: 4319 case Builtin::BIllabs: 4320 case Builtin::BIcabsf: 4321 case Builtin::BIcabs: 4322 case Builtin::BIcabsl: 4323 return Builtin::BIfabsf; 4324 } 4325 case AVK_Complex: 4326 switch (AbsKind) { 4327 default: 4328 return 0; 4329 case Builtin::BI__builtin_abs: 4330 case Builtin::BI__builtin_labs: 4331 case Builtin::BI__builtin_llabs: 4332 case Builtin::BI__builtin_fabsf: 4333 case Builtin::BI__builtin_fabs: 4334 case Builtin::BI__builtin_fabsl: 4335 return Builtin::BI__builtin_cabsf; 4336 case Builtin::BIabs: 4337 case Builtin::BIlabs: 4338 case Builtin::BIllabs: 4339 case Builtin::BIfabsf: 4340 case Builtin::BIfabs: 4341 case Builtin::BIfabsl: 4342 return Builtin::BIcabsf; 4343 } 4344 } 4345 llvm_unreachable("Unable to convert function"); 4346 } 4347 4348 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 4349 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4350 if (!FnInfo) 4351 return 0; 4352 4353 switch (FDecl->getBuiltinID()) { 4354 default: 4355 return 0; 4356 case Builtin::BI__builtin_abs: 4357 case Builtin::BI__builtin_fabs: 4358 case Builtin::BI__builtin_fabsf: 4359 case Builtin::BI__builtin_fabsl: 4360 case Builtin::BI__builtin_labs: 4361 case Builtin::BI__builtin_llabs: 4362 case Builtin::BI__builtin_cabs: 4363 case Builtin::BI__builtin_cabsf: 4364 case Builtin::BI__builtin_cabsl: 4365 case Builtin::BIabs: 4366 case Builtin::BIlabs: 4367 case Builtin::BIllabs: 4368 case Builtin::BIfabs: 4369 case Builtin::BIfabsf: 4370 case Builtin::BIfabsl: 4371 case Builtin::BIcabs: 4372 case Builtin::BIcabsf: 4373 case Builtin::BIcabsl: 4374 return FDecl->getBuiltinID(); 4375 } 4376 llvm_unreachable("Unknown Builtin type"); 4377 } 4378 4379 // If the replacement is valid, emit a note with replacement function. 4380 // Additionally, suggest including the proper header if not already included. 4381 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 4382 unsigned AbsKind, QualType ArgType) { 4383 bool EmitHeaderHint = true; 4384 const char *HeaderName = nullptr; 4385 const char *FunctionName = nullptr; 4386 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 4387 FunctionName = "std::abs"; 4388 if (ArgType->isIntegralOrEnumerationType()) { 4389 HeaderName = "cstdlib"; 4390 } else if (ArgType->isRealFloatingType()) { 4391 HeaderName = "cmath"; 4392 } else { 4393 llvm_unreachable("Invalid Type"); 4394 } 4395 4396 // Lookup all std::abs 4397 if (NamespaceDecl *Std = S.getStdNamespace()) { 4398 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 4399 R.suppressDiagnostics(); 4400 S.LookupQualifiedName(R, Std); 4401 4402 for (const auto *I : R) { 4403 const FunctionDecl *FDecl = nullptr; 4404 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 4405 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 4406 } else { 4407 FDecl = dyn_cast<FunctionDecl>(I); 4408 } 4409 if (!FDecl) 4410 continue; 4411 4412 // Found std::abs(), check that they are the right ones. 4413 if (FDecl->getNumParams() != 1) 4414 continue; 4415 4416 // Check that the parameter type can handle the argument. 4417 QualType ParamType = FDecl->getParamDecl(0)->getType(); 4418 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 4419 S.Context.getTypeSize(ArgType) <= 4420 S.Context.getTypeSize(ParamType)) { 4421 // Found a function, don't need the header hint. 4422 EmitHeaderHint = false; 4423 break; 4424 } 4425 } 4426 } 4427 } else { 4428 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind); 4429 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 4430 4431 if (HeaderName) { 4432 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 4433 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 4434 R.suppressDiagnostics(); 4435 S.LookupName(R, S.getCurScope()); 4436 4437 if (R.isSingleResult()) { 4438 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 4439 if (FD && FD->getBuiltinID() == AbsKind) { 4440 EmitHeaderHint = false; 4441 } else { 4442 return; 4443 } 4444 } else if (!R.empty()) { 4445 return; 4446 } 4447 } 4448 } 4449 4450 S.Diag(Loc, diag::note_replace_abs_function) 4451 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 4452 4453 if (!HeaderName) 4454 return; 4455 4456 if (!EmitHeaderHint) 4457 return; 4458 4459 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 4460 << FunctionName; 4461 } 4462 4463 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 4464 if (!FDecl) 4465 return false; 4466 4467 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 4468 return false; 4469 4470 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 4471 4472 while (ND && ND->isInlineNamespace()) { 4473 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 4474 } 4475 4476 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 4477 return false; 4478 4479 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 4480 return false; 4481 4482 return true; 4483 } 4484 4485 // Warn when using the wrong abs() function. 4486 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 4487 const FunctionDecl *FDecl, 4488 IdentifierInfo *FnInfo) { 4489 if (Call->getNumArgs() != 1) 4490 return; 4491 4492 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 4493 bool IsStdAbs = IsFunctionStdAbs(FDecl); 4494 if (AbsKind == 0 && !IsStdAbs) 4495 return; 4496 4497 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 4498 QualType ParamType = Call->getArg(0)->getType(); 4499 4500 // Unsigned types cannot be negative. Suggest removing the absolute value 4501 // function call. 4502 if (ArgType->isUnsignedIntegerType()) { 4503 const char *FunctionName = 4504 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind); 4505 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 4506 Diag(Call->getExprLoc(), diag::note_remove_abs) 4507 << FunctionName 4508 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 4509 return; 4510 } 4511 4512 // std::abs has overloads which prevent most of the absolute value problems 4513 // from occurring. 4514 if (IsStdAbs) 4515 return; 4516 4517 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 4518 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 4519 4520 // The argument and parameter are the same kind. Check if they are the right 4521 // size. 4522 if (ArgValueKind == ParamValueKind) { 4523 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 4524 return; 4525 4526 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 4527 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 4528 << FDecl << ArgType << ParamType; 4529 4530 if (NewAbsKind == 0) 4531 return; 4532 4533 emitReplacement(*this, Call->getExprLoc(), 4534 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 4535 return; 4536 } 4537 4538 // ArgValueKind != ParamValueKind 4539 // The wrong type of absolute value function was used. Attempt to find the 4540 // proper one. 4541 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 4542 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 4543 if (NewAbsKind == 0) 4544 return; 4545 4546 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 4547 << FDecl << ParamValueKind << ArgValueKind; 4548 4549 emitReplacement(*this, Call->getExprLoc(), 4550 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 4551 return; 4552 } 4553 4554 //===--- CHECK: Standard memory functions ---------------------------------===// 4555 4556 /// \brief Takes the expression passed to the size_t parameter of functions 4557 /// such as memcmp, strncat, etc and warns if it's a comparison. 4558 /// 4559 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 4560 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 4561 IdentifierInfo *FnName, 4562 SourceLocation FnLoc, 4563 SourceLocation RParenLoc) { 4564 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 4565 if (!Size) 4566 return false; 4567 4568 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 4569 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 4570 return false; 4571 4572 SourceRange SizeRange = Size->getSourceRange(); 4573 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 4574 << SizeRange << FnName; 4575 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 4576 << FnName << FixItHint::CreateInsertion( 4577 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 4578 << FixItHint::CreateRemoval(RParenLoc); 4579 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 4580 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 4581 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 4582 ")"); 4583 4584 return true; 4585 } 4586 4587 /// \brief Determine whether the given type is or contains a dynamic class type 4588 /// (e.g., whether it has a vtable). 4589 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 4590 bool &IsContained) { 4591 // Look through array types while ignoring qualifiers. 4592 const Type *Ty = T->getBaseElementTypeUnsafe(); 4593 IsContained = false; 4594 4595 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 4596 RD = RD ? RD->getDefinition() : nullptr; 4597 if (!RD) 4598 return nullptr; 4599 4600 if (RD->isDynamicClass()) 4601 return RD; 4602 4603 // Check all the fields. If any bases were dynamic, the class is dynamic. 4604 // It's impossible for a class to transitively contain itself by value, so 4605 // infinite recursion is impossible. 4606 for (auto *FD : RD->fields()) { 4607 bool SubContained; 4608 if (const CXXRecordDecl *ContainedRD = 4609 getContainedDynamicClass(FD->getType(), SubContained)) { 4610 IsContained = true; 4611 return ContainedRD; 4612 } 4613 } 4614 4615 return nullptr; 4616 } 4617 4618 /// \brief If E is a sizeof expression, returns its argument expression, 4619 /// otherwise returns NULL. 4620 static const Expr *getSizeOfExprArg(const Expr* E) { 4621 if (const UnaryExprOrTypeTraitExpr *SizeOf = 4622 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 4623 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 4624 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 4625 4626 return nullptr; 4627 } 4628 4629 /// \brief If E is a sizeof expression, returns its argument type. 4630 static QualType getSizeOfArgType(const Expr* E) { 4631 if (const UnaryExprOrTypeTraitExpr *SizeOf = 4632 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 4633 if (SizeOf->getKind() == clang::UETT_SizeOf) 4634 return SizeOf->getTypeOfArgument(); 4635 4636 return QualType(); 4637 } 4638 4639 /// \brief Check for dangerous or invalid arguments to memset(). 4640 /// 4641 /// This issues warnings on known problematic, dangerous or unspecified 4642 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 4643 /// function calls. 4644 /// 4645 /// \param Call The call expression to diagnose. 4646 void Sema::CheckMemaccessArguments(const CallExpr *Call, 4647 unsigned BId, 4648 IdentifierInfo *FnName) { 4649 assert(BId != 0); 4650 4651 // It is possible to have a non-standard definition of memset. Validate 4652 // we have enough arguments, and if not, abort further checking. 4653 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 4654 if (Call->getNumArgs() < ExpectedNumArgs) 4655 return; 4656 4657 unsigned LastArg = (BId == Builtin::BImemset || 4658 BId == Builtin::BIstrndup ? 1 : 2); 4659 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 4660 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 4661 4662 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 4663 Call->getLocStart(), Call->getRParenLoc())) 4664 return; 4665 4666 // We have special checking when the length is a sizeof expression. 4667 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 4668 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 4669 llvm::FoldingSetNodeID SizeOfArgID; 4670 4671 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 4672 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 4673 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 4674 4675 QualType DestTy = Dest->getType(); 4676 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 4677 QualType PointeeTy = DestPtrTy->getPointeeType(); 4678 4679 // Never warn about void type pointers. This can be used to suppress 4680 // false positives. 4681 if (PointeeTy->isVoidType()) 4682 continue; 4683 4684 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 4685 // actually comparing the expressions for equality. Because computing the 4686 // expression IDs can be expensive, we only do this if the diagnostic is 4687 // enabled. 4688 if (SizeOfArg && 4689 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 4690 SizeOfArg->getExprLoc())) { 4691 // We only compute IDs for expressions if the warning is enabled, and 4692 // cache the sizeof arg's ID. 4693 if (SizeOfArgID == llvm::FoldingSetNodeID()) 4694 SizeOfArg->Profile(SizeOfArgID, Context, true); 4695 llvm::FoldingSetNodeID DestID; 4696 Dest->Profile(DestID, Context, true); 4697 if (DestID == SizeOfArgID) { 4698 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 4699 // over sizeof(src) as well. 4700 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 4701 StringRef ReadableName = FnName->getName(); 4702 4703 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 4704 if (UnaryOp->getOpcode() == UO_AddrOf) 4705 ActionIdx = 1; // If its an address-of operator, just remove it. 4706 if (!PointeeTy->isIncompleteType() && 4707 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 4708 ActionIdx = 2; // If the pointee's size is sizeof(char), 4709 // suggest an explicit length. 4710 4711 // If the function is defined as a builtin macro, do not show macro 4712 // expansion. 4713 SourceLocation SL = SizeOfArg->getExprLoc(); 4714 SourceRange DSR = Dest->getSourceRange(); 4715 SourceRange SSR = SizeOfArg->getSourceRange(); 4716 SourceManager &SM = getSourceManager(); 4717 4718 if (SM.isMacroArgExpansion(SL)) { 4719 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 4720 SL = SM.getSpellingLoc(SL); 4721 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 4722 SM.getSpellingLoc(DSR.getEnd())); 4723 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 4724 SM.getSpellingLoc(SSR.getEnd())); 4725 } 4726 4727 DiagRuntimeBehavior(SL, SizeOfArg, 4728 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 4729 << ReadableName 4730 << PointeeTy 4731 << DestTy 4732 << DSR 4733 << SSR); 4734 DiagRuntimeBehavior(SL, SizeOfArg, 4735 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 4736 << ActionIdx 4737 << SSR); 4738 4739 break; 4740 } 4741 } 4742 4743 // Also check for cases where the sizeof argument is the exact same 4744 // type as the memory argument, and where it points to a user-defined 4745 // record type. 4746 if (SizeOfArgTy != QualType()) { 4747 if (PointeeTy->isRecordType() && 4748 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 4749 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 4750 PDiag(diag::warn_sizeof_pointer_type_memaccess) 4751 << FnName << SizeOfArgTy << ArgIdx 4752 << PointeeTy << Dest->getSourceRange() 4753 << LenExpr->getSourceRange()); 4754 break; 4755 } 4756 } 4757 4758 // Always complain about dynamic classes. 4759 bool IsContained; 4760 if (const CXXRecordDecl *ContainedRD = 4761 getContainedDynamicClass(PointeeTy, IsContained)) { 4762 4763 unsigned OperationType = 0; 4764 // "overwritten" if we're warning about the destination for any call 4765 // but memcmp; otherwise a verb appropriate to the call. 4766 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 4767 if (BId == Builtin::BImemcpy) 4768 OperationType = 1; 4769 else if(BId == Builtin::BImemmove) 4770 OperationType = 2; 4771 else if (BId == Builtin::BImemcmp) 4772 OperationType = 3; 4773 } 4774 4775 DiagRuntimeBehavior( 4776 Dest->getExprLoc(), Dest, 4777 PDiag(diag::warn_dyn_class_memaccess) 4778 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 4779 << FnName << IsContained << ContainedRD << OperationType 4780 << Call->getCallee()->getSourceRange()); 4781 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 4782 BId != Builtin::BImemset) 4783 DiagRuntimeBehavior( 4784 Dest->getExprLoc(), Dest, 4785 PDiag(diag::warn_arc_object_memaccess) 4786 << ArgIdx << FnName << PointeeTy 4787 << Call->getCallee()->getSourceRange()); 4788 else 4789 continue; 4790 4791 DiagRuntimeBehavior( 4792 Dest->getExprLoc(), Dest, 4793 PDiag(diag::note_bad_memaccess_silence) 4794 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 4795 break; 4796 } 4797 } 4798 } 4799 4800 // A little helper routine: ignore addition and subtraction of integer literals. 4801 // This intentionally does not ignore all integer constant expressions because 4802 // we don't want to remove sizeof(). 4803 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 4804 Ex = Ex->IgnoreParenCasts(); 4805 4806 for (;;) { 4807 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 4808 if (!BO || !BO->isAdditiveOp()) 4809 break; 4810 4811 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 4812 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 4813 4814 if (isa<IntegerLiteral>(RHS)) 4815 Ex = LHS; 4816 else if (isa<IntegerLiteral>(LHS)) 4817 Ex = RHS; 4818 else 4819 break; 4820 } 4821 4822 return Ex; 4823 } 4824 4825 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 4826 ASTContext &Context) { 4827 // Only handle constant-sized or VLAs, but not flexible members. 4828 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 4829 // Only issue the FIXIT for arrays of size > 1. 4830 if (CAT->getSize().getSExtValue() <= 1) 4831 return false; 4832 } else if (!Ty->isVariableArrayType()) { 4833 return false; 4834 } 4835 return true; 4836 } 4837 4838 // Warn if the user has made the 'size' argument to strlcpy or strlcat 4839 // be the size of the source, instead of the destination. 4840 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 4841 IdentifierInfo *FnName) { 4842 4843 // Don't crash if the user has the wrong number of arguments 4844 unsigned NumArgs = Call->getNumArgs(); 4845 if ((NumArgs != 3) && (NumArgs != 4)) 4846 return; 4847 4848 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 4849 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 4850 const Expr *CompareWithSrc = nullptr; 4851 4852 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 4853 Call->getLocStart(), Call->getRParenLoc())) 4854 return; 4855 4856 // Look for 'strlcpy(dst, x, sizeof(x))' 4857 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 4858 CompareWithSrc = Ex; 4859 else { 4860 // Look for 'strlcpy(dst, x, strlen(x))' 4861 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 4862 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 4863 SizeCall->getNumArgs() == 1) 4864 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 4865 } 4866 } 4867 4868 if (!CompareWithSrc) 4869 return; 4870 4871 // Determine if the argument to sizeof/strlen is equal to the source 4872 // argument. In principle there's all kinds of things you could do 4873 // here, for instance creating an == expression and evaluating it with 4874 // EvaluateAsBooleanCondition, but this uses a more direct technique: 4875 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 4876 if (!SrcArgDRE) 4877 return; 4878 4879 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 4880 if (!CompareWithSrcDRE || 4881 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 4882 return; 4883 4884 const Expr *OriginalSizeArg = Call->getArg(2); 4885 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 4886 << OriginalSizeArg->getSourceRange() << FnName; 4887 4888 // Output a FIXIT hint if the destination is an array (rather than a 4889 // pointer to an array). This could be enhanced to handle some 4890 // pointers if we know the actual size, like if DstArg is 'array+2' 4891 // we could say 'sizeof(array)-2'. 4892 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 4893 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 4894 return; 4895 4896 SmallString<128> sizeString; 4897 llvm::raw_svector_ostream OS(sizeString); 4898 OS << "sizeof("; 4899 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 4900 OS << ")"; 4901 4902 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 4903 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 4904 OS.str()); 4905 } 4906 4907 /// Check if two expressions refer to the same declaration. 4908 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 4909 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 4910 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 4911 return D1->getDecl() == D2->getDecl(); 4912 return false; 4913 } 4914 4915 static const Expr *getStrlenExprArg(const Expr *E) { 4916 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 4917 const FunctionDecl *FD = CE->getDirectCallee(); 4918 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 4919 return nullptr; 4920 return CE->getArg(0)->IgnoreParenCasts(); 4921 } 4922 return nullptr; 4923 } 4924 4925 // Warn on anti-patterns as the 'size' argument to strncat. 4926 // The correct size argument should look like following: 4927 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 4928 void Sema::CheckStrncatArguments(const CallExpr *CE, 4929 IdentifierInfo *FnName) { 4930 // Don't crash if the user has the wrong number of arguments. 4931 if (CE->getNumArgs() < 3) 4932 return; 4933 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 4934 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 4935 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 4936 4937 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 4938 CE->getRParenLoc())) 4939 return; 4940 4941 // Identify common expressions, which are wrongly used as the size argument 4942 // to strncat and may lead to buffer overflows. 4943 unsigned PatternType = 0; 4944 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 4945 // - sizeof(dst) 4946 if (referToTheSameDecl(SizeOfArg, DstArg)) 4947 PatternType = 1; 4948 // - sizeof(src) 4949 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 4950 PatternType = 2; 4951 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 4952 if (BE->getOpcode() == BO_Sub) { 4953 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 4954 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 4955 // - sizeof(dst) - strlen(dst) 4956 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 4957 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 4958 PatternType = 1; 4959 // - sizeof(src) - (anything) 4960 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 4961 PatternType = 2; 4962 } 4963 } 4964 4965 if (PatternType == 0) 4966 return; 4967 4968 // Generate the diagnostic. 4969 SourceLocation SL = LenArg->getLocStart(); 4970 SourceRange SR = LenArg->getSourceRange(); 4971 SourceManager &SM = getSourceManager(); 4972 4973 // If the function is defined as a builtin macro, do not show macro expansion. 4974 if (SM.isMacroArgExpansion(SL)) { 4975 SL = SM.getSpellingLoc(SL); 4976 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 4977 SM.getSpellingLoc(SR.getEnd())); 4978 } 4979 4980 // Check if the destination is an array (rather than a pointer to an array). 4981 QualType DstTy = DstArg->getType(); 4982 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 4983 Context); 4984 if (!isKnownSizeArray) { 4985 if (PatternType == 1) 4986 Diag(SL, diag::warn_strncat_wrong_size) << SR; 4987 else 4988 Diag(SL, diag::warn_strncat_src_size) << SR; 4989 return; 4990 } 4991 4992 if (PatternType == 1) 4993 Diag(SL, diag::warn_strncat_large_size) << SR; 4994 else 4995 Diag(SL, diag::warn_strncat_src_size) << SR; 4996 4997 SmallString<128> sizeString; 4998 llvm::raw_svector_ostream OS(sizeString); 4999 OS << "sizeof("; 5000 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 5001 OS << ") - "; 5002 OS << "strlen("; 5003 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 5004 OS << ") - 1"; 5005 5006 Diag(SL, diag::note_strncat_wrong_size) 5007 << FixItHint::CreateReplacement(SR, OS.str()); 5008 } 5009 5010 //===--- CHECK: Return Address of Stack Variable --------------------------===// 5011 5012 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 5013 Decl *ParentDecl); 5014 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars, 5015 Decl *ParentDecl); 5016 5017 /// CheckReturnStackAddr - Check if a return statement returns the address 5018 /// of a stack variable. 5019 static void 5020 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 5021 SourceLocation ReturnLoc) { 5022 5023 Expr *stackE = nullptr; 5024 SmallVector<DeclRefExpr *, 8> refVars; 5025 5026 // Perform checking for returned stack addresses, local blocks, 5027 // label addresses or references to temporaries. 5028 if (lhsType->isPointerType() || 5029 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 5030 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 5031 } else if (lhsType->isReferenceType()) { 5032 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 5033 } 5034 5035 if (!stackE) 5036 return; // Nothing suspicious was found. 5037 5038 SourceLocation diagLoc; 5039 SourceRange diagRange; 5040 if (refVars.empty()) { 5041 diagLoc = stackE->getLocStart(); 5042 diagRange = stackE->getSourceRange(); 5043 } else { 5044 // We followed through a reference variable. 'stackE' contains the 5045 // problematic expression but we will warn at the return statement pointing 5046 // at the reference variable. We will later display the "trail" of 5047 // reference variables using notes. 5048 diagLoc = refVars[0]->getLocStart(); 5049 diagRange = refVars[0]->getSourceRange(); 5050 } 5051 5052 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var. 5053 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref 5054 : diag::warn_ret_stack_addr) 5055 << DR->getDecl()->getDeclName() << diagRange; 5056 } else if (isa<BlockExpr>(stackE)) { // local block. 5057 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 5058 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 5059 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 5060 } else { // local temporary. 5061 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref 5062 : diag::warn_ret_local_temp_addr) 5063 << diagRange; 5064 } 5065 5066 // Display the "trail" of reference variables that we followed until we 5067 // found the problematic expression using notes. 5068 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 5069 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 5070 // If this var binds to another reference var, show the range of the next 5071 // var, otherwise the var binds to the problematic expression, in which case 5072 // show the range of the expression. 5073 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange() 5074 : stackE->getSourceRange(); 5075 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 5076 << VD->getDeclName() << range; 5077 } 5078 } 5079 5080 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 5081 /// check if the expression in a return statement evaluates to an address 5082 /// to a location on the stack, a local block, an address of a label, or a 5083 /// reference to local temporary. The recursion is used to traverse the 5084 /// AST of the return expression, with recursion backtracking when we 5085 /// encounter a subexpression that (1) clearly does not lead to one of the 5086 /// above problematic expressions (2) is something we cannot determine leads to 5087 /// a problematic expression based on such local checking. 5088 /// 5089 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 5090 /// the expression that they point to. Such variables are added to the 5091 /// 'refVars' vector so that we know what the reference variable "trail" was. 5092 /// 5093 /// EvalAddr processes expressions that are pointers that are used as 5094 /// references (and not L-values). EvalVal handles all other values. 5095 /// At the base case of the recursion is a check for the above problematic 5096 /// expressions. 5097 /// 5098 /// This implementation handles: 5099 /// 5100 /// * pointer-to-pointer casts 5101 /// * implicit conversions from array references to pointers 5102 /// * taking the address of fields 5103 /// * arbitrary interplay between "&" and "*" operators 5104 /// * pointer arithmetic from an address of a stack variable 5105 /// * taking the address of an array element where the array is on the stack 5106 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 5107 Decl *ParentDecl) { 5108 if (E->isTypeDependent()) 5109 return nullptr; 5110 5111 // We should only be called for evaluating pointer expressions. 5112 assert((E->getType()->isAnyPointerType() || 5113 E->getType()->isBlockPointerType() || 5114 E->getType()->isObjCQualifiedIdType()) && 5115 "EvalAddr only works on pointers"); 5116 5117 E = E->IgnoreParens(); 5118 5119 // Our "symbolic interpreter" is just a dispatch off the currently 5120 // viewed AST node. We then recursively traverse the AST by calling 5121 // EvalAddr and EvalVal appropriately. 5122 switch (E->getStmtClass()) { 5123 case Stmt::DeclRefExprClass: { 5124 DeclRefExpr *DR = cast<DeclRefExpr>(E); 5125 5126 // If we leave the immediate function, the lifetime isn't about to end. 5127 if (DR->refersToEnclosingVariableOrCapture()) 5128 return nullptr; 5129 5130 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 5131 // If this is a reference variable, follow through to the expression that 5132 // it points to. 5133 if (V->hasLocalStorage() && 5134 V->getType()->isReferenceType() && V->hasInit()) { 5135 // Add the reference variable to the "trail". 5136 refVars.push_back(DR); 5137 return EvalAddr(V->getInit(), refVars, ParentDecl); 5138 } 5139 5140 return nullptr; 5141 } 5142 5143 case Stmt::UnaryOperatorClass: { 5144 // The only unary operator that make sense to handle here 5145 // is AddrOf. All others don't make sense as pointers. 5146 UnaryOperator *U = cast<UnaryOperator>(E); 5147 5148 if (U->getOpcode() == UO_AddrOf) 5149 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 5150 else 5151 return nullptr; 5152 } 5153 5154 case Stmt::BinaryOperatorClass: { 5155 // Handle pointer arithmetic. All other binary operators are not valid 5156 // in this context. 5157 BinaryOperator *B = cast<BinaryOperator>(E); 5158 BinaryOperatorKind op = B->getOpcode(); 5159 5160 if (op != BO_Add && op != BO_Sub) 5161 return nullptr; 5162 5163 Expr *Base = B->getLHS(); 5164 5165 // Determine which argument is the real pointer base. It could be 5166 // the RHS argument instead of the LHS. 5167 if (!Base->getType()->isPointerType()) Base = B->getRHS(); 5168 5169 assert (Base->getType()->isPointerType()); 5170 return EvalAddr(Base, refVars, ParentDecl); 5171 } 5172 5173 // For conditional operators we need to see if either the LHS or RHS are 5174 // valid DeclRefExpr*s. If one of them is valid, we return it. 5175 case Stmt::ConditionalOperatorClass: { 5176 ConditionalOperator *C = cast<ConditionalOperator>(E); 5177 5178 // Handle the GNU extension for missing LHS. 5179 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 5180 if (Expr *LHSExpr = C->getLHS()) { 5181 // In C++, we can have a throw-expression, which has 'void' type. 5182 if (!LHSExpr->getType()->isVoidType()) 5183 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 5184 return LHS; 5185 } 5186 5187 // In C++, we can have a throw-expression, which has 'void' type. 5188 if (C->getRHS()->getType()->isVoidType()) 5189 return nullptr; 5190 5191 return EvalAddr(C->getRHS(), refVars, ParentDecl); 5192 } 5193 5194 case Stmt::BlockExprClass: 5195 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 5196 return E; // local block. 5197 return nullptr; 5198 5199 case Stmt::AddrLabelExprClass: 5200 return E; // address of label. 5201 5202 case Stmt::ExprWithCleanupsClass: 5203 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 5204 ParentDecl); 5205 5206 // For casts, we need to handle conversions from arrays to 5207 // pointer values, and pointer-to-pointer conversions. 5208 case Stmt::ImplicitCastExprClass: 5209 case Stmt::CStyleCastExprClass: 5210 case Stmt::CXXFunctionalCastExprClass: 5211 case Stmt::ObjCBridgedCastExprClass: 5212 case Stmt::CXXStaticCastExprClass: 5213 case Stmt::CXXDynamicCastExprClass: 5214 case Stmt::CXXConstCastExprClass: 5215 case Stmt::CXXReinterpretCastExprClass: { 5216 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 5217 switch (cast<CastExpr>(E)->getCastKind()) { 5218 case CK_LValueToRValue: 5219 case CK_NoOp: 5220 case CK_BaseToDerived: 5221 case CK_DerivedToBase: 5222 case CK_UncheckedDerivedToBase: 5223 case CK_Dynamic: 5224 case CK_CPointerToObjCPointerCast: 5225 case CK_BlockPointerToObjCPointerCast: 5226 case CK_AnyPointerToBlockPointerCast: 5227 return EvalAddr(SubExpr, refVars, ParentDecl); 5228 5229 case CK_ArrayToPointerDecay: 5230 return EvalVal(SubExpr, refVars, ParentDecl); 5231 5232 case CK_BitCast: 5233 if (SubExpr->getType()->isAnyPointerType() || 5234 SubExpr->getType()->isBlockPointerType() || 5235 SubExpr->getType()->isObjCQualifiedIdType()) 5236 return EvalAddr(SubExpr, refVars, ParentDecl); 5237 else 5238 return nullptr; 5239 5240 default: 5241 return nullptr; 5242 } 5243 } 5244 5245 case Stmt::MaterializeTemporaryExprClass: 5246 if (Expr *Result = EvalAddr( 5247 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 5248 refVars, ParentDecl)) 5249 return Result; 5250 5251 return E; 5252 5253 // Everything else: we simply don't reason about them. 5254 default: 5255 return nullptr; 5256 } 5257 } 5258 5259 5260 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 5261 /// See the comments for EvalAddr for more details. 5262 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars, 5263 Decl *ParentDecl) { 5264 do { 5265 // We should only be called for evaluating non-pointer expressions, or 5266 // expressions with a pointer type that are not used as references but instead 5267 // are l-values (e.g., DeclRefExpr with a pointer type). 5268 5269 // Our "symbolic interpreter" is just a dispatch off the currently 5270 // viewed AST node. We then recursively traverse the AST by calling 5271 // EvalAddr and EvalVal appropriately. 5272 5273 E = E->IgnoreParens(); 5274 switch (E->getStmtClass()) { 5275 case Stmt::ImplicitCastExprClass: { 5276 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 5277 if (IE->getValueKind() == VK_LValue) { 5278 E = IE->getSubExpr(); 5279 continue; 5280 } 5281 return nullptr; 5282 } 5283 5284 case Stmt::ExprWithCleanupsClass: 5285 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl); 5286 5287 case Stmt::DeclRefExprClass: { 5288 // When we hit a DeclRefExpr we are looking at code that refers to a 5289 // variable's name. If it's not a reference variable we check if it has 5290 // local storage within the function, and if so, return the expression. 5291 DeclRefExpr *DR = cast<DeclRefExpr>(E); 5292 5293 // If we leave the immediate function, the lifetime isn't about to end. 5294 if (DR->refersToEnclosingVariableOrCapture()) 5295 return nullptr; 5296 5297 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 5298 // Check if it refers to itself, e.g. "int& i = i;". 5299 if (V == ParentDecl) 5300 return DR; 5301 5302 if (V->hasLocalStorage()) { 5303 if (!V->getType()->isReferenceType()) 5304 return DR; 5305 5306 // Reference variable, follow through to the expression that 5307 // it points to. 5308 if (V->hasInit()) { 5309 // Add the reference variable to the "trail". 5310 refVars.push_back(DR); 5311 return EvalVal(V->getInit(), refVars, V); 5312 } 5313 } 5314 } 5315 5316 return nullptr; 5317 } 5318 5319 case Stmt::UnaryOperatorClass: { 5320 // The only unary operator that make sense to handle here 5321 // is Deref. All others don't resolve to a "name." This includes 5322 // handling all sorts of rvalues passed to a unary operator. 5323 UnaryOperator *U = cast<UnaryOperator>(E); 5324 5325 if (U->getOpcode() == UO_Deref) 5326 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 5327 5328 return nullptr; 5329 } 5330 5331 case Stmt::ArraySubscriptExprClass: { 5332 // Array subscripts are potential references to data on the stack. We 5333 // retrieve the DeclRefExpr* for the array variable if it indeed 5334 // has local storage. 5335 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl); 5336 } 5337 5338 case Stmt::ConditionalOperatorClass: { 5339 // For conditional operators we need to see if either the LHS or RHS are 5340 // non-NULL Expr's. If one is non-NULL, we return it. 5341 ConditionalOperator *C = cast<ConditionalOperator>(E); 5342 5343 // Handle the GNU extension for missing LHS. 5344 if (Expr *LHSExpr = C->getLHS()) { 5345 // In C++, we can have a throw-expression, which has 'void' type. 5346 if (!LHSExpr->getType()->isVoidType()) 5347 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 5348 return LHS; 5349 } 5350 5351 // In C++, we can have a throw-expression, which has 'void' type. 5352 if (C->getRHS()->getType()->isVoidType()) 5353 return nullptr; 5354 5355 return EvalVal(C->getRHS(), refVars, ParentDecl); 5356 } 5357 5358 // Accesses to members are potential references to data on the stack. 5359 case Stmt::MemberExprClass: { 5360 MemberExpr *M = cast<MemberExpr>(E); 5361 5362 // Check for indirect access. We only want direct field accesses. 5363 if (M->isArrow()) 5364 return nullptr; 5365 5366 // Check whether the member type is itself a reference, in which case 5367 // we're not going to refer to the member, but to what the member refers to. 5368 if (M->getMemberDecl()->getType()->isReferenceType()) 5369 return nullptr; 5370 5371 return EvalVal(M->getBase(), refVars, ParentDecl); 5372 } 5373 5374 case Stmt::MaterializeTemporaryExprClass: 5375 if (Expr *Result = EvalVal( 5376 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 5377 refVars, ParentDecl)) 5378 return Result; 5379 5380 return E; 5381 5382 default: 5383 // Check that we don't return or take the address of a reference to a 5384 // temporary. This is only useful in C++. 5385 if (!E->isTypeDependent() && E->isRValue()) 5386 return E; 5387 5388 // Everything else: we simply don't reason about them. 5389 return nullptr; 5390 } 5391 } while (true); 5392 } 5393 5394 void 5395 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 5396 SourceLocation ReturnLoc, 5397 bool isObjCMethod, 5398 const AttrVec *Attrs, 5399 const FunctionDecl *FD) { 5400 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 5401 5402 // Check if the return value is null but should not be. 5403 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) && 5404 CheckNonNullExpr(*this, RetValExp)) 5405 Diag(ReturnLoc, diag::warn_null_ret) 5406 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 5407 5408 // C++11 [basic.stc.dynamic.allocation]p4: 5409 // If an allocation function declared with a non-throwing 5410 // exception-specification fails to allocate storage, it shall return 5411 // a null pointer. Any other allocation function that fails to allocate 5412 // storage shall indicate failure only by throwing an exception [...] 5413 if (FD) { 5414 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 5415 if (Op == OO_New || Op == OO_Array_New) { 5416 const FunctionProtoType *Proto 5417 = FD->getType()->castAs<FunctionProtoType>(); 5418 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 5419 CheckNonNullExpr(*this, RetValExp)) 5420 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 5421 << FD << getLangOpts().CPlusPlus11; 5422 } 5423 } 5424 } 5425 5426 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 5427 5428 /// Check for comparisons of floating point operands using != and ==. 5429 /// Issue a warning if these are no self-comparisons, as they are not likely 5430 /// to do what the programmer intended. 5431 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 5432 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 5433 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 5434 5435 // Special case: check for x == x (which is OK). 5436 // Do not emit warnings for such cases. 5437 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 5438 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 5439 if (DRL->getDecl() == DRR->getDecl()) 5440 return; 5441 5442 5443 // Special case: check for comparisons against literals that can be exactly 5444 // represented by APFloat. In such cases, do not emit a warning. This 5445 // is a heuristic: often comparison against such literals are used to 5446 // detect if a value in a variable has not changed. This clearly can 5447 // lead to false negatives. 5448 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 5449 if (FLL->isExact()) 5450 return; 5451 } else 5452 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 5453 if (FLR->isExact()) 5454 return; 5455 5456 // Check for comparisons with builtin types. 5457 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 5458 if (CL->getBuiltinCallee()) 5459 return; 5460 5461 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 5462 if (CR->getBuiltinCallee()) 5463 return; 5464 5465 // Emit the diagnostic. 5466 Diag(Loc, diag::warn_floatingpoint_eq) 5467 << LHS->getSourceRange() << RHS->getSourceRange(); 5468 } 5469 5470 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 5471 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 5472 5473 namespace { 5474 5475 /// Structure recording the 'active' range of an integer-valued 5476 /// expression. 5477 struct IntRange { 5478 /// The number of bits active in the int. 5479 unsigned Width; 5480 5481 /// True if the int is known not to have negative values. 5482 bool NonNegative; 5483 5484 IntRange(unsigned Width, bool NonNegative) 5485 : Width(Width), NonNegative(NonNegative) 5486 {} 5487 5488 /// Returns the range of the bool type. 5489 static IntRange forBoolType() { 5490 return IntRange(1, true); 5491 } 5492 5493 /// Returns the range of an opaque value of the given integral type. 5494 static IntRange forValueOfType(ASTContext &C, QualType T) { 5495 return forValueOfCanonicalType(C, 5496 T->getCanonicalTypeInternal().getTypePtr()); 5497 } 5498 5499 /// Returns the range of an opaque value of a canonical integral type. 5500 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 5501 assert(T->isCanonicalUnqualified()); 5502 5503 if (const VectorType *VT = dyn_cast<VectorType>(T)) 5504 T = VT->getElementType().getTypePtr(); 5505 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 5506 T = CT->getElementType().getTypePtr(); 5507 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 5508 T = AT->getValueType().getTypePtr(); 5509 5510 // For enum types, use the known bit width of the enumerators. 5511 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 5512 EnumDecl *Enum = ET->getDecl(); 5513 if (!Enum->isCompleteDefinition()) 5514 return IntRange(C.getIntWidth(QualType(T, 0)), false); 5515 5516 unsigned NumPositive = Enum->getNumPositiveBits(); 5517 unsigned NumNegative = Enum->getNumNegativeBits(); 5518 5519 if (NumNegative == 0) 5520 return IntRange(NumPositive, true/*NonNegative*/); 5521 else 5522 return IntRange(std::max(NumPositive + 1, NumNegative), 5523 false/*NonNegative*/); 5524 } 5525 5526 const BuiltinType *BT = cast<BuiltinType>(T); 5527 assert(BT->isInteger()); 5528 5529 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 5530 } 5531 5532 /// Returns the "target" range of a canonical integral type, i.e. 5533 /// the range of values expressible in the type. 5534 /// 5535 /// This matches forValueOfCanonicalType except that enums have the 5536 /// full range of their type, not the range of their enumerators. 5537 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 5538 assert(T->isCanonicalUnqualified()); 5539 5540 if (const VectorType *VT = dyn_cast<VectorType>(T)) 5541 T = VT->getElementType().getTypePtr(); 5542 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 5543 T = CT->getElementType().getTypePtr(); 5544 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 5545 T = AT->getValueType().getTypePtr(); 5546 if (const EnumType *ET = dyn_cast<EnumType>(T)) 5547 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 5548 5549 const BuiltinType *BT = cast<BuiltinType>(T); 5550 assert(BT->isInteger()); 5551 5552 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 5553 } 5554 5555 /// Returns the supremum of two ranges: i.e. their conservative merge. 5556 static IntRange join(IntRange L, IntRange R) { 5557 return IntRange(std::max(L.Width, R.Width), 5558 L.NonNegative && R.NonNegative); 5559 } 5560 5561 /// Returns the infinum of two ranges: i.e. their aggressive merge. 5562 static IntRange meet(IntRange L, IntRange R) { 5563 return IntRange(std::min(L.Width, R.Width), 5564 L.NonNegative || R.NonNegative); 5565 } 5566 }; 5567 5568 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 5569 unsigned MaxWidth) { 5570 if (value.isSigned() && value.isNegative()) 5571 return IntRange(value.getMinSignedBits(), false); 5572 5573 if (value.getBitWidth() > MaxWidth) 5574 value = value.trunc(MaxWidth); 5575 5576 // isNonNegative() just checks the sign bit without considering 5577 // signedness. 5578 return IntRange(value.getActiveBits(), true); 5579 } 5580 5581 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 5582 unsigned MaxWidth) { 5583 if (result.isInt()) 5584 return GetValueRange(C, result.getInt(), MaxWidth); 5585 5586 if (result.isVector()) { 5587 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 5588 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 5589 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 5590 R = IntRange::join(R, El); 5591 } 5592 return R; 5593 } 5594 5595 if (result.isComplexInt()) { 5596 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 5597 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 5598 return IntRange::join(R, I); 5599 } 5600 5601 // This can happen with lossless casts to intptr_t of "based" lvalues. 5602 // Assume it might use arbitrary bits. 5603 // FIXME: The only reason we need to pass the type in here is to get 5604 // the sign right on this one case. It would be nice if APValue 5605 // preserved this. 5606 assert(result.isLValue() || result.isAddrLabelDiff()); 5607 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 5608 } 5609 5610 static QualType GetExprType(Expr *E) { 5611 QualType Ty = E->getType(); 5612 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 5613 Ty = AtomicRHS->getValueType(); 5614 return Ty; 5615 } 5616 5617 /// Pseudo-evaluate the given integer expression, estimating the 5618 /// range of values it might take. 5619 /// 5620 /// \param MaxWidth - the width to which the value will be truncated 5621 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { 5622 E = E->IgnoreParens(); 5623 5624 // Try a full evaluation first. 5625 Expr::EvalResult result; 5626 if (E->EvaluateAsRValue(result, C)) 5627 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 5628 5629 // I think we only want to look through implicit casts here; if the 5630 // user has an explicit widening cast, we should treat the value as 5631 // being of the new, wider type. 5632 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 5633 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 5634 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 5635 5636 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 5637 5638 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast); 5639 5640 // Assume that non-integer casts can span the full range of the type. 5641 if (!isIntegerCast) 5642 return OutputTypeRange; 5643 5644 IntRange SubRange 5645 = GetExprRange(C, CE->getSubExpr(), 5646 std::min(MaxWidth, OutputTypeRange.Width)); 5647 5648 // Bail out if the subexpr's range is as wide as the cast type. 5649 if (SubRange.Width >= OutputTypeRange.Width) 5650 return OutputTypeRange; 5651 5652 // Otherwise, we take the smaller width, and we're non-negative if 5653 // either the output type or the subexpr is. 5654 return IntRange(SubRange.Width, 5655 SubRange.NonNegative || OutputTypeRange.NonNegative); 5656 } 5657 5658 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 5659 // If we can fold the condition, just take that operand. 5660 bool CondResult; 5661 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 5662 return GetExprRange(C, CondResult ? CO->getTrueExpr() 5663 : CO->getFalseExpr(), 5664 MaxWidth); 5665 5666 // Otherwise, conservatively merge. 5667 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 5668 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 5669 return IntRange::join(L, R); 5670 } 5671 5672 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5673 switch (BO->getOpcode()) { 5674 5675 // Boolean-valued operations are single-bit and positive. 5676 case BO_LAnd: 5677 case BO_LOr: 5678 case BO_LT: 5679 case BO_GT: 5680 case BO_LE: 5681 case BO_GE: 5682 case BO_EQ: 5683 case BO_NE: 5684 return IntRange::forBoolType(); 5685 5686 // The type of the assignments is the type of the LHS, so the RHS 5687 // is not necessarily the same type. 5688 case BO_MulAssign: 5689 case BO_DivAssign: 5690 case BO_RemAssign: 5691 case BO_AddAssign: 5692 case BO_SubAssign: 5693 case BO_XorAssign: 5694 case BO_OrAssign: 5695 // TODO: bitfields? 5696 return IntRange::forValueOfType(C, GetExprType(E)); 5697 5698 // Simple assignments just pass through the RHS, which will have 5699 // been coerced to the LHS type. 5700 case BO_Assign: 5701 // TODO: bitfields? 5702 return GetExprRange(C, BO->getRHS(), MaxWidth); 5703 5704 // Operations with opaque sources are black-listed. 5705 case BO_PtrMemD: 5706 case BO_PtrMemI: 5707 return IntRange::forValueOfType(C, GetExprType(E)); 5708 5709 // Bitwise-and uses the *infinum* of the two source ranges. 5710 case BO_And: 5711 case BO_AndAssign: 5712 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 5713 GetExprRange(C, BO->getRHS(), MaxWidth)); 5714 5715 // Left shift gets black-listed based on a judgement call. 5716 case BO_Shl: 5717 // ...except that we want to treat '1 << (blah)' as logically 5718 // positive. It's an important idiom. 5719 if (IntegerLiteral *I 5720 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 5721 if (I->getValue() == 1) { 5722 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 5723 return IntRange(R.Width, /*NonNegative*/ true); 5724 } 5725 } 5726 // fallthrough 5727 5728 case BO_ShlAssign: 5729 return IntRange::forValueOfType(C, GetExprType(E)); 5730 5731 // Right shift by a constant can narrow its left argument. 5732 case BO_Shr: 5733 case BO_ShrAssign: { 5734 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 5735 5736 // If the shift amount is a positive constant, drop the width by 5737 // that much. 5738 llvm::APSInt shift; 5739 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 5740 shift.isNonNegative()) { 5741 unsigned zext = shift.getZExtValue(); 5742 if (zext >= L.Width) 5743 L.Width = (L.NonNegative ? 0 : 1); 5744 else 5745 L.Width -= zext; 5746 } 5747 5748 return L; 5749 } 5750 5751 // Comma acts as its right operand. 5752 case BO_Comma: 5753 return GetExprRange(C, BO->getRHS(), MaxWidth); 5754 5755 // Black-list pointer subtractions. 5756 case BO_Sub: 5757 if (BO->getLHS()->getType()->isPointerType()) 5758 return IntRange::forValueOfType(C, GetExprType(E)); 5759 break; 5760 5761 // The width of a division result is mostly determined by the size 5762 // of the LHS. 5763 case BO_Div: { 5764 // Don't 'pre-truncate' the operands. 5765 unsigned opWidth = C.getIntWidth(GetExprType(E)); 5766 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 5767 5768 // If the divisor is constant, use that. 5769 llvm::APSInt divisor; 5770 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 5771 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 5772 if (log2 >= L.Width) 5773 L.Width = (L.NonNegative ? 0 : 1); 5774 else 5775 L.Width = std::min(L.Width - log2, MaxWidth); 5776 return L; 5777 } 5778 5779 // Otherwise, just use the LHS's width. 5780 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 5781 return IntRange(L.Width, L.NonNegative && R.NonNegative); 5782 } 5783 5784 // The result of a remainder can't be larger than the result of 5785 // either side. 5786 case BO_Rem: { 5787 // Don't 'pre-truncate' the operands. 5788 unsigned opWidth = C.getIntWidth(GetExprType(E)); 5789 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 5790 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 5791 5792 IntRange meet = IntRange::meet(L, R); 5793 meet.Width = std::min(meet.Width, MaxWidth); 5794 return meet; 5795 } 5796 5797 // The default behavior is okay for these. 5798 case BO_Mul: 5799 case BO_Add: 5800 case BO_Xor: 5801 case BO_Or: 5802 break; 5803 } 5804 5805 // The default case is to treat the operation as if it were closed 5806 // on the narrowest type that encompasses both operands. 5807 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 5808 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 5809 return IntRange::join(L, R); 5810 } 5811 5812 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 5813 switch (UO->getOpcode()) { 5814 // Boolean-valued operations are white-listed. 5815 case UO_LNot: 5816 return IntRange::forBoolType(); 5817 5818 // Operations with opaque sources are black-listed. 5819 case UO_Deref: 5820 case UO_AddrOf: // should be impossible 5821 return IntRange::forValueOfType(C, GetExprType(E)); 5822 5823 default: 5824 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 5825 } 5826 } 5827 5828 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 5829 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 5830 5831 if (FieldDecl *BitField = E->getSourceBitField()) 5832 return IntRange(BitField->getBitWidthValue(C), 5833 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 5834 5835 return IntRange::forValueOfType(C, GetExprType(E)); 5836 } 5837 5838 static IntRange GetExprRange(ASTContext &C, Expr *E) { 5839 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 5840 } 5841 5842 /// Checks whether the given value, which currently has the given 5843 /// source semantics, has the same value when coerced through the 5844 /// target semantics. 5845 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 5846 const llvm::fltSemantics &Src, 5847 const llvm::fltSemantics &Tgt) { 5848 llvm::APFloat truncated = value; 5849 5850 bool ignored; 5851 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 5852 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 5853 5854 return truncated.bitwiseIsEqual(value); 5855 } 5856 5857 /// Checks whether the given value, which currently has the given 5858 /// source semantics, has the same value when coerced through the 5859 /// target semantics. 5860 /// 5861 /// The value might be a vector of floats (or a complex number). 5862 static bool IsSameFloatAfterCast(const APValue &value, 5863 const llvm::fltSemantics &Src, 5864 const llvm::fltSemantics &Tgt) { 5865 if (value.isFloat()) 5866 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 5867 5868 if (value.isVector()) { 5869 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 5870 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 5871 return false; 5872 return true; 5873 } 5874 5875 assert(value.isComplexFloat()); 5876 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 5877 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 5878 } 5879 5880 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 5881 5882 static bool IsZero(Sema &S, Expr *E) { 5883 // Suppress cases where we are comparing against an enum constant. 5884 if (const DeclRefExpr *DR = 5885 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 5886 if (isa<EnumConstantDecl>(DR->getDecl())) 5887 return false; 5888 5889 // Suppress cases where the '0' value is expanded from a macro. 5890 if (E->getLocStart().isMacroID()) 5891 return false; 5892 5893 llvm::APSInt Value; 5894 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 5895 } 5896 5897 static bool HasEnumType(Expr *E) { 5898 // Strip off implicit integral promotions. 5899 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5900 if (ICE->getCastKind() != CK_IntegralCast && 5901 ICE->getCastKind() != CK_NoOp) 5902 break; 5903 E = ICE->getSubExpr(); 5904 } 5905 5906 return E->getType()->isEnumeralType(); 5907 } 5908 5909 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 5910 // Disable warning in template instantiations. 5911 if (!S.ActiveTemplateInstantiations.empty()) 5912 return; 5913 5914 BinaryOperatorKind op = E->getOpcode(); 5915 if (E->isValueDependent()) 5916 return; 5917 5918 if (op == BO_LT && IsZero(S, E->getRHS())) { 5919 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 5920 << "< 0" << "false" << HasEnumType(E->getLHS()) 5921 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5922 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 5923 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 5924 << ">= 0" << "true" << HasEnumType(E->getLHS()) 5925 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5926 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 5927 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 5928 << "0 >" << "false" << HasEnumType(E->getRHS()) 5929 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5930 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 5931 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 5932 << "0 <=" << "true" << HasEnumType(E->getRHS()) 5933 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 5934 } 5935 } 5936 5937 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, 5938 Expr *Constant, Expr *Other, 5939 llvm::APSInt Value, 5940 bool RhsConstant) { 5941 // Disable warning in template instantiations. 5942 if (!S.ActiveTemplateInstantiations.empty()) 5943 return; 5944 5945 // TODO: Investigate using GetExprRange() to get tighter bounds 5946 // on the bit ranges. 5947 QualType OtherT = Other->getType(); 5948 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT)) 5949 OtherT = AT->getValueType(); 5950 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 5951 unsigned OtherWidth = OtherRange.Width; 5952 5953 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 5954 5955 // 0 values are handled later by CheckTrivialUnsignedComparison(). 5956 if ((Value == 0) && (!OtherIsBooleanType)) 5957 return; 5958 5959 BinaryOperatorKind op = E->getOpcode(); 5960 bool IsTrue = true; 5961 5962 // Used for diagnostic printout. 5963 enum { 5964 LiteralConstant = 0, 5965 CXXBoolLiteralTrue, 5966 CXXBoolLiteralFalse 5967 } LiteralOrBoolConstant = LiteralConstant; 5968 5969 if (!OtherIsBooleanType) { 5970 QualType ConstantT = Constant->getType(); 5971 QualType CommonT = E->getLHS()->getType(); 5972 5973 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 5974 return; 5975 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 5976 "comparison with non-integer type"); 5977 5978 bool ConstantSigned = ConstantT->isSignedIntegerType(); 5979 bool CommonSigned = CommonT->isSignedIntegerType(); 5980 5981 bool EqualityOnly = false; 5982 5983 if (CommonSigned) { 5984 // The common type is signed, therefore no signed to unsigned conversion. 5985 if (!OtherRange.NonNegative) { 5986 // Check that the constant is representable in type OtherT. 5987 if (ConstantSigned) { 5988 if (OtherWidth >= Value.getMinSignedBits()) 5989 return; 5990 } else { // !ConstantSigned 5991 if (OtherWidth >= Value.getActiveBits() + 1) 5992 return; 5993 } 5994 } else { // !OtherSigned 5995 // Check that the constant is representable in type OtherT. 5996 // Negative values are out of range. 5997 if (ConstantSigned) { 5998 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 5999 return; 6000 } else { // !ConstantSigned 6001 if (OtherWidth >= Value.getActiveBits()) 6002 return; 6003 } 6004 } 6005 } else { // !CommonSigned 6006 if (OtherRange.NonNegative) { 6007 if (OtherWidth >= Value.getActiveBits()) 6008 return; 6009 } else { // OtherSigned 6010 assert(!ConstantSigned && 6011 "Two signed types converted to unsigned types."); 6012 // Check to see if the constant is representable in OtherT. 6013 if (OtherWidth > Value.getActiveBits()) 6014 return; 6015 // Check to see if the constant is equivalent to a negative value 6016 // cast to CommonT. 6017 if (S.Context.getIntWidth(ConstantT) == 6018 S.Context.getIntWidth(CommonT) && 6019 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 6020 return; 6021 // The constant value rests between values that OtherT can represent 6022 // after conversion. Relational comparison still works, but equality 6023 // comparisons will be tautological. 6024 EqualityOnly = true; 6025 } 6026 } 6027 6028 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 6029 6030 if (op == BO_EQ || op == BO_NE) { 6031 IsTrue = op == BO_NE; 6032 } else if (EqualityOnly) { 6033 return; 6034 } else if (RhsConstant) { 6035 if (op == BO_GT || op == BO_GE) 6036 IsTrue = !PositiveConstant; 6037 else // op == BO_LT || op == BO_LE 6038 IsTrue = PositiveConstant; 6039 } else { 6040 if (op == BO_LT || op == BO_LE) 6041 IsTrue = !PositiveConstant; 6042 else // op == BO_GT || op == BO_GE 6043 IsTrue = PositiveConstant; 6044 } 6045 } else { 6046 // Other isKnownToHaveBooleanValue 6047 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 6048 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 6049 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 6050 6051 static const struct LinkedConditions { 6052 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 6053 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 6054 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 6055 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 6056 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 6057 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 6058 6059 } TruthTable = { 6060 // Constant on LHS. | Constant on RHS. | 6061 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 6062 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 6063 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 6064 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 6065 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 6066 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 6067 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 6068 }; 6069 6070 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 6071 6072 enum ConstantValue ConstVal = Zero; 6073 if (Value.isUnsigned() || Value.isNonNegative()) { 6074 if (Value == 0) { 6075 LiteralOrBoolConstant = 6076 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 6077 ConstVal = Zero; 6078 } else if (Value == 1) { 6079 LiteralOrBoolConstant = 6080 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 6081 ConstVal = One; 6082 } else { 6083 LiteralOrBoolConstant = LiteralConstant; 6084 ConstVal = GT_One; 6085 } 6086 } else { 6087 ConstVal = LT_Zero; 6088 } 6089 6090 CompareBoolWithConstantResult CmpRes; 6091 6092 switch (op) { 6093 case BO_LT: 6094 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 6095 break; 6096 case BO_GT: 6097 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 6098 break; 6099 case BO_LE: 6100 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 6101 break; 6102 case BO_GE: 6103 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 6104 break; 6105 case BO_EQ: 6106 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 6107 break; 6108 case BO_NE: 6109 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 6110 break; 6111 default: 6112 CmpRes = Unkwn; 6113 break; 6114 } 6115 6116 if (CmpRes == AFals) { 6117 IsTrue = false; 6118 } else if (CmpRes == ATrue) { 6119 IsTrue = true; 6120 } else { 6121 return; 6122 } 6123 } 6124 6125 // If this is a comparison to an enum constant, include that 6126 // constant in the diagnostic. 6127 const EnumConstantDecl *ED = nullptr; 6128 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 6129 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 6130 6131 SmallString<64> PrettySourceValue; 6132 llvm::raw_svector_ostream OS(PrettySourceValue); 6133 if (ED) 6134 OS << '\'' << *ED << "' (" << Value << ")"; 6135 else 6136 OS << Value; 6137 6138 S.DiagRuntimeBehavior( 6139 E->getOperatorLoc(), E, 6140 S.PDiag(diag::warn_out_of_range_compare) 6141 << OS.str() << LiteralOrBoolConstant 6142 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 6143 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 6144 } 6145 6146 /// Analyze the operands of the given comparison. Implements the 6147 /// fallback case from AnalyzeComparison. 6148 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 6149 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 6150 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 6151 } 6152 6153 /// \brief Implements -Wsign-compare. 6154 /// 6155 /// \param E the binary operator to check for warnings 6156 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 6157 // The type the comparison is being performed in. 6158 QualType T = E->getLHS()->getType(); 6159 6160 // Only analyze comparison operators where both sides have been converted to 6161 // the same type. 6162 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 6163 return AnalyzeImpConvsInComparison(S, E); 6164 6165 // Don't analyze value-dependent comparisons directly. 6166 if (E->isValueDependent()) 6167 return AnalyzeImpConvsInComparison(S, E); 6168 6169 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 6170 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 6171 6172 bool IsComparisonConstant = false; 6173 6174 // Check whether an integer constant comparison results in a value 6175 // of 'true' or 'false'. 6176 if (T->isIntegralType(S.Context)) { 6177 llvm::APSInt RHSValue; 6178 bool IsRHSIntegralLiteral = 6179 RHS->isIntegerConstantExpr(RHSValue, S.Context); 6180 llvm::APSInt LHSValue; 6181 bool IsLHSIntegralLiteral = 6182 LHS->isIntegerConstantExpr(LHSValue, S.Context); 6183 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 6184 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 6185 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 6186 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 6187 else 6188 IsComparisonConstant = 6189 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 6190 } else if (!T->hasUnsignedIntegerRepresentation()) 6191 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 6192 6193 // We don't do anything special if this isn't an unsigned integral 6194 // comparison: we're only interested in integral comparisons, and 6195 // signed comparisons only happen in cases we don't care to warn about. 6196 // 6197 // We also don't care about value-dependent expressions or expressions 6198 // whose result is a constant. 6199 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 6200 return AnalyzeImpConvsInComparison(S, E); 6201 6202 // Check to see if one of the (unmodified) operands is of different 6203 // signedness. 6204 Expr *signedOperand, *unsignedOperand; 6205 if (LHS->getType()->hasSignedIntegerRepresentation()) { 6206 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 6207 "unsigned comparison between two signed integer expressions?"); 6208 signedOperand = LHS; 6209 unsignedOperand = RHS; 6210 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 6211 signedOperand = RHS; 6212 unsignedOperand = LHS; 6213 } else { 6214 CheckTrivialUnsignedComparison(S, E); 6215 return AnalyzeImpConvsInComparison(S, E); 6216 } 6217 6218 // Otherwise, calculate the effective range of the signed operand. 6219 IntRange signedRange = GetExprRange(S.Context, signedOperand); 6220 6221 // Go ahead and analyze implicit conversions in the operands. Note 6222 // that we skip the implicit conversions on both sides. 6223 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 6224 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 6225 6226 // If the signed range is non-negative, -Wsign-compare won't fire, 6227 // but we should still check for comparisons which are always true 6228 // or false. 6229 if (signedRange.NonNegative) 6230 return CheckTrivialUnsignedComparison(S, E); 6231 6232 // For (in)equality comparisons, if the unsigned operand is a 6233 // constant which cannot collide with a overflowed signed operand, 6234 // then reinterpreting the signed operand as unsigned will not 6235 // change the result of the comparison. 6236 if (E->isEqualityOp()) { 6237 unsigned comparisonWidth = S.Context.getIntWidth(T); 6238 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 6239 6240 // We should never be unable to prove that the unsigned operand is 6241 // non-negative. 6242 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 6243 6244 if (unsignedRange.Width < comparisonWidth) 6245 return; 6246 } 6247 6248 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 6249 S.PDiag(diag::warn_mixed_sign_comparison) 6250 << LHS->getType() << RHS->getType() 6251 << LHS->getSourceRange() << RHS->getSourceRange()); 6252 } 6253 6254 /// Analyzes an attempt to assign the given value to a bitfield. 6255 /// 6256 /// Returns true if there was something fishy about the attempt. 6257 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 6258 SourceLocation InitLoc) { 6259 assert(Bitfield->isBitField()); 6260 if (Bitfield->isInvalidDecl()) 6261 return false; 6262 6263 // White-list bool bitfields. 6264 if (Bitfield->getType()->isBooleanType()) 6265 return false; 6266 6267 // Ignore value- or type-dependent expressions. 6268 if (Bitfield->getBitWidth()->isValueDependent() || 6269 Bitfield->getBitWidth()->isTypeDependent() || 6270 Init->isValueDependent() || 6271 Init->isTypeDependent()) 6272 return false; 6273 6274 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 6275 6276 llvm::APSInt Value; 6277 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 6278 return false; 6279 6280 unsigned OriginalWidth = Value.getBitWidth(); 6281 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 6282 6283 if (OriginalWidth <= FieldWidth) 6284 return false; 6285 6286 // Compute the value which the bitfield will contain. 6287 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 6288 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 6289 6290 // Check whether the stored value is equal to the original value. 6291 TruncatedValue = TruncatedValue.extend(OriginalWidth); 6292 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 6293 return false; 6294 6295 // Special-case bitfields of width 1: booleans are naturally 0/1, and 6296 // therefore don't strictly fit into a signed bitfield of width 1. 6297 if (FieldWidth == 1 && Value == 1) 6298 return false; 6299 6300 std::string PrettyValue = Value.toString(10); 6301 std::string PrettyTrunc = TruncatedValue.toString(10); 6302 6303 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 6304 << PrettyValue << PrettyTrunc << OriginalInit->getType() 6305 << Init->getSourceRange(); 6306 6307 return true; 6308 } 6309 6310 /// Analyze the given simple or compound assignment for warning-worthy 6311 /// operations. 6312 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 6313 // Just recurse on the LHS. 6314 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 6315 6316 // We want to recurse on the RHS as normal unless we're assigning to 6317 // a bitfield. 6318 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 6319 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 6320 E->getOperatorLoc())) { 6321 // Recurse, ignoring any implicit conversions on the RHS. 6322 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 6323 E->getOperatorLoc()); 6324 } 6325 } 6326 6327 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 6328 } 6329 6330 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 6331 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 6332 SourceLocation CContext, unsigned diag, 6333 bool pruneControlFlow = false) { 6334 if (pruneControlFlow) { 6335 S.DiagRuntimeBehavior(E->getExprLoc(), E, 6336 S.PDiag(diag) 6337 << SourceType << T << E->getSourceRange() 6338 << SourceRange(CContext)); 6339 return; 6340 } 6341 S.Diag(E->getExprLoc(), diag) 6342 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 6343 } 6344 6345 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 6346 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 6347 SourceLocation CContext, unsigned diag, 6348 bool pruneControlFlow = false) { 6349 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 6350 } 6351 6352 /// Diagnose an implicit cast from a literal expression. Does not warn when the 6353 /// cast wouldn't lose information. 6354 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T, 6355 SourceLocation CContext) { 6356 // Try to convert the literal exactly to an integer. If we can, don't warn. 6357 bool isExact = false; 6358 const llvm::APFloat &Value = FL->getValue(); 6359 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 6360 T->hasUnsignedIntegerRepresentation()); 6361 if (Value.convertToInteger(IntegerValue, 6362 llvm::APFloat::rmTowardZero, &isExact) 6363 == llvm::APFloat::opOK && isExact) 6364 return; 6365 6366 // FIXME: Force the precision of the source value down so we don't print 6367 // digits which are usually useless (we don't really care here if we 6368 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 6369 // would automatically print the shortest representation, but it's a bit 6370 // tricky to implement. 6371 SmallString<16> PrettySourceValue; 6372 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 6373 precision = (precision * 59 + 195) / 196; 6374 Value.toString(PrettySourceValue, precision); 6375 6376 SmallString<16> PrettyTargetValue; 6377 if (T->isSpecificBuiltinType(BuiltinType::Bool)) 6378 PrettyTargetValue = IntegerValue == 0 ? "false" : "true"; 6379 else 6380 IntegerValue.toString(PrettyTargetValue); 6381 6382 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer) 6383 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue 6384 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext); 6385 } 6386 6387 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 6388 if (!Range.Width) return "0"; 6389 6390 llvm::APSInt ValueInRange = Value; 6391 ValueInRange.setIsSigned(!Range.NonNegative); 6392 ValueInRange = ValueInRange.trunc(Range.Width); 6393 return ValueInRange.toString(10); 6394 } 6395 6396 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 6397 if (!isa<ImplicitCastExpr>(Ex)) 6398 return false; 6399 6400 Expr *InnerE = Ex->IgnoreParenImpCasts(); 6401 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 6402 const Type *Source = 6403 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 6404 if (Target->isDependentType()) 6405 return false; 6406 6407 const BuiltinType *FloatCandidateBT = 6408 dyn_cast<BuiltinType>(ToBool ? Source : Target); 6409 const Type *BoolCandidateType = ToBool ? Target : Source; 6410 6411 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 6412 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 6413 } 6414 6415 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 6416 SourceLocation CC) { 6417 unsigned NumArgs = TheCall->getNumArgs(); 6418 for (unsigned i = 0; i < NumArgs; ++i) { 6419 Expr *CurrA = TheCall->getArg(i); 6420 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 6421 continue; 6422 6423 bool IsSwapped = ((i > 0) && 6424 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 6425 IsSwapped |= ((i < (NumArgs - 1)) && 6426 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 6427 if (IsSwapped) { 6428 // Warn on this floating-point to bool conversion. 6429 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 6430 CurrA->getType(), CC, 6431 diag::warn_impcast_floating_point_to_bool); 6432 } 6433 } 6434 } 6435 6436 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 6437 SourceLocation CC) { 6438 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 6439 E->getExprLoc())) 6440 return; 6441 6442 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 6443 const Expr::NullPointerConstantKind NullKind = 6444 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 6445 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 6446 return; 6447 6448 // Return if target type is a safe conversion. 6449 if (T->isAnyPointerType() || T->isBlockPointerType() || 6450 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 6451 return; 6452 6453 SourceLocation Loc = E->getSourceRange().getBegin(); 6454 6455 // __null is usually wrapped in a macro. Go up a macro if that is the case. 6456 if (NullKind == Expr::NPCK_GNUNull) { 6457 if (Loc.isMacroID()) 6458 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 6459 } 6460 6461 // Only warn if the null and context location are in the same macro expansion. 6462 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 6463 return; 6464 6465 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 6466 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 6467 << FixItHint::CreateReplacement(Loc, 6468 S.getFixItZeroLiteralForType(T, Loc)); 6469 } 6470 6471 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 6472 SourceLocation CC, bool *ICContext = nullptr) { 6473 if (E->isTypeDependent() || E->isValueDependent()) return; 6474 6475 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 6476 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 6477 if (Source == Target) return; 6478 if (Target->isDependentType()) return; 6479 6480 // If the conversion context location is invalid don't complain. We also 6481 // don't want to emit a warning if the issue occurs from the expansion of 6482 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 6483 // delay this check as long as possible. Once we detect we are in that 6484 // scenario, we just return. 6485 if (CC.isInvalid()) 6486 return; 6487 6488 // Diagnose implicit casts to bool. 6489 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 6490 if (isa<StringLiteral>(E)) 6491 // Warn on string literal to bool. Checks for string literals in logical 6492 // and expressions, for instance, assert(0 && "error here"), are 6493 // prevented by a check in AnalyzeImplicitConversions(). 6494 return DiagnoseImpCast(S, E, T, CC, 6495 diag::warn_impcast_string_literal_to_bool); 6496 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 6497 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 6498 // This covers the literal expressions that evaluate to Objective-C 6499 // objects. 6500 return DiagnoseImpCast(S, E, T, CC, 6501 diag::warn_impcast_objective_c_literal_to_bool); 6502 } 6503 if (Source->isPointerType() || Source->canDecayToPointerType()) { 6504 // Warn on pointer to bool conversion that is always true. 6505 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 6506 SourceRange(CC)); 6507 } 6508 } 6509 6510 // Strip vector types. 6511 if (isa<VectorType>(Source)) { 6512 if (!isa<VectorType>(Target)) { 6513 if (S.SourceMgr.isInSystemMacro(CC)) 6514 return; 6515 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 6516 } 6517 6518 // If the vector cast is cast between two vectors of the same size, it is 6519 // a bitcast, not a conversion. 6520 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 6521 return; 6522 6523 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 6524 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 6525 } 6526 if (auto VecTy = dyn_cast<VectorType>(Target)) 6527 Target = VecTy->getElementType().getTypePtr(); 6528 6529 // Strip complex types. 6530 if (isa<ComplexType>(Source)) { 6531 if (!isa<ComplexType>(Target)) { 6532 if (S.SourceMgr.isInSystemMacro(CC)) 6533 return; 6534 6535 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 6536 } 6537 6538 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 6539 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 6540 } 6541 6542 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 6543 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 6544 6545 // If the source is floating point... 6546 if (SourceBT && SourceBT->isFloatingPoint()) { 6547 // ...and the target is floating point... 6548 if (TargetBT && TargetBT->isFloatingPoint()) { 6549 // ...then warn if we're dropping FP rank. 6550 6551 // Builtin FP kinds are ordered by increasing FP rank. 6552 if (SourceBT->getKind() > TargetBT->getKind()) { 6553 // Don't warn about float constants that are precisely 6554 // representable in the target type. 6555 Expr::EvalResult result; 6556 if (E->EvaluateAsRValue(result, S.Context)) { 6557 // Value might be a float, a float vector, or a float complex. 6558 if (IsSameFloatAfterCast(result.Val, 6559 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 6560 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 6561 return; 6562 } 6563 6564 if (S.SourceMgr.isInSystemMacro(CC)) 6565 return; 6566 6567 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 6568 } 6569 return; 6570 } 6571 6572 // If the target is integral, always warn. 6573 if (TargetBT && TargetBT->isInteger()) { 6574 if (S.SourceMgr.isInSystemMacro(CC)) 6575 return; 6576 6577 Expr *InnerE = E->IgnoreParenImpCasts(); 6578 // We also want to warn on, e.g., "int i = -1.234" 6579 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 6580 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 6581 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 6582 6583 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) { 6584 DiagnoseFloatingLiteralImpCast(S, FL, T, CC); 6585 } else { 6586 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer); 6587 } 6588 } 6589 6590 // If the target is bool, warn if expr is a function or method call. 6591 if (Target->isSpecificBuiltinType(BuiltinType::Bool) && 6592 isa<CallExpr>(E)) { 6593 // Check last argument of function call to see if it is an 6594 // implicit cast from a type matching the type the result 6595 // is being cast to. 6596 CallExpr *CEx = cast<CallExpr>(E); 6597 unsigned NumArgs = CEx->getNumArgs(); 6598 if (NumArgs > 0) { 6599 Expr *LastA = CEx->getArg(NumArgs - 1); 6600 Expr *InnerE = LastA->IgnoreParenImpCasts(); 6601 const Type *InnerType = 6602 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 6603 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) { 6604 // Warn on this floating-point to bool conversion 6605 DiagnoseImpCast(S, E, T, CC, 6606 diag::warn_impcast_floating_point_to_bool); 6607 } 6608 } 6609 } 6610 return; 6611 } 6612 6613 DiagnoseNullConversion(S, E, T, CC); 6614 6615 if (!Source->isIntegerType() || !Target->isIntegerType()) 6616 return; 6617 6618 // TODO: remove this early return once the false positives for constant->bool 6619 // in templates, macros, etc, are reduced or removed. 6620 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 6621 return; 6622 6623 IntRange SourceRange = GetExprRange(S.Context, E); 6624 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 6625 6626 if (SourceRange.Width > TargetRange.Width) { 6627 // If the source is a constant, use a default-on diagnostic. 6628 // TODO: this should happen for bitfield stores, too. 6629 llvm::APSInt Value(32); 6630 if (E->isIntegerConstantExpr(Value, S.Context)) { 6631 if (S.SourceMgr.isInSystemMacro(CC)) 6632 return; 6633 6634 std::string PrettySourceValue = Value.toString(10); 6635 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 6636 6637 S.DiagRuntimeBehavior(E->getExprLoc(), E, 6638 S.PDiag(diag::warn_impcast_integer_precision_constant) 6639 << PrettySourceValue << PrettyTargetValue 6640 << E->getType() << T << E->getSourceRange() 6641 << clang::SourceRange(CC)); 6642 return; 6643 } 6644 6645 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 6646 if (S.SourceMgr.isInSystemMacro(CC)) 6647 return; 6648 6649 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 6650 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 6651 /* pruneControlFlow */ true); 6652 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 6653 } 6654 6655 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 6656 (!TargetRange.NonNegative && SourceRange.NonNegative && 6657 SourceRange.Width == TargetRange.Width)) { 6658 6659 if (S.SourceMgr.isInSystemMacro(CC)) 6660 return; 6661 6662 unsigned DiagID = diag::warn_impcast_integer_sign; 6663 6664 // Traditionally, gcc has warned about this under -Wsign-compare. 6665 // We also want to warn about it in -Wconversion. 6666 // So if -Wconversion is off, use a completely identical diagnostic 6667 // in the sign-compare group. 6668 // The conditional-checking code will 6669 if (ICContext) { 6670 DiagID = diag::warn_impcast_integer_sign_conditional; 6671 *ICContext = true; 6672 } 6673 6674 return DiagnoseImpCast(S, E, T, CC, DiagID); 6675 } 6676 6677 // Diagnose conversions between different enumeration types. 6678 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 6679 // type, to give us better diagnostics. 6680 QualType SourceType = E->getType(); 6681 if (!S.getLangOpts().CPlusPlus) { 6682 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 6683 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 6684 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 6685 SourceType = S.Context.getTypeDeclType(Enum); 6686 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 6687 } 6688 } 6689 6690 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 6691 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 6692 if (SourceEnum->getDecl()->hasNameForLinkage() && 6693 TargetEnum->getDecl()->hasNameForLinkage() && 6694 SourceEnum != TargetEnum) { 6695 if (S.SourceMgr.isInSystemMacro(CC)) 6696 return; 6697 6698 return DiagnoseImpCast(S, E, SourceType, T, CC, 6699 diag::warn_impcast_different_enum_types); 6700 } 6701 6702 return; 6703 } 6704 6705 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 6706 SourceLocation CC, QualType T); 6707 6708 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 6709 SourceLocation CC, bool &ICContext) { 6710 E = E->IgnoreParenImpCasts(); 6711 6712 if (isa<ConditionalOperator>(E)) 6713 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 6714 6715 AnalyzeImplicitConversions(S, E, CC); 6716 if (E->getType() != T) 6717 return CheckImplicitConversion(S, E, T, CC, &ICContext); 6718 return; 6719 } 6720 6721 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 6722 SourceLocation CC, QualType T) { 6723 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 6724 6725 bool Suspicious = false; 6726 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 6727 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 6728 6729 // If -Wconversion would have warned about either of the candidates 6730 // for a signedness conversion to the context type... 6731 if (!Suspicious) return; 6732 6733 // ...but it's currently ignored... 6734 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 6735 return; 6736 6737 // ...then check whether it would have warned about either of the 6738 // candidates for a signedness conversion to the condition type. 6739 if (E->getType() == T) return; 6740 6741 Suspicious = false; 6742 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 6743 E->getType(), CC, &Suspicious); 6744 if (!Suspicious) 6745 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 6746 E->getType(), CC, &Suspicious); 6747 } 6748 6749 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 6750 /// Input argument E is a logical expression. 6751 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 6752 if (S.getLangOpts().Bool) 6753 return; 6754 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 6755 } 6756 6757 /// AnalyzeImplicitConversions - Find and report any interesting 6758 /// implicit conversions in the given expression. There are a couple 6759 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 6760 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 6761 QualType T = OrigE->getType(); 6762 Expr *E = OrigE->IgnoreParenImpCasts(); 6763 6764 if (E->isTypeDependent() || E->isValueDependent()) 6765 return; 6766 6767 // For conditional operators, we analyze the arguments as if they 6768 // were being fed directly into the output. 6769 if (isa<ConditionalOperator>(E)) { 6770 ConditionalOperator *CO = cast<ConditionalOperator>(E); 6771 CheckConditionalOperator(S, CO, CC, T); 6772 return; 6773 } 6774 6775 // Check implicit argument conversions for function calls. 6776 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 6777 CheckImplicitArgumentConversions(S, Call, CC); 6778 6779 // Go ahead and check any implicit conversions we might have skipped. 6780 // The non-canonical typecheck is just an optimization; 6781 // CheckImplicitConversion will filter out dead implicit conversions. 6782 if (E->getType() != T) 6783 CheckImplicitConversion(S, E, T, CC); 6784 6785 // Now continue drilling into this expression. 6786 6787 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) { 6788 if (POE->getResultExpr()) 6789 E = POE->getResultExpr(); 6790 } 6791 6792 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 6793 if (OVE->getSourceExpr()) 6794 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 6795 return; 6796 } 6797 6798 // Skip past explicit casts. 6799 if (isa<ExplicitCastExpr>(E)) { 6800 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 6801 return AnalyzeImplicitConversions(S, E, CC); 6802 } 6803 6804 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6805 // Do a somewhat different check with comparison operators. 6806 if (BO->isComparisonOp()) 6807 return AnalyzeComparison(S, BO); 6808 6809 // And with simple assignments. 6810 if (BO->getOpcode() == BO_Assign) 6811 return AnalyzeAssignment(S, BO); 6812 } 6813 6814 // These break the otherwise-useful invariant below. Fortunately, 6815 // we don't really need to recurse into them, because any internal 6816 // expressions should have been analyzed already when they were 6817 // built into statements. 6818 if (isa<StmtExpr>(E)) return; 6819 6820 // Don't descend into unevaluated contexts. 6821 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 6822 6823 // Now just recurse over the expression's children. 6824 CC = E->getExprLoc(); 6825 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 6826 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 6827 for (Stmt::child_range I = E->children(); I; ++I) { 6828 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I); 6829 if (!ChildExpr) 6830 continue; 6831 6832 if (IsLogicalAndOperator && 6833 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 6834 // Ignore checking string literals that are in logical and operators. 6835 // This is a common pattern for asserts. 6836 continue; 6837 AnalyzeImplicitConversions(S, ChildExpr, CC); 6838 } 6839 6840 if (BO && BO->isLogicalOp()) { 6841 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 6842 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 6843 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 6844 6845 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 6846 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 6847 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 6848 } 6849 6850 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 6851 if (U->getOpcode() == UO_LNot) 6852 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 6853 } 6854 6855 } // end anonymous namespace 6856 6857 enum { 6858 AddressOf, 6859 FunctionPointer, 6860 ArrayPointer 6861 }; 6862 6863 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 6864 // Returns true when emitting a warning about taking the address of a reference. 6865 static bool CheckForReference(Sema &SemaRef, const Expr *E, 6866 PartialDiagnostic PD) { 6867 E = E->IgnoreParenImpCasts(); 6868 6869 const FunctionDecl *FD = nullptr; 6870 6871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 6872 if (!DRE->getDecl()->getType()->isReferenceType()) 6873 return false; 6874 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 6875 if (!M->getMemberDecl()->getType()->isReferenceType()) 6876 return false; 6877 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 6878 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 6879 return false; 6880 FD = Call->getDirectCallee(); 6881 } else { 6882 return false; 6883 } 6884 6885 SemaRef.Diag(E->getExprLoc(), PD); 6886 6887 // If possible, point to location of function. 6888 if (FD) { 6889 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 6890 } 6891 6892 return true; 6893 } 6894 6895 // Returns true if the SourceLocation is expanded from any macro body. 6896 // Returns false if the SourceLocation is invalid, is from not in a macro 6897 // expansion, or is from expanded from a top-level macro argument. 6898 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 6899 if (Loc.isInvalid()) 6900 return false; 6901 6902 while (Loc.isMacroID()) { 6903 if (SM.isMacroBodyExpansion(Loc)) 6904 return true; 6905 Loc = SM.getImmediateMacroCallerLoc(Loc); 6906 } 6907 6908 return false; 6909 } 6910 6911 /// \brief Diagnose pointers that are always non-null. 6912 /// \param E the expression containing the pointer 6913 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 6914 /// compared to a null pointer 6915 /// \param IsEqual True when the comparison is equal to a null pointer 6916 /// \param Range Extra SourceRange to highlight in the diagnostic 6917 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 6918 Expr::NullPointerConstantKind NullKind, 6919 bool IsEqual, SourceRange Range) { 6920 if (!E) 6921 return; 6922 6923 // Don't warn inside macros. 6924 if (E->getExprLoc().isMacroID()) { 6925 const SourceManager &SM = getSourceManager(); 6926 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 6927 IsInAnyMacroBody(SM, Range.getBegin())) 6928 return; 6929 } 6930 E = E->IgnoreImpCasts(); 6931 6932 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 6933 6934 if (isa<CXXThisExpr>(E)) { 6935 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 6936 : diag::warn_this_bool_conversion; 6937 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 6938 return; 6939 } 6940 6941 bool IsAddressOf = false; 6942 6943 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 6944 if (UO->getOpcode() != UO_AddrOf) 6945 return; 6946 IsAddressOf = true; 6947 E = UO->getSubExpr(); 6948 } 6949 6950 if (IsAddressOf) { 6951 unsigned DiagID = IsCompare 6952 ? diag::warn_address_of_reference_null_compare 6953 : diag::warn_address_of_reference_bool_conversion; 6954 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 6955 << IsEqual; 6956 if (CheckForReference(*this, E, PD)) { 6957 return; 6958 } 6959 } 6960 6961 // Expect to find a single Decl. Skip anything more complicated. 6962 ValueDecl *D = nullptr; 6963 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 6964 D = R->getDecl(); 6965 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 6966 D = M->getMemberDecl(); 6967 } 6968 6969 // Weak Decls can be null. 6970 if (!D || D->isWeak()) 6971 return; 6972 6973 // Check for parameter decl with nonnull attribute 6974 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) { 6975 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV)) 6976 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 6977 unsigned NumArgs = FD->getNumParams(); 6978 llvm::SmallBitVector AttrNonNull(NumArgs); 6979 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 6980 if (!NonNull->args_size()) { 6981 AttrNonNull.set(0, NumArgs); 6982 break; 6983 } 6984 for (unsigned Val : NonNull->args()) { 6985 if (Val >= NumArgs) 6986 continue; 6987 AttrNonNull.set(Val); 6988 } 6989 } 6990 if (!AttrNonNull.empty()) 6991 for (unsigned i = 0; i < NumArgs; ++i) 6992 if (FD->getParamDecl(i) == PV && 6993 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) { 6994 std::string Str; 6995 llvm::raw_string_ostream S(Str); 6996 E->printPretty(S, nullptr, getPrintingPolicy()); 6997 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare 6998 : diag::warn_cast_nonnull_to_bool; 6999 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange() 7000 << Range << IsEqual; 7001 return; 7002 } 7003 } 7004 } 7005 7006 QualType T = D->getType(); 7007 const bool IsArray = T->isArrayType(); 7008 const bool IsFunction = T->isFunctionType(); 7009 7010 // Address of function is used to silence the function warning. 7011 if (IsAddressOf && IsFunction) { 7012 return; 7013 } 7014 7015 // Found nothing. 7016 if (!IsAddressOf && !IsFunction && !IsArray) 7017 return; 7018 7019 // Pretty print the expression for the diagnostic. 7020 std::string Str; 7021 llvm::raw_string_ostream S(Str); 7022 E->printPretty(S, nullptr, getPrintingPolicy()); 7023 7024 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 7025 : diag::warn_impcast_pointer_to_bool; 7026 unsigned DiagType; 7027 if (IsAddressOf) 7028 DiagType = AddressOf; 7029 else if (IsFunction) 7030 DiagType = FunctionPointer; 7031 else if (IsArray) 7032 DiagType = ArrayPointer; 7033 else 7034 llvm_unreachable("Could not determine diagnostic."); 7035 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 7036 << Range << IsEqual; 7037 7038 if (!IsFunction) 7039 return; 7040 7041 // Suggest '&' to silence the function warning. 7042 Diag(E->getExprLoc(), diag::note_function_warning_silence) 7043 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 7044 7045 // Check to see if '()' fixit should be emitted. 7046 QualType ReturnType; 7047 UnresolvedSet<4> NonTemplateOverloads; 7048 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 7049 if (ReturnType.isNull()) 7050 return; 7051 7052 if (IsCompare) { 7053 // There are two cases here. If there is null constant, the only suggest 7054 // for a pointer return type. If the null is 0, then suggest if the return 7055 // type is a pointer or an integer type. 7056 if (!ReturnType->isPointerType()) { 7057 if (NullKind == Expr::NPCK_ZeroExpression || 7058 NullKind == Expr::NPCK_ZeroLiteral) { 7059 if (!ReturnType->isIntegerType()) 7060 return; 7061 } else { 7062 return; 7063 } 7064 } 7065 } else { // !IsCompare 7066 // For function to bool, only suggest if the function pointer has bool 7067 // return type. 7068 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 7069 return; 7070 } 7071 Diag(E->getExprLoc(), diag::note_function_to_function_call) 7072 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 7073 } 7074 7075 7076 /// Diagnoses "dangerous" implicit conversions within the given 7077 /// expression (which is a full expression). Implements -Wconversion 7078 /// and -Wsign-compare. 7079 /// 7080 /// \param CC the "context" location of the implicit conversion, i.e. 7081 /// the most location of the syntactic entity requiring the implicit 7082 /// conversion 7083 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 7084 // Don't diagnose in unevaluated contexts. 7085 if (isUnevaluatedContext()) 7086 return; 7087 7088 // Don't diagnose for value- or type-dependent expressions. 7089 if (E->isTypeDependent() || E->isValueDependent()) 7090 return; 7091 7092 // Check for array bounds violations in cases where the check isn't triggered 7093 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 7094 // ArraySubscriptExpr is on the RHS of a variable initialization. 7095 CheckArrayAccess(E); 7096 7097 // This is not the right CC for (e.g.) a variable initialization. 7098 AnalyzeImplicitConversions(*this, E, CC); 7099 } 7100 7101 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 7102 /// Input argument E is a logical expression. 7103 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 7104 ::CheckBoolLikeConversion(*this, E, CC); 7105 } 7106 7107 /// Diagnose when expression is an integer constant expression and its evaluation 7108 /// results in integer overflow 7109 void Sema::CheckForIntOverflow (Expr *E) { 7110 if (isa<BinaryOperator>(E->IgnoreParenCasts())) 7111 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 7112 } 7113 7114 namespace { 7115 /// \brief Visitor for expressions which looks for unsequenced operations on the 7116 /// same object. 7117 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 7118 typedef EvaluatedExprVisitor<SequenceChecker> Base; 7119 7120 /// \brief A tree of sequenced regions within an expression. Two regions are 7121 /// unsequenced if one is an ancestor or a descendent of the other. When we 7122 /// finish processing an expression with sequencing, such as a comma 7123 /// expression, we fold its tree nodes into its parent, since they are 7124 /// unsequenced with respect to nodes we will visit later. 7125 class SequenceTree { 7126 struct Value { 7127 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 7128 unsigned Parent : 31; 7129 bool Merged : 1; 7130 }; 7131 SmallVector<Value, 8> Values; 7132 7133 public: 7134 /// \brief A region within an expression which may be sequenced with respect 7135 /// to some other region. 7136 class Seq { 7137 explicit Seq(unsigned N) : Index(N) {} 7138 unsigned Index; 7139 friend class SequenceTree; 7140 public: 7141 Seq() : Index(0) {} 7142 }; 7143 7144 SequenceTree() { Values.push_back(Value(0)); } 7145 Seq root() const { return Seq(0); } 7146 7147 /// \brief Create a new sequence of operations, which is an unsequenced 7148 /// subset of \p Parent. This sequence of operations is sequenced with 7149 /// respect to other children of \p Parent. 7150 Seq allocate(Seq Parent) { 7151 Values.push_back(Value(Parent.Index)); 7152 return Seq(Values.size() - 1); 7153 } 7154 7155 /// \brief Merge a sequence of operations into its parent. 7156 void merge(Seq S) { 7157 Values[S.Index].Merged = true; 7158 } 7159 7160 /// \brief Determine whether two operations are unsequenced. This operation 7161 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 7162 /// should have been merged into its parent as appropriate. 7163 bool isUnsequenced(Seq Cur, Seq Old) { 7164 unsigned C = representative(Cur.Index); 7165 unsigned Target = representative(Old.Index); 7166 while (C >= Target) { 7167 if (C == Target) 7168 return true; 7169 C = Values[C].Parent; 7170 } 7171 return false; 7172 } 7173 7174 private: 7175 /// \brief Pick a representative for a sequence. 7176 unsigned representative(unsigned K) { 7177 if (Values[K].Merged) 7178 // Perform path compression as we go. 7179 return Values[K].Parent = representative(Values[K].Parent); 7180 return K; 7181 } 7182 }; 7183 7184 /// An object for which we can track unsequenced uses. 7185 typedef NamedDecl *Object; 7186 7187 /// Different flavors of object usage which we track. We only track the 7188 /// least-sequenced usage of each kind. 7189 enum UsageKind { 7190 /// A read of an object. Multiple unsequenced reads are OK. 7191 UK_Use, 7192 /// A modification of an object which is sequenced before the value 7193 /// computation of the expression, such as ++n in C++. 7194 UK_ModAsValue, 7195 /// A modification of an object which is not sequenced before the value 7196 /// computation of the expression, such as n++. 7197 UK_ModAsSideEffect, 7198 7199 UK_Count = UK_ModAsSideEffect + 1 7200 }; 7201 7202 struct Usage { 7203 Usage() : Use(nullptr), Seq() {} 7204 Expr *Use; 7205 SequenceTree::Seq Seq; 7206 }; 7207 7208 struct UsageInfo { 7209 UsageInfo() : Diagnosed(false) {} 7210 Usage Uses[UK_Count]; 7211 /// Have we issued a diagnostic for this variable already? 7212 bool Diagnosed; 7213 }; 7214 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 7215 7216 Sema &SemaRef; 7217 /// Sequenced regions within the expression. 7218 SequenceTree Tree; 7219 /// Declaration modifications and references which we have seen. 7220 UsageInfoMap UsageMap; 7221 /// The region we are currently within. 7222 SequenceTree::Seq Region; 7223 /// Filled in with declarations which were modified as a side-effect 7224 /// (that is, post-increment operations). 7225 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 7226 /// Expressions to check later. We defer checking these to reduce 7227 /// stack usage. 7228 SmallVectorImpl<Expr *> &WorkList; 7229 7230 /// RAII object wrapping the visitation of a sequenced subexpression of an 7231 /// expression. At the end of this process, the side-effects of the evaluation 7232 /// become sequenced with respect to the value computation of the result, so 7233 /// we downgrade any UK_ModAsSideEffect within the evaluation to 7234 /// UK_ModAsValue. 7235 struct SequencedSubexpression { 7236 SequencedSubexpression(SequenceChecker &Self) 7237 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 7238 Self.ModAsSideEffect = &ModAsSideEffect; 7239 } 7240 ~SequencedSubexpression() { 7241 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend(); 7242 MI != ME; ++MI) { 7243 UsageInfo &U = Self.UsageMap[MI->first]; 7244 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 7245 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue); 7246 SideEffectUsage = MI->second; 7247 } 7248 Self.ModAsSideEffect = OldModAsSideEffect; 7249 } 7250 7251 SequenceChecker &Self; 7252 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 7253 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 7254 }; 7255 7256 /// RAII object wrapping the visitation of a subexpression which we might 7257 /// choose to evaluate as a constant. If any subexpression is evaluated and 7258 /// found to be non-constant, this allows us to suppress the evaluation of 7259 /// the outer expression. 7260 class EvaluationTracker { 7261 public: 7262 EvaluationTracker(SequenceChecker &Self) 7263 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 7264 Self.EvalTracker = this; 7265 } 7266 ~EvaluationTracker() { 7267 Self.EvalTracker = Prev; 7268 if (Prev) 7269 Prev->EvalOK &= EvalOK; 7270 } 7271 7272 bool evaluate(const Expr *E, bool &Result) { 7273 if (!EvalOK || E->isValueDependent()) 7274 return false; 7275 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 7276 return EvalOK; 7277 } 7278 7279 private: 7280 SequenceChecker &Self; 7281 EvaluationTracker *Prev; 7282 bool EvalOK; 7283 } *EvalTracker; 7284 7285 /// \brief Find the object which is produced by the specified expression, 7286 /// if any. 7287 Object getObject(Expr *E, bool Mod) const { 7288 E = E->IgnoreParenCasts(); 7289 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 7290 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 7291 return getObject(UO->getSubExpr(), Mod); 7292 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 7293 if (BO->getOpcode() == BO_Comma) 7294 return getObject(BO->getRHS(), Mod); 7295 if (Mod && BO->isAssignmentOp()) 7296 return getObject(BO->getLHS(), Mod); 7297 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 7298 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 7299 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 7300 return ME->getMemberDecl(); 7301 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 7302 // FIXME: If this is a reference, map through to its value. 7303 return DRE->getDecl(); 7304 return nullptr; 7305 } 7306 7307 /// \brief Note that an object was modified or used by an expression. 7308 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 7309 Usage &U = UI.Uses[UK]; 7310 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 7311 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 7312 ModAsSideEffect->push_back(std::make_pair(O, U)); 7313 U.Use = Ref; 7314 U.Seq = Region; 7315 } 7316 } 7317 /// \brief Check whether a modification or use conflicts with a prior usage. 7318 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 7319 bool IsModMod) { 7320 if (UI.Diagnosed) 7321 return; 7322 7323 const Usage &U = UI.Uses[OtherKind]; 7324 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 7325 return; 7326 7327 Expr *Mod = U.Use; 7328 Expr *ModOrUse = Ref; 7329 if (OtherKind == UK_Use) 7330 std::swap(Mod, ModOrUse); 7331 7332 SemaRef.Diag(Mod->getExprLoc(), 7333 IsModMod ? diag::warn_unsequenced_mod_mod 7334 : diag::warn_unsequenced_mod_use) 7335 << O << SourceRange(ModOrUse->getExprLoc()); 7336 UI.Diagnosed = true; 7337 } 7338 7339 void notePreUse(Object O, Expr *Use) { 7340 UsageInfo &U = UsageMap[O]; 7341 // Uses conflict with other modifications. 7342 checkUsage(O, U, Use, UK_ModAsValue, false); 7343 } 7344 void notePostUse(Object O, Expr *Use) { 7345 UsageInfo &U = UsageMap[O]; 7346 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 7347 addUsage(U, O, Use, UK_Use); 7348 } 7349 7350 void notePreMod(Object O, Expr *Mod) { 7351 UsageInfo &U = UsageMap[O]; 7352 // Modifications conflict with other modifications and with uses. 7353 checkUsage(O, U, Mod, UK_ModAsValue, true); 7354 checkUsage(O, U, Mod, UK_Use, false); 7355 } 7356 void notePostMod(Object O, Expr *Use, UsageKind UK) { 7357 UsageInfo &U = UsageMap[O]; 7358 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 7359 addUsage(U, O, Use, UK); 7360 } 7361 7362 public: 7363 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 7364 : Base(S.Context), SemaRef(S), Region(Tree.root()), 7365 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 7366 Visit(E); 7367 } 7368 7369 void VisitStmt(Stmt *S) { 7370 // Skip all statements which aren't expressions for now. 7371 } 7372 7373 void VisitExpr(Expr *E) { 7374 // By default, just recurse to evaluated subexpressions. 7375 Base::VisitStmt(E); 7376 } 7377 7378 void VisitCastExpr(CastExpr *E) { 7379 Object O = Object(); 7380 if (E->getCastKind() == CK_LValueToRValue) 7381 O = getObject(E->getSubExpr(), false); 7382 7383 if (O) 7384 notePreUse(O, E); 7385 VisitExpr(E); 7386 if (O) 7387 notePostUse(O, E); 7388 } 7389 7390 void VisitBinComma(BinaryOperator *BO) { 7391 // C++11 [expr.comma]p1: 7392 // Every value computation and side effect associated with the left 7393 // expression is sequenced before every value computation and side 7394 // effect associated with the right expression. 7395 SequenceTree::Seq LHS = Tree.allocate(Region); 7396 SequenceTree::Seq RHS = Tree.allocate(Region); 7397 SequenceTree::Seq OldRegion = Region; 7398 7399 { 7400 SequencedSubexpression SeqLHS(*this); 7401 Region = LHS; 7402 Visit(BO->getLHS()); 7403 } 7404 7405 Region = RHS; 7406 Visit(BO->getRHS()); 7407 7408 Region = OldRegion; 7409 7410 // Forget that LHS and RHS are sequenced. They are both unsequenced 7411 // with respect to other stuff. 7412 Tree.merge(LHS); 7413 Tree.merge(RHS); 7414 } 7415 7416 void VisitBinAssign(BinaryOperator *BO) { 7417 // The modification is sequenced after the value computation of the LHS 7418 // and RHS, so check it before inspecting the operands and update the 7419 // map afterwards. 7420 Object O = getObject(BO->getLHS(), true); 7421 if (!O) 7422 return VisitExpr(BO); 7423 7424 notePreMod(O, BO); 7425 7426 // C++11 [expr.ass]p7: 7427 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 7428 // only once. 7429 // 7430 // Therefore, for a compound assignment operator, O is considered used 7431 // everywhere except within the evaluation of E1 itself. 7432 if (isa<CompoundAssignOperator>(BO)) 7433 notePreUse(O, BO); 7434 7435 Visit(BO->getLHS()); 7436 7437 if (isa<CompoundAssignOperator>(BO)) 7438 notePostUse(O, BO); 7439 7440 Visit(BO->getRHS()); 7441 7442 // C++11 [expr.ass]p1: 7443 // the assignment is sequenced [...] before the value computation of the 7444 // assignment expression. 7445 // C11 6.5.16/3 has no such rule. 7446 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 7447 : UK_ModAsSideEffect); 7448 } 7449 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 7450 VisitBinAssign(CAO); 7451 } 7452 7453 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 7454 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 7455 void VisitUnaryPreIncDec(UnaryOperator *UO) { 7456 Object O = getObject(UO->getSubExpr(), true); 7457 if (!O) 7458 return VisitExpr(UO); 7459 7460 notePreMod(O, UO); 7461 Visit(UO->getSubExpr()); 7462 // C++11 [expr.pre.incr]p1: 7463 // the expression ++x is equivalent to x+=1 7464 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 7465 : UK_ModAsSideEffect); 7466 } 7467 7468 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 7469 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 7470 void VisitUnaryPostIncDec(UnaryOperator *UO) { 7471 Object O = getObject(UO->getSubExpr(), true); 7472 if (!O) 7473 return VisitExpr(UO); 7474 7475 notePreMod(O, UO); 7476 Visit(UO->getSubExpr()); 7477 notePostMod(O, UO, UK_ModAsSideEffect); 7478 } 7479 7480 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 7481 void VisitBinLOr(BinaryOperator *BO) { 7482 // The side-effects of the LHS of an '&&' are sequenced before the 7483 // value computation of the RHS, and hence before the value computation 7484 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 7485 // as if they were unconditionally sequenced. 7486 EvaluationTracker Eval(*this); 7487 { 7488 SequencedSubexpression Sequenced(*this); 7489 Visit(BO->getLHS()); 7490 } 7491 7492 bool Result; 7493 if (Eval.evaluate(BO->getLHS(), Result)) { 7494 if (!Result) 7495 Visit(BO->getRHS()); 7496 } else { 7497 // Check for unsequenced operations in the RHS, treating it as an 7498 // entirely separate evaluation. 7499 // 7500 // FIXME: If there are operations in the RHS which are unsequenced 7501 // with respect to operations outside the RHS, and those operations 7502 // are unconditionally evaluated, diagnose them. 7503 WorkList.push_back(BO->getRHS()); 7504 } 7505 } 7506 void VisitBinLAnd(BinaryOperator *BO) { 7507 EvaluationTracker Eval(*this); 7508 { 7509 SequencedSubexpression Sequenced(*this); 7510 Visit(BO->getLHS()); 7511 } 7512 7513 bool Result; 7514 if (Eval.evaluate(BO->getLHS(), Result)) { 7515 if (Result) 7516 Visit(BO->getRHS()); 7517 } else { 7518 WorkList.push_back(BO->getRHS()); 7519 } 7520 } 7521 7522 // Only visit the condition, unless we can be sure which subexpression will 7523 // be chosen. 7524 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 7525 EvaluationTracker Eval(*this); 7526 { 7527 SequencedSubexpression Sequenced(*this); 7528 Visit(CO->getCond()); 7529 } 7530 7531 bool Result; 7532 if (Eval.evaluate(CO->getCond(), Result)) 7533 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 7534 else { 7535 WorkList.push_back(CO->getTrueExpr()); 7536 WorkList.push_back(CO->getFalseExpr()); 7537 } 7538 } 7539 7540 void VisitCallExpr(CallExpr *CE) { 7541 // C++11 [intro.execution]p15: 7542 // When calling a function [...], every value computation and side effect 7543 // associated with any argument expression, or with the postfix expression 7544 // designating the called function, is sequenced before execution of every 7545 // expression or statement in the body of the function [and thus before 7546 // the value computation of its result]. 7547 SequencedSubexpression Sequenced(*this); 7548 Base::VisitCallExpr(CE); 7549 7550 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 7551 } 7552 7553 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 7554 // This is a call, so all subexpressions are sequenced before the result. 7555 SequencedSubexpression Sequenced(*this); 7556 7557 if (!CCE->isListInitialization()) 7558 return VisitExpr(CCE); 7559 7560 // In C++11, list initializations are sequenced. 7561 SmallVector<SequenceTree::Seq, 32> Elts; 7562 SequenceTree::Seq Parent = Region; 7563 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 7564 E = CCE->arg_end(); 7565 I != E; ++I) { 7566 Region = Tree.allocate(Parent); 7567 Elts.push_back(Region); 7568 Visit(*I); 7569 } 7570 7571 // Forget that the initializers are sequenced. 7572 Region = Parent; 7573 for (unsigned I = 0; I < Elts.size(); ++I) 7574 Tree.merge(Elts[I]); 7575 } 7576 7577 void VisitInitListExpr(InitListExpr *ILE) { 7578 if (!SemaRef.getLangOpts().CPlusPlus11) 7579 return VisitExpr(ILE); 7580 7581 // In C++11, list initializations are sequenced. 7582 SmallVector<SequenceTree::Seq, 32> Elts; 7583 SequenceTree::Seq Parent = Region; 7584 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 7585 Expr *E = ILE->getInit(I); 7586 if (!E) continue; 7587 Region = Tree.allocate(Parent); 7588 Elts.push_back(Region); 7589 Visit(E); 7590 } 7591 7592 // Forget that the initializers are sequenced. 7593 Region = Parent; 7594 for (unsigned I = 0; I < Elts.size(); ++I) 7595 Tree.merge(Elts[I]); 7596 } 7597 }; 7598 } 7599 7600 void Sema::CheckUnsequencedOperations(Expr *E) { 7601 SmallVector<Expr *, 8> WorkList; 7602 WorkList.push_back(E); 7603 while (!WorkList.empty()) { 7604 Expr *Item = WorkList.pop_back_val(); 7605 SequenceChecker(*this, Item, WorkList); 7606 } 7607 } 7608 7609 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 7610 bool IsConstexpr) { 7611 CheckImplicitConversions(E, CheckLoc); 7612 CheckUnsequencedOperations(E); 7613 if (!IsConstexpr && !E->isValueDependent()) 7614 CheckForIntOverflow(E); 7615 } 7616 7617 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 7618 FieldDecl *BitField, 7619 Expr *Init) { 7620 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 7621 } 7622 7623 /// CheckParmsForFunctionDef - Check that the parameters of the given 7624 /// function are appropriate for the definition of a function. This 7625 /// takes care of any checks that cannot be performed on the 7626 /// declaration itself, e.g., that the types of each of the function 7627 /// parameters are complete. 7628 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P, 7629 ParmVarDecl *const *PEnd, 7630 bool CheckParameterNames) { 7631 bool HasInvalidParm = false; 7632 for (; P != PEnd; ++P) { 7633 ParmVarDecl *Param = *P; 7634 7635 // C99 6.7.5.3p4: the parameters in a parameter type list in a 7636 // function declarator that is part of a function definition of 7637 // that function shall not have incomplete type. 7638 // 7639 // This is also C++ [dcl.fct]p6. 7640 if (!Param->isInvalidDecl() && 7641 RequireCompleteType(Param->getLocation(), Param->getType(), 7642 diag::err_typecheck_decl_incomplete_type)) { 7643 Param->setInvalidDecl(); 7644 HasInvalidParm = true; 7645 } 7646 7647 // C99 6.9.1p5: If the declarator includes a parameter type list, the 7648 // declaration of each parameter shall include an identifier. 7649 if (CheckParameterNames && 7650 Param->getIdentifier() == nullptr && 7651 !Param->isImplicit() && 7652 !getLangOpts().CPlusPlus) 7653 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 7654 7655 // C99 6.7.5.3p12: 7656 // If the function declarator is not part of a definition of that 7657 // function, parameters may have incomplete type and may use the [*] 7658 // notation in their sequences of declarator specifiers to specify 7659 // variable length array types. 7660 QualType PType = Param->getOriginalType(); 7661 while (const ArrayType *AT = Context.getAsArrayType(PType)) { 7662 if (AT->getSizeModifier() == ArrayType::Star) { 7663 // FIXME: This diagnostic should point the '[*]' if source-location 7664 // information is added for it. 7665 Diag(Param->getLocation(), diag::err_array_star_in_function_definition); 7666 break; 7667 } 7668 PType= AT->getElementType(); 7669 } 7670 7671 // MSVC destroys objects passed by value in the callee. Therefore a 7672 // function definition which takes such a parameter must be able to call the 7673 // object's destructor. However, we don't perform any direct access check 7674 // on the dtor. 7675 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 7676 .getCXXABI() 7677 .areArgsDestroyedLeftToRightInCallee()) { 7678 if (!Param->isInvalidDecl()) { 7679 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 7680 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 7681 if (!ClassDecl->isInvalidDecl() && 7682 !ClassDecl->hasIrrelevantDestructor() && 7683 !ClassDecl->isDependentContext()) { 7684 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 7685 MarkFunctionReferenced(Param->getLocation(), Destructor); 7686 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 7687 } 7688 } 7689 } 7690 } 7691 } 7692 7693 return HasInvalidParm; 7694 } 7695 7696 /// CheckCastAlign - Implements -Wcast-align, which warns when a 7697 /// pointer cast increases the alignment requirements. 7698 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 7699 // This is actually a lot of work to potentially be doing on every 7700 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 7701 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 7702 return; 7703 7704 // Ignore dependent types. 7705 if (T->isDependentType() || Op->getType()->isDependentType()) 7706 return; 7707 7708 // Require that the destination be a pointer type. 7709 const PointerType *DestPtr = T->getAs<PointerType>(); 7710 if (!DestPtr) return; 7711 7712 // If the destination has alignment 1, we're done. 7713 QualType DestPointee = DestPtr->getPointeeType(); 7714 if (DestPointee->isIncompleteType()) return; 7715 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 7716 if (DestAlign.isOne()) return; 7717 7718 // Require that the source be a pointer type. 7719 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 7720 if (!SrcPtr) return; 7721 QualType SrcPointee = SrcPtr->getPointeeType(); 7722 7723 // Whitelist casts from cv void*. We already implicitly 7724 // whitelisted casts to cv void*, since they have alignment 1. 7725 // Also whitelist casts involving incomplete types, which implicitly 7726 // includes 'void'. 7727 if (SrcPointee->isIncompleteType()) return; 7728 7729 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 7730 if (SrcAlign >= DestAlign) return; 7731 7732 Diag(TRange.getBegin(), diag::warn_cast_align) 7733 << Op->getType() << T 7734 << static_cast<unsigned>(SrcAlign.getQuantity()) 7735 << static_cast<unsigned>(DestAlign.getQuantity()) 7736 << TRange << Op->getSourceRange(); 7737 } 7738 7739 static const Type* getElementType(const Expr *BaseExpr) { 7740 const Type* EltType = BaseExpr->getType().getTypePtr(); 7741 if (EltType->isAnyPointerType()) 7742 return EltType->getPointeeType().getTypePtr(); 7743 else if (EltType->isArrayType()) 7744 return EltType->getBaseElementTypeUnsafe(); 7745 return EltType; 7746 } 7747 7748 /// \brief Check whether this array fits the idiom of a size-one tail padded 7749 /// array member of a struct. 7750 /// 7751 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 7752 /// commonly used to emulate flexible arrays in C89 code. 7753 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, 7754 const NamedDecl *ND) { 7755 if (Size != 1 || !ND) return false; 7756 7757 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 7758 if (!FD) return false; 7759 7760 // Don't consider sizes resulting from macro expansions or template argument 7761 // substitution to form C89 tail-padded arrays. 7762 7763 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 7764 while (TInfo) { 7765 TypeLoc TL = TInfo->getTypeLoc(); 7766 // Look through typedefs. 7767 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 7768 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 7769 TInfo = TDL->getTypeSourceInfo(); 7770 continue; 7771 } 7772 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 7773 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 7774 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 7775 return false; 7776 } 7777 break; 7778 } 7779 7780 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 7781 if (!RD) return false; 7782 if (RD->isUnion()) return false; 7783 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 7784 if (!CRD->isStandardLayout()) return false; 7785 } 7786 7787 // See if this is the last field decl in the record. 7788 const Decl *D = FD; 7789 while ((D = D->getNextDeclInContext())) 7790 if (isa<FieldDecl>(D)) 7791 return false; 7792 return true; 7793 } 7794 7795 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 7796 const ArraySubscriptExpr *ASE, 7797 bool AllowOnePastEnd, bool IndexNegated) { 7798 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 7799 if (IndexExpr->isValueDependent()) 7800 return; 7801 7802 const Type *EffectiveType = getElementType(BaseExpr); 7803 BaseExpr = BaseExpr->IgnoreParenCasts(); 7804 const ConstantArrayType *ArrayTy = 7805 Context.getAsConstantArrayType(BaseExpr->getType()); 7806 if (!ArrayTy) 7807 return; 7808 7809 llvm::APSInt index; 7810 if (!IndexExpr->EvaluateAsInt(index, Context)) 7811 return; 7812 if (IndexNegated) 7813 index = -index; 7814 7815 const NamedDecl *ND = nullptr; 7816 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 7817 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 7818 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 7819 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 7820 7821 if (index.isUnsigned() || !index.isNegative()) { 7822 llvm::APInt size = ArrayTy->getSize(); 7823 if (!size.isStrictlyPositive()) 7824 return; 7825 7826 const Type* BaseType = getElementType(BaseExpr); 7827 if (BaseType != EffectiveType) { 7828 // Make sure we're comparing apples to apples when comparing index to size 7829 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 7830 uint64_t array_typesize = Context.getTypeSize(BaseType); 7831 // Handle ptrarith_typesize being zero, such as when casting to void* 7832 if (!ptrarith_typesize) ptrarith_typesize = 1; 7833 if (ptrarith_typesize != array_typesize) { 7834 // There's a cast to a different size type involved 7835 uint64_t ratio = array_typesize / ptrarith_typesize; 7836 // TODO: Be smarter about handling cases where array_typesize is not a 7837 // multiple of ptrarith_typesize 7838 if (ptrarith_typesize * ratio == array_typesize) 7839 size *= llvm::APInt(size.getBitWidth(), ratio); 7840 } 7841 } 7842 7843 if (size.getBitWidth() > index.getBitWidth()) 7844 index = index.zext(size.getBitWidth()); 7845 else if (size.getBitWidth() < index.getBitWidth()) 7846 size = size.zext(index.getBitWidth()); 7847 7848 // For array subscripting the index must be less than size, but for pointer 7849 // arithmetic also allow the index (offset) to be equal to size since 7850 // computing the next address after the end of the array is legal and 7851 // commonly done e.g. in C++ iterators and range-based for loops. 7852 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 7853 return; 7854 7855 // Also don't warn for arrays of size 1 which are members of some 7856 // structure. These are often used to approximate flexible arrays in C89 7857 // code. 7858 if (IsTailPaddedMemberArray(*this, size, ND)) 7859 return; 7860 7861 // Suppress the warning if the subscript expression (as identified by the 7862 // ']' location) and the index expression are both from macro expansions 7863 // within a system header. 7864 if (ASE) { 7865 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 7866 ASE->getRBracketLoc()); 7867 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 7868 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 7869 IndexExpr->getLocStart()); 7870 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 7871 return; 7872 } 7873 } 7874 7875 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 7876 if (ASE) 7877 DiagID = diag::warn_array_index_exceeds_bounds; 7878 7879 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 7880 PDiag(DiagID) << index.toString(10, true) 7881 << size.toString(10, true) 7882 << (unsigned)size.getLimitedValue(~0U) 7883 << IndexExpr->getSourceRange()); 7884 } else { 7885 unsigned DiagID = diag::warn_array_index_precedes_bounds; 7886 if (!ASE) { 7887 DiagID = diag::warn_ptr_arith_precedes_bounds; 7888 if (index.isNegative()) index = -index; 7889 } 7890 7891 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 7892 PDiag(DiagID) << index.toString(10, true) 7893 << IndexExpr->getSourceRange()); 7894 } 7895 7896 if (!ND) { 7897 // Try harder to find a NamedDecl to point at in the note. 7898 while (const ArraySubscriptExpr *ASE = 7899 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 7900 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 7901 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 7902 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 7903 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 7904 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 7905 } 7906 7907 if (ND) 7908 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 7909 PDiag(diag::note_array_index_out_of_bounds) 7910 << ND->getDeclName()); 7911 } 7912 7913 void Sema::CheckArrayAccess(const Expr *expr) { 7914 int AllowOnePastEnd = 0; 7915 while (expr) { 7916 expr = expr->IgnoreParenImpCasts(); 7917 switch (expr->getStmtClass()) { 7918 case Stmt::ArraySubscriptExprClass: { 7919 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 7920 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 7921 AllowOnePastEnd > 0); 7922 return; 7923 } 7924 case Stmt::UnaryOperatorClass: { 7925 // Only unwrap the * and & unary operators 7926 const UnaryOperator *UO = cast<UnaryOperator>(expr); 7927 expr = UO->getSubExpr(); 7928 switch (UO->getOpcode()) { 7929 case UO_AddrOf: 7930 AllowOnePastEnd++; 7931 break; 7932 case UO_Deref: 7933 AllowOnePastEnd--; 7934 break; 7935 default: 7936 return; 7937 } 7938 break; 7939 } 7940 case Stmt::ConditionalOperatorClass: { 7941 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 7942 if (const Expr *lhs = cond->getLHS()) 7943 CheckArrayAccess(lhs); 7944 if (const Expr *rhs = cond->getRHS()) 7945 CheckArrayAccess(rhs); 7946 return; 7947 } 7948 default: 7949 return; 7950 } 7951 } 7952 } 7953 7954 //===--- CHECK: Objective-C retain cycles ----------------------------------// 7955 7956 namespace { 7957 struct RetainCycleOwner { 7958 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 7959 VarDecl *Variable; 7960 SourceRange Range; 7961 SourceLocation Loc; 7962 bool Indirect; 7963 7964 void setLocsFrom(Expr *e) { 7965 Loc = e->getExprLoc(); 7966 Range = e->getSourceRange(); 7967 } 7968 }; 7969 } 7970 7971 /// Consider whether capturing the given variable can possibly lead to 7972 /// a retain cycle. 7973 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 7974 // In ARC, it's captured strongly iff the variable has __strong 7975 // lifetime. In MRR, it's captured strongly if the variable is 7976 // __block and has an appropriate type. 7977 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 7978 return false; 7979 7980 owner.Variable = var; 7981 if (ref) 7982 owner.setLocsFrom(ref); 7983 return true; 7984 } 7985 7986 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 7987 while (true) { 7988 e = e->IgnoreParens(); 7989 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 7990 switch (cast->getCastKind()) { 7991 case CK_BitCast: 7992 case CK_LValueBitCast: 7993 case CK_LValueToRValue: 7994 case CK_ARCReclaimReturnedObject: 7995 e = cast->getSubExpr(); 7996 continue; 7997 7998 default: 7999 return false; 8000 } 8001 } 8002 8003 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 8004 ObjCIvarDecl *ivar = ref->getDecl(); 8005 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 8006 return false; 8007 8008 // Try to find a retain cycle in the base. 8009 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 8010 return false; 8011 8012 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 8013 owner.Indirect = true; 8014 return true; 8015 } 8016 8017 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 8018 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 8019 if (!var) return false; 8020 return considerVariable(var, ref, owner); 8021 } 8022 8023 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 8024 if (member->isArrow()) return false; 8025 8026 // Don't count this as an indirect ownership. 8027 e = member->getBase(); 8028 continue; 8029 } 8030 8031 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 8032 // Only pay attention to pseudo-objects on property references. 8033 ObjCPropertyRefExpr *pre 8034 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 8035 ->IgnoreParens()); 8036 if (!pre) return false; 8037 if (pre->isImplicitProperty()) return false; 8038 ObjCPropertyDecl *property = pre->getExplicitProperty(); 8039 if (!property->isRetaining() && 8040 !(property->getPropertyIvarDecl() && 8041 property->getPropertyIvarDecl()->getType() 8042 .getObjCLifetime() == Qualifiers::OCL_Strong)) 8043 return false; 8044 8045 owner.Indirect = true; 8046 if (pre->isSuperReceiver()) { 8047 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 8048 if (!owner.Variable) 8049 return false; 8050 owner.Loc = pre->getLocation(); 8051 owner.Range = pre->getSourceRange(); 8052 return true; 8053 } 8054 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 8055 ->getSourceExpr()); 8056 continue; 8057 } 8058 8059 // Array ivars? 8060 8061 return false; 8062 } 8063 } 8064 8065 namespace { 8066 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 8067 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 8068 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 8069 Context(Context), Variable(variable), Capturer(nullptr), 8070 VarWillBeReased(false) {} 8071 ASTContext &Context; 8072 VarDecl *Variable; 8073 Expr *Capturer; 8074 bool VarWillBeReased; 8075 8076 void VisitDeclRefExpr(DeclRefExpr *ref) { 8077 if (ref->getDecl() == Variable && !Capturer) 8078 Capturer = ref; 8079 } 8080 8081 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 8082 if (Capturer) return; 8083 Visit(ref->getBase()); 8084 if (Capturer && ref->isFreeIvar()) 8085 Capturer = ref; 8086 } 8087 8088 void VisitBlockExpr(BlockExpr *block) { 8089 // Look inside nested blocks 8090 if (block->getBlockDecl()->capturesVariable(Variable)) 8091 Visit(block->getBlockDecl()->getBody()); 8092 } 8093 8094 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 8095 if (Capturer) return; 8096 if (OVE->getSourceExpr()) 8097 Visit(OVE->getSourceExpr()); 8098 } 8099 void VisitBinaryOperator(BinaryOperator *BinOp) { 8100 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 8101 return; 8102 Expr *LHS = BinOp->getLHS(); 8103 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 8104 if (DRE->getDecl() != Variable) 8105 return; 8106 if (Expr *RHS = BinOp->getRHS()) { 8107 RHS = RHS->IgnoreParenCasts(); 8108 llvm::APSInt Value; 8109 VarWillBeReased = 8110 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 8111 } 8112 } 8113 } 8114 }; 8115 } 8116 8117 /// Check whether the given argument is a block which captures a 8118 /// variable. 8119 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 8120 assert(owner.Variable && owner.Loc.isValid()); 8121 8122 e = e->IgnoreParenCasts(); 8123 8124 // Look through [^{...} copy] and Block_copy(^{...}). 8125 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 8126 Selector Cmd = ME->getSelector(); 8127 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 8128 e = ME->getInstanceReceiver(); 8129 if (!e) 8130 return nullptr; 8131 e = e->IgnoreParenCasts(); 8132 } 8133 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 8134 if (CE->getNumArgs() == 1) { 8135 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 8136 if (Fn) { 8137 const IdentifierInfo *FnI = Fn->getIdentifier(); 8138 if (FnI && FnI->isStr("_Block_copy")) { 8139 e = CE->getArg(0)->IgnoreParenCasts(); 8140 } 8141 } 8142 } 8143 } 8144 8145 BlockExpr *block = dyn_cast<BlockExpr>(e); 8146 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 8147 return nullptr; 8148 8149 FindCaptureVisitor visitor(S.Context, owner.Variable); 8150 visitor.Visit(block->getBlockDecl()->getBody()); 8151 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 8152 } 8153 8154 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 8155 RetainCycleOwner &owner) { 8156 assert(capturer); 8157 assert(owner.Variable && owner.Loc.isValid()); 8158 8159 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 8160 << owner.Variable << capturer->getSourceRange(); 8161 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 8162 << owner.Indirect << owner.Range; 8163 } 8164 8165 /// Check for a keyword selector that starts with the word 'add' or 8166 /// 'set'. 8167 static bool isSetterLikeSelector(Selector sel) { 8168 if (sel.isUnarySelector()) return false; 8169 8170 StringRef str = sel.getNameForSlot(0); 8171 while (!str.empty() && str.front() == '_') str = str.substr(1); 8172 if (str.startswith("set")) 8173 str = str.substr(3); 8174 else if (str.startswith("add")) { 8175 // Specially whitelist 'addOperationWithBlock:'. 8176 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 8177 return false; 8178 str = str.substr(3); 8179 } 8180 else 8181 return false; 8182 8183 if (str.empty()) return true; 8184 return !isLowercase(str.front()); 8185 } 8186 8187 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 8188 ObjCMessageExpr *Message) { 8189 if (S.NSMutableArrayPointer.isNull()) { 8190 IdentifierInfo *NSMutableArrayId = 8191 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray); 8192 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId, 8193 Message->getLocStart(), 8194 Sema::LookupOrdinaryName); 8195 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 8196 if (!InterfaceDecl) { 8197 return None; 8198 } 8199 QualType NSMutableArrayObject = 8200 S.Context.getObjCInterfaceType(InterfaceDecl); 8201 S.NSMutableArrayPointer = 8202 S.Context.getObjCObjectPointerType(NSMutableArrayObject); 8203 } 8204 8205 if (S.NSMutableArrayPointer != Message->getReceiverType()) { 8206 return None; 8207 } 8208 8209 Selector Sel = Message->getSelector(); 8210 8211 Optional<NSAPI::NSArrayMethodKind> MKOpt = 8212 S.NSAPIObj->getNSArrayMethodKind(Sel); 8213 if (!MKOpt) { 8214 return None; 8215 } 8216 8217 NSAPI::NSArrayMethodKind MK = *MKOpt; 8218 8219 switch (MK) { 8220 case NSAPI::NSMutableArr_addObject: 8221 case NSAPI::NSMutableArr_insertObjectAtIndex: 8222 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 8223 return 0; 8224 case NSAPI::NSMutableArr_replaceObjectAtIndex: 8225 return 1; 8226 8227 default: 8228 return None; 8229 } 8230 8231 return None; 8232 } 8233 8234 static 8235 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 8236 ObjCMessageExpr *Message) { 8237 8238 if (S.NSMutableDictionaryPointer.isNull()) { 8239 IdentifierInfo *NSMutableDictionaryId = 8240 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary); 8241 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId, 8242 Message->getLocStart(), 8243 Sema::LookupOrdinaryName); 8244 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 8245 if (!InterfaceDecl) { 8246 return None; 8247 } 8248 QualType NSMutableDictionaryObject = 8249 S.Context.getObjCInterfaceType(InterfaceDecl); 8250 S.NSMutableDictionaryPointer = 8251 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject); 8252 } 8253 8254 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) { 8255 return None; 8256 } 8257 8258 Selector Sel = Message->getSelector(); 8259 8260 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 8261 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 8262 if (!MKOpt) { 8263 return None; 8264 } 8265 8266 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 8267 8268 switch (MK) { 8269 case NSAPI::NSMutableDict_setObjectForKey: 8270 case NSAPI::NSMutableDict_setValueForKey: 8271 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 8272 return 0; 8273 8274 default: 8275 return None; 8276 } 8277 8278 return None; 8279 } 8280 8281 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 8282 8283 ObjCInterfaceDecl *InterfaceDecl; 8284 if (S.NSMutableSetPointer.isNull()) { 8285 IdentifierInfo *NSMutableSetId = 8286 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet); 8287 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId, 8288 Message->getLocStart(), 8289 Sema::LookupOrdinaryName); 8290 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 8291 if (InterfaceDecl) { 8292 QualType NSMutableSetObject = 8293 S.Context.getObjCInterfaceType(InterfaceDecl); 8294 S.NSMutableSetPointer = 8295 S.Context.getObjCObjectPointerType(NSMutableSetObject); 8296 } 8297 } 8298 8299 if (S.NSCountedSetPointer.isNull()) { 8300 IdentifierInfo *NSCountedSetId = 8301 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet); 8302 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId, 8303 Message->getLocStart(), 8304 Sema::LookupOrdinaryName); 8305 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 8306 if (InterfaceDecl) { 8307 QualType NSCountedSetObject = 8308 S.Context.getObjCInterfaceType(InterfaceDecl); 8309 S.NSCountedSetPointer = 8310 S.Context.getObjCObjectPointerType(NSCountedSetObject); 8311 } 8312 } 8313 8314 if (S.NSMutableOrderedSetPointer.isNull()) { 8315 IdentifierInfo *NSOrderedSetId = 8316 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet); 8317 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId, 8318 Message->getLocStart(), 8319 Sema::LookupOrdinaryName); 8320 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 8321 if (InterfaceDecl) { 8322 QualType NSOrderedSetObject = 8323 S.Context.getObjCInterfaceType(InterfaceDecl); 8324 S.NSMutableOrderedSetPointer = 8325 S.Context.getObjCObjectPointerType(NSOrderedSetObject); 8326 } 8327 } 8328 8329 QualType ReceiverType = Message->getReceiverType(); 8330 8331 bool IsMutableSet = !S.NSMutableSetPointer.isNull() && 8332 ReceiverType == S.NSMutableSetPointer; 8333 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() && 8334 ReceiverType == S.NSMutableOrderedSetPointer; 8335 bool IsCountedSet = !S.NSCountedSetPointer.isNull() && 8336 ReceiverType == S.NSCountedSetPointer; 8337 8338 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) { 8339 return None; 8340 } 8341 8342 Selector Sel = Message->getSelector(); 8343 8344 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 8345 if (!MKOpt) { 8346 return None; 8347 } 8348 8349 NSAPI::NSSetMethodKind MK = *MKOpt; 8350 8351 switch (MK) { 8352 case NSAPI::NSMutableSet_addObject: 8353 case NSAPI::NSOrderedSet_setObjectAtIndex: 8354 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 8355 case NSAPI::NSOrderedSet_insertObjectAtIndex: 8356 return 0; 8357 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 8358 return 1; 8359 } 8360 8361 return None; 8362 } 8363 8364 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 8365 if (!Message->isInstanceMessage()) { 8366 return; 8367 } 8368 8369 Optional<int> ArgOpt; 8370 8371 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 8372 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 8373 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 8374 return; 8375 } 8376 8377 int ArgIndex = *ArgOpt; 8378 8379 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 8380 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 8381 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 8382 } 8383 8384 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 8385 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 8386 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 8387 } 8388 8389 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 8390 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 8391 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 8392 ValueDecl *Decl = ReceiverRE->getDecl(); 8393 Diag(Message->getSourceRange().getBegin(), 8394 diag::warn_objc_circular_container) 8395 << Decl->getName(); 8396 Diag(Decl->getLocation(), 8397 diag::note_objc_circular_container_declared_here) 8398 << Decl->getName(); 8399 } 8400 } 8401 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 8402 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 8403 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 8404 ObjCIvarDecl *Decl = IvarRE->getDecl(); 8405 Diag(Message->getSourceRange().getBegin(), 8406 diag::warn_objc_circular_container) 8407 << Decl->getName(); 8408 Diag(Decl->getLocation(), 8409 diag::note_objc_circular_container_declared_here) 8410 << Decl->getName(); 8411 } 8412 } 8413 } 8414 8415 } 8416 8417 /// Check a message send to see if it's likely to cause a retain cycle. 8418 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 8419 // Only check instance methods whose selector looks like a setter. 8420 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 8421 return; 8422 8423 // Try to find a variable that the receiver is strongly owned by. 8424 RetainCycleOwner owner; 8425 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 8426 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 8427 return; 8428 } else { 8429 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 8430 owner.Variable = getCurMethodDecl()->getSelfDecl(); 8431 owner.Loc = msg->getSuperLoc(); 8432 owner.Range = msg->getSuperLoc(); 8433 } 8434 8435 // Check whether the receiver is captured by any of the arguments. 8436 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 8437 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 8438 return diagnoseRetainCycle(*this, capturer, owner); 8439 } 8440 8441 /// Check a property assign to see if it's likely to cause a retain cycle. 8442 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 8443 RetainCycleOwner owner; 8444 if (!findRetainCycleOwner(*this, receiver, owner)) 8445 return; 8446 8447 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 8448 diagnoseRetainCycle(*this, capturer, owner); 8449 } 8450 8451 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 8452 RetainCycleOwner Owner; 8453 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 8454 return; 8455 8456 // Because we don't have an expression for the variable, we have to set the 8457 // location explicitly here. 8458 Owner.Loc = Var->getLocation(); 8459 Owner.Range = Var->getSourceRange(); 8460 8461 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 8462 diagnoseRetainCycle(*this, Capturer, Owner); 8463 } 8464 8465 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 8466 Expr *RHS, bool isProperty) { 8467 // Check if RHS is an Objective-C object literal, which also can get 8468 // immediately zapped in a weak reference. Note that we explicitly 8469 // allow ObjCStringLiterals, since those are designed to never really die. 8470 RHS = RHS->IgnoreParenImpCasts(); 8471 8472 // This enum needs to match with the 'select' in 8473 // warn_objc_arc_literal_assign (off-by-1). 8474 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 8475 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 8476 return false; 8477 8478 S.Diag(Loc, diag::warn_arc_literal_assign) 8479 << (unsigned) Kind 8480 << (isProperty ? 0 : 1) 8481 << RHS->getSourceRange(); 8482 8483 return true; 8484 } 8485 8486 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 8487 Qualifiers::ObjCLifetime LT, 8488 Expr *RHS, bool isProperty) { 8489 // Strip off any implicit cast added to get to the one ARC-specific. 8490 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 8491 if (cast->getCastKind() == CK_ARCConsumeObject) { 8492 S.Diag(Loc, diag::warn_arc_retained_assign) 8493 << (LT == Qualifiers::OCL_ExplicitNone) 8494 << (isProperty ? 0 : 1) 8495 << RHS->getSourceRange(); 8496 return true; 8497 } 8498 RHS = cast->getSubExpr(); 8499 } 8500 8501 if (LT == Qualifiers::OCL_Weak && 8502 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 8503 return true; 8504 8505 return false; 8506 } 8507 8508 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 8509 QualType LHS, Expr *RHS) { 8510 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 8511 8512 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 8513 return false; 8514 8515 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 8516 return true; 8517 8518 return false; 8519 } 8520 8521 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 8522 Expr *LHS, Expr *RHS) { 8523 QualType LHSType; 8524 // PropertyRef on LHS type need be directly obtained from 8525 // its declaration as it has a PseudoType. 8526 ObjCPropertyRefExpr *PRE 8527 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 8528 if (PRE && !PRE->isImplicitProperty()) { 8529 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 8530 if (PD) 8531 LHSType = PD->getType(); 8532 } 8533 8534 if (LHSType.isNull()) 8535 LHSType = LHS->getType(); 8536 8537 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 8538 8539 if (LT == Qualifiers::OCL_Weak) { 8540 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 8541 getCurFunction()->markSafeWeakUse(LHS); 8542 } 8543 8544 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 8545 return; 8546 8547 // FIXME. Check for other life times. 8548 if (LT != Qualifiers::OCL_None) 8549 return; 8550 8551 if (PRE) { 8552 if (PRE->isImplicitProperty()) 8553 return; 8554 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 8555 if (!PD) 8556 return; 8557 8558 unsigned Attributes = PD->getPropertyAttributes(); 8559 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 8560 // when 'assign' attribute was not explicitly specified 8561 // by user, ignore it and rely on property type itself 8562 // for lifetime info. 8563 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 8564 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 8565 LHSType->isObjCRetainableType()) 8566 return; 8567 8568 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 8569 if (cast->getCastKind() == CK_ARCConsumeObject) { 8570 Diag(Loc, diag::warn_arc_retained_property_assign) 8571 << RHS->getSourceRange(); 8572 return; 8573 } 8574 RHS = cast->getSubExpr(); 8575 } 8576 } 8577 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 8578 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 8579 return; 8580 } 8581 } 8582 } 8583 8584 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 8585 8586 namespace { 8587 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 8588 SourceLocation StmtLoc, 8589 const NullStmt *Body) { 8590 // Do not warn if the body is a macro that expands to nothing, e.g: 8591 // 8592 // #define CALL(x) 8593 // if (condition) 8594 // CALL(0); 8595 // 8596 if (Body->hasLeadingEmptyMacro()) 8597 return false; 8598 8599 // Get line numbers of statement and body. 8600 bool StmtLineInvalid; 8601 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc, 8602 &StmtLineInvalid); 8603 if (StmtLineInvalid) 8604 return false; 8605 8606 bool BodyLineInvalid; 8607 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 8608 &BodyLineInvalid); 8609 if (BodyLineInvalid) 8610 return false; 8611 8612 // Warn if null statement and body are on the same line. 8613 if (StmtLine != BodyLine) 8614 return false; 8615 8616 return true; 8617 } 8618 } // Unnamed namespace 8619 8620 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 8621 const Stmt *Body, 8622 unsigned DiagID) { 8623 // Since this is a syntactic check, don't emit diagnostic for template 8624 // instantiations, this just adds noise. 8625 if (CurrentInstantiationScope) 8626 return; 8627 8628 // The body should be a null statement. 8629 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 8630 if (!NBody) 8631 return; 8632 8633 // Do the usual checks. 8634 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 8635 return; 8636 8637 Diag(NBody->getSemiLoc(), DiagID); 8638 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 8639 } 8640 8641 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 8642 const Stmt *PossibleBody) { 8643 assert(!CurrentInstantiationScope); // Ensured by caller 8644 8645 SourceLocation StmtLoc; 8646 const Stmt *Body; 8647 unsigned DiagID; 8648 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 8649 StmtLoc = FS->getRParenLoc(); 8650 Body = FS->getBody(); 8651 DiagID = diag::warn_empty_for_body; 8652 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 8653 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 8654 Body = WS->getBody(); 8655 DiagID = diag::warn_empty_while_body; 8656 } else 8657 return; // Neither `for' nor `while'. 8658 8659 // The body should be a null statement. 8660 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 8661 if (!NBody) 8662 return; 8663 8664 // Skip expensive checks if diagnostic is disabled. 8665 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 8666 return; 8667 8668 // Do the usual checks. 8669 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 8670 return; 8671 8672 // `for(...);' and `while(...);' are popular idioms, so in order to keep 8673 // noise level low, emit diagnostics only if for/while is followed by a 8674 // CompoundStmt, e.g.: 8675 // for (int i = 0; i < n; i++); 8676 // { 8677 // a(i); 8678 // } 8679 // or if for/while is followed by a statement with more indentation 8680 // than for/while itself: 8681 // for (int i = 0; i < n; i++); 8682 // a(i); 8683 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 8684 if (!ProbableTypo) { 8685 bool BodyColInvalid; 8686 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 8687 PossibleBody->getLocStart(), 8688 &BodyColInvalid); 8689 if (BodyColInvalid) 8690 return; 8691 8692 bool StmtColInvalid; 8693 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 8694 S->getLocStart(), 8695 &StmtColInvalid); 8696 if (StmtColInvalid) 8697 return; 8698 8699 if (BodyCol > StmtCol) 8700 ProbableTypo = true; 8701 } 8702 8703 if (ProbableTypo) { 8704 Diag(NBody->getSemiLoc(), DiagID); 8705 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 8706 } 8707 } 8708 8709 //===--- CHECK: Warn on self move with std::move. -------------------------===// 8710 8711 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 8712 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 8713 SourceLocation OpLoc) { 8714 8715 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 8716 return; 8717 8718 if (!ActiveTemplateInstantiations.empty()) 8719 return; 8720 8721 // Strip parens and casts away. 8722 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8723 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8724 8725 // Check for a call expression 8726 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 8727 if (!CE || CE->getNumArgs() != 1) 8728 return; 8729 8730 // Check for a call to std::move 8731 const FunctionDecl *FD = CE->getDirectCallee(); 8732 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 8733 !FD->getIdentifier()->isStr("move")) 8734 return; 8735 8736 // Get argument from std::move 8737 RHSExpr = CE->getArg(0); 8738 8739 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8740 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8741 8742 // Two DeclRefExpr's, check that the decls are the same. 8743 if (LHSDeclRef && RHSDeclRef) { 8744 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 8745 return; 8746 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 8747 RHSDeclRef->getDecl()->getCanonicalDecl()) 8748 return; 8749 8750 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 8751 << LHSExpr->getSourceRange() 8752 << RHSExpr->getSourceRange(); 8753 return; 8754 } 8755 8756 // Member variables require a different approach to check for self moves. 8757 // MemberExpr's are the same if every nested MemberExpr refers to the same 8758 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 8759 // the base Expr's are CXXThisExpr's. 8760 const Expr *LHSBase = LHSExpr; 8761 const Expr *RHSBase = RHSExpr; 8762 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 8763 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 8764 if (!LHSME || !RHSME) 8765 return; 8766 8767 while (LHSME && RHSME) { 8768 if (LHSME->getMemberDecl()->getCanonicalDecl() != 8769 RHSME->getMemberDecl()->getCanonicalDecl()) 8770 return; 8771 8772 LHSBase = LHSME->getBase(); 8773 RHSBase = RHSME->getBase(); 8774 LHSME = dyn_cast<MemberExpr>(LHSBase); 8775 RHSME = dyn_cast<MemberExpr>(RHSBase); 8776 } 8777 8778 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 8779 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 8780 if (LHSDeclRef && RHSDeclRef) { 8781 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 8782 return; 8783 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 8784 RHSDeclRef->getDecl()->getCanonicalDecl()) 8785 return; 8786 8787 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 8788 << LHSExpr->getSourceRange() 8789 << RHSExpr->getSourceRange(); 8790 return; 8791 } 8792 8793 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 8794 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 8795 << LHSExpr->getSourceRange() 8796 << RHSExpr->getSourceRange(); 8797 } 8798 8799 //===--- Layout compatibility ----------------------------------------------// 8800 8801 namespace { 8802 8803 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 8804 8805 /// \brief Check if two enumeration types are layout-compatible. 8806 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 8807 // C++11 [dcl.enum] p8: 8808 // Two enumeration types are layout-compatible if they have the same 8809 // underlying type. 8810 return ED1->isComplete() && ED2->isComplete() && 8811 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 8812 } 8813 8814 /// \brief Check if two fields are layout-compatible. 8815 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 8816 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 8817 return false; 8818 8819 if (Field1->isBitField() != Field2->isBitField()) 8820 return false; 8821 8822 if (Field1->isBitField()) { 8823 // Make sure that the bit-fields are the same length. 8824 unsigned Bits1 = Field1->getBitWidthValue(C); 8825 unsigned Bits2 = Field2->getBitWidthValue(C); 8826 8827 if (Bits1 != Bits2) 8828 return false; 8829 } 8830 8831 return true; 8832 } 8833 8834 /// \brief Check if two standard-layout structs are layout-compatible. 8835 /// (C++11 [class.mem] p17) 8836 bool isLayoutCompatibleStruct(ASTContext &C, 8837 RecordDecl *RD1, 8838 RecordDecl *RD2) { 8839 // If both records are C++ classes, check that base classes match. 8840 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 8841 // If one of records is a CXXRecordDecl we are in C++ mode, 8842 // thus the other one is a CXXRecordDecl, too. 8843 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 8844 // Check number of base classes. 8845 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 8846 return false; 8847 8848 // Check the base classes. 8849 for (CXXRecordDecl::base_class_const_iterator 8850 Base1 = D1CXX->bases_begin(), 8851 BaseEnd1 = D1CXX->bases_end(), 8852 Base2 = D2CXX->bases_begin(); 8853 Base1 != BaseEnd1; 8854 ++Base1, ++Base2) { 8855 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 8856 return false; 8857 } 8858 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 8859 // If only RD2 is a C++ class, it should have zero base classes. 8860 if (D2CXX->getNumBases() > 0) 8861 return false; 8862 } 8863 8864 // Check the fields. 8865 RecordDecl::field_iterator Field2 = RD2->field_begin(), 8866 Field2End = RD2->field_end(), 8867 Field1 = RD1->field_begin(), 8868 Field1End = RD1->field_end(); 8869 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 8870 if (!isLayoutCompatible(C, *Field1, *Field2)) 8871 return false; 8872 } 8873 if (Field1 != Field1End || Field2 != Field2End) 8874 return false; 8875 8876 return true; 8877 } 8878 8879 /// \brief Check if two standard-layout unions are layout-compatible. 8880 /// (C++11 [class.mem] p18) 8881 bool isLayoutCompatibleUnion(ASTContext &C, 8882 RecordDecl *RD1, 8883 RecordDecl *RD2) { 8884 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 8885 for (auto *Field2 : RD2->fields()) 8886 UnmatchedFields.insert(Field2); 8887 8888 for (auto *Field1 : RD1->fields()) { 8889 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 8890 I = UnmatchedFields.begin(), 8891 E = UnmatchedFields.end(); 8892 8893 for ( ; I != E; ++I) { 8894 if (isLayoutCompatible(C, Field1, *I)) { 8895 bool Result = UnmatchedFields.erase(*I); 8896 (void) Result; 8897 assert(Result); 8898 break; 8899 } 8900 } 8901 if (I == E) 8902 return false; 8903 } 8904 8905 return UnmatchedFields.empty(); 8906 } 8907 8908 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 8909 if (RD1->isUnion() != RD2->isUnion()) 8910 return false; 8911 8912 if (RD1->isUnion()) 8913 return isLayoutCompatibleUnion(C, RD1, RD2); 8914 else 8915 return isLayoutCompatibleStruct(C, RD1, RD2); 8916 } 8917 8918 /// \brief Check if two types are layout-compatible in C++11 sense. 8919 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 8920 if (T1.isNull() || T2.isNull()) 8921 return false; 8922 8923 // C++11 [basic.types] p11: 8924 // If two types T1 and T2 are the same type, then T1 and T2 are 8925 // layout-compatible types. 8926 if (C.hasSameType(T1, T2)) 8927 return true; 8928 8929 T1 = T1.getCanonicalType().getUnqualifiedType(); 8930 T2 = T2.getCanonicalType().getUnqualifiedType(); 8931 8932 const Type::TypeClass TC1 = T1->getTypeClass(); 8933 const Type::TypeClass TC2 = T2->getTypeClass(); 8934 8935 if (TC1 != TC2) 8936 return false; 8937 8938 if (TC1 == Type::Enum) { 8939 return isLayoutCompatible(C, 8940 cast<EnumType>(T1)->getDecl(), 8941 cast<EnumType>(T2)->getDecl()); 8942 } else if (TC1 == Type::Record) { 8943 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 8944 return false; 8945 8946 return isLayoutCompatible(C, 8947 cast<RecordType>(T1)->getDecl(), 8948 cast<RecordType>(T2)->getDecl()); 8949 } 8950 8951 return false; 8952 } 8953 } 8954 8955 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 8956 8957 namespace { 8958 /// \brief Given a type tag expression find the type tag itself. 8959 /// 8960 /// \param TypeExpr Type tag expression, as it appears in user's code. 8961 /// 8962 /// \param VD Declaration of an identifier that appears in a type tag. 8963 /// 8964 /// \param MagicValue Type tag magic value. 8965 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 8966 const ValueDecl **VD, uint64_t *MagicValue) { 8967 while(true) { 8968 if (!TypeExpr) 8969 return false; 8970 8971 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 8972 8973 switch (TypeExpr->getStmtClass()) { 8974 case Stmt::UnaryOperatorClass: { 8975 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 8976 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 8977 TypeExpr = UO->getSubExpr(); 8978 continue; 8979 } 8980 return false; 8981 } 8982 8983 case Stmt::DeclRefExprClass: { 8984 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 8985 *VD = DRE->getDecl(); 8986 return true; 8987 } 8988 8989 case Stmt::IntegerLiteralClass: { 8990 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 8991 llvm::APInt MagicValueAPInt = IL->getValue(); 8992 if (MagicValueAPInt.getActiveBits() <= 64) { 8993 *MagicValue = MagicValueAPInt.getZExtValue(); 8994 return true; 8995 } else 8996 return false; 8997 } 8998 8999 case Stmt::BinaryConditionalOperatorClass: 9000 case Stmt::ConditionalOperatorClass: { 9001 const AbstractConditionalOperator *ACO = 9002 cast<AbstractConditionalOperator>(TypeExpr); 9003 bool Result; 9004 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 9005 if (Result) 9006 TypeExpr = ACO->getTrueExpr(); 9007 else 9008 TypeExpr = ACO->getFalseExpr(); 9009 continue; 9010 } 9011 return false; 9012 } 9013 9014 case Stmt::BinaryOperatorClass: { 9015 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 9016 if (BO->getOpcode() == BO_Comma) { 9017 TypeExpr = BO->getRHS(); 9018 continue; 9019 } 9020 return false; 9021 } 9022 9023 default: 9024 return false; 9025 } 9026 } 9027 } 9028 9029 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 9030 /// 9031 /// \param TypeExpr Expression that specifies a type tag. 9032 /// 9033 /// \param MagicValues Registered magic values. 9034 /// 9035 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 9036 /// kind. 9037 /// 9038 /// \param TypeInfo Information about the corresponding C type. 9039 /// 9040 /// \returns true if the corresponding C type was found. 9041 bool GetMatchingCType( 9042 const IdentifierInfo *ArgumentKind, 9043 const Expr *TypeExpr, const ASTContext &Ctx, 9044 const llvm::DenseMap<Sema::TypeTagMagicValue, 9045 Sema::TypeTagData> *MagicValues, 9046 bool &FoundWrongKind, 9047 Sema::TypeTagData &TypeInfo) { 9048 FoundWrongKind = false; 9049 9050 // Variable declaration that has type_tag_for_datatype attribute. 9051 const ValueDecl *VD = nullptr; 9052 9053 uint64_t MagicValue; 9054 9055 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 9056 return false; 9057 9058 if (VD) { 9059 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 9060 if (I->getArgumentKind() != ArgumentKind) { 9061 FoundWrongKind = true; 9062 return false; 9063 } 9064 TypeInfo.Type = I->getMatchingCType(); 9065 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 9066 TypeInfo.MustBeNull = I->getMustBeNull(); 9067 return true; 9068 } 9069 return false; 9070 } 9071 9072 if (!MagicValues) 9073 return false; 9074 9075 llvm::DenseMap<Sema::TypeTagMagicValue, 9076 Sema::TypeTagData>::const_iterator I = 9077 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 9078 if (I == MagicValues->end()) 9079 return false; 9080 9081 TypeInfo = I->second; 9082 return true; 9083 } 9084 } // unnamed namespace 9085 9086 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 9087 uint64_t MagicValue, QualType Type, 9088 bool LayoutCompatible, 9089 bool MustBeNull) { 9090 if (!TypeTagForDatatypeMagicValues) 9091 TypeTagForDatatypeMagicValues.reset( 9092 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 9093 9094 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 9095 (*TypeTagForDatatypeMagicValues)[Magic] = 9096 TypeTagData(Type, LayoutCompatible, MustBeNull); 9097 } 9098 9099 namespace { 9100 bool IsSameCharType(QualType T1, QualType T2) { 9101 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 9102 if (!BT1) 9103 return false; 9104 9105 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 9106 if (!BT2) 9107 return false; 9108 9109 BuiltinType::Kind T1Kind = BT1->getKind(); 9110 BuiltinType::Kind T2Kind = BT2->getKind(); 9111 9112 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 9113 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 9114 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 9115 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 9116 } 9117 } // unnamed namespace 9118 9119 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 9120 const Expr * const *ExprArgs) { 9121 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 9122 bool IsPointerAttr = Attr->getIsPointer(); 9123 9124 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 9125 bool FoundWrongKind; 9126 TypeTagData TypeInfo; 9127 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 9128 TypeTagForDatatypeMagicValues.get(), 9129 FoundWrongKind, TypeInfo)) { 9130 if (FoundWrongKind) 9131 Diag(TypeTagExpr->getExprLoc(), 9132 diag::warn_type_tag_for_datatype_wrong_kind) 9133 << TypeTagExpr->getSourceRange(); 9134 return; 9135 } 9136 9137 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 9138 if (IsPointerAttr) { 9139 // Skip implicit cast of pointer to `void *' (as a function argument). 9140 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 9141 if (ICE->getType()->isVoidPointerType() && 9142 ICE->getCastKind() == CK_BitCast) 9143 ArgumentExpr = ICE->getSubExpr(); 9144 } 9145 QualType ArgumentType = ArgumentExpr->getType(); 9146 9147 // Passing a `void*' pointer shouldn't trigger a warning. 9148 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 9149 return; 9150 9151 if (TypeInfo.MustBeNull) { 9152 // Type tag with matching void type requires a null pointer. 9153 if (!ArgumentExpr->isNullPointerConstant(Context, 9154 Expr::NPC_ValueDependentIsNotNull)) { 9155 Diag(ArgumentExpr->getExprLoc(), 9156 diag::warn_type_safety_null_pointer_required) 9157 << ArgumentKind->getName() 9158 << ArgumentExpr->getSourceRange() 9159 << TypeTagExpr->getSourceRange(); 9160 } 9161 return; 9162 } 9163 9164 QualType RequiredType = TypeInfo.Type; 9165 if (IsPointerAttr) 9166 RequiredType = Context.getPointerType(RequiredType); 9167 9168 bool mismatch = false; 9169 if (!TypeInfo.LayoutCompatible) { 9170 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 9171 9172 // C++11 [basic.fundamental] p1: 9173 // Plain char, signed char, and unsigned char are three distinct types. 9174 // 9175 // But we treat plain `char' as equivalent to `signed char' or `unsigned 9176 // char' depending on the current char signedness mode. 9177 if (mismatch) 9178 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 9179 RequiredType->getPointeeType())) || 9180 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 9181 mismatch = false; 9182 } else 9183 if (IsPointerAttr) 9184 mismatch = !isLayoutCompatible(Context, 9185 ArgumentType->getPointeeType(), 9186 RequiredType->getPointeeType()); 9187 else 9188 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 9189 9190 if (mismatch) 9191 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 9192 << ArgumentType << ArgumentKind 9193 << TypeInfo.LayoutCompatible << RequiredType 9194 << ArgumentExpr->getSourceRange() 9195 << TypeTagExpr->getSourceRange(); 9196 } 9197 9198