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