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