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