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