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