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