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