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