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