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