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->parameters().back(); 2965 else if (FunctionDecl *FD = getCurFunctionDecl()) 2966 LastArg = FD->parameters().back(); 2967 else 2968 LastArg = getCurMethodDecl()->parameters().back(); 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 3989 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 3990 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 3991 bool IsStringLocation, Range StringRange, 3992 ArrayRef<FixItHint> Fixit = None); 3993 3994 protected: 3995 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 3996 const char *startSpec, 3997 unsigned specifierLen, 3998 const char *csStart, unsigned csLen); 3999 4000 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 4001 const char *startSpec, 4002 unsigned specifierLen); 4003 4004 SourceRange getFormatStringRange(); 4005 CharSourceRange getSpecifierRange(const char *startSpecifier, 4006 unsigned specifierLen); 4007 SourceLocation getLocationOfByte(const char *x); 4008 4009 const Expr *getDataArg(unsigned i) const; 4010 4011 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 4012 const analyze_format_string::ConversionSpecifier &CS, 4013 const char *startSpecifier, unsigned specifierLen, 4014 unsigned argIndex); 4015 4016 template <typename Range> 4017 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4018 bool IsStringLocation, Range StringRange, 4019 ArrayRef<FixItHint> Fixit = None); 4020 }; 4021 } // end anonymous namespace 4022 4023 SourceRange CheckFormatHandler::getFormatStringRange() { 4024 return OrigFormatExpr->getSourceRange(); 4025 } 4026 4027 CharSourceRange CheckFormatHandler:: 4028 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 4029 SourceLocation Start = getLocationOfByte(startSpecifier); 4030 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 4031 4032 // Advance the end SourceLocation by one due to half-open ranges. 4033 End = End.getLocWithOffset(1); 4034 4035 return CharSourceRange::getCharRange(Start, End); 4036 } 4037 4038 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 4039 return S.getLocationOfStringLiteralByte(FExpr, x - Beg); 4040 } 4041 4042 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 4043 unsigned specifierLen){ 4044 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 4045 getLocationOfByte(startSpecifier), 4046 /*IsStringLocation*/true, 4047 getSpecifierRange(startSpecifier, specifierLen)); 4048 } 4049 4050 void CheckFormatHandler::HandleInvalidLengthModifier( 4051 const analyze_format_string::FormatSpecifier &FS, 4052 const analyze_format_string::ConversionSpecifier &CS, 4053 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 4054 using namespace analyze_format_string; 4055 4056 const LengthModifier &LM = FS.getLengthModifier(); 4057 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4058 4059 // See if we know how to fix this length modifier. 4060 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4061 if (FixedLM) { 4062 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4063 getLocationOfByte(LM.getStart()), 4064 /*IsStringLocation*/true, 4065 getSpecifierRange(startSpecifier, specifierLen)); 4066 4067 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4068 << FixedLM->toString() 4069 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4070 4071 } else { 4072 FixItHint Hint; 4073 if (DiagID == diag::warn_format_nonsensical_length) 4074 Hint = FixItHint::CreateRemoval(LMRange); 4075 4076 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 4077 getLocationOfByte(LM.getStart()), 4078 /*IsStringLocation*/true, 4079 getSpecifierRange(startSpecifier, specifierLen), 4080 Hint); 4081 } 4082 } 4083 4084 void CheckFormatHandler::HandleNonStandardLengthModifier( 4085 const analyze_format_string::FormatSpecifier &FS, 4086 const char *startSpecifier, unsigned specifierLen) { 4087 using namespace analyze_format_string; 4088 4089 const LengthModifier &LM = FS.getLengthModifier(); 4090 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 4091 4092 // See if we know how to fix this length modifier. 4093 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 4094 if (FixedLM) { 4095 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4096 << LM.toString() << 0, 4097 getLocationOfByte(LM.getStart()), 4098 /*IsStringLocation*/true, 4099 getSpecifierRange(startSpecifier, specifierLen)); 4100 4101 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 4102 << FixedLM->toString() 4103 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 4104 4105 } else { 4106 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4107 << LM.toString() << 0, 4108 getLocationOfByte(LM.getStart()), 4109 /*IsStringLocation*/true, 4110 getSpecifierRange(startSpecifier, specifierLen)); 4111 } 4112 } 4113 4114 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 4115 const analyze_format_string::ConversionSpecifier &CS, 4116 const char *startSpecifier, unsigned specifierLen) { 4117 using namespace analyze_format_string; 4118 4119 // See if we know how to fix this conversion specifier. 4120 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 4121 if (FixedCS) { 4122 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4123 << CS.toString() << /*conversion specifier*/1, 4124 getLocationOfByte(CS.getStart()), 4125 /*IsStringLocation*/true, 4126 getSpecifierRange(startSpecifier, specifierLen)); 4127 4128 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 4129 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 4130 << FixedCS->toString() 4131 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 4132 } else { 4133 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 4134 << CS.toString() << /*conversion specifier*/1, 4135 getLocationOfByte(CS.getStart()), 4136 /*IsStringLocation*/true, 4137 getSpecifierRange(startSpecifier, specifierLen)); 4138 } 4139 } 4140 4141 void CheckFormatHandler::HandlePosition(const char *startPos, 4142 unsigned posLen) { 4143 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 4144 getLocationOfByte(startPos), 4145 /*IsStringLocation*/true, 4146 getSpecifierRange(startPos, posLen)); 4147 } 4148 4149 void 4150 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 4151 analyze_format_string::PositionContext p) { 4152 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 4153 << (unsigned) p, 4154 getLocationOfByte(startPos), /*IsStringLocation*/true, 4155 getSpecifierRange(startPos, posLen)); 4156 } 4157 4158 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 4159 unsigned posLen) { 4160 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 4161 getLocationOfByte(startPos), 4162 /*IsStringLocation*/true, 4163 getSpecifierRange(startPos, posLen)); 4164 } 4165 4166 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 4167 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 4168 // The presence of a null character is likely an error. 4169 EmitFormatDiagnostic( 4170 S.PDiag(diag::warn_printf_format_string_contains_null_char), 4171 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 4172 getFormatStringRange()); 4173 } 4174 } 4175 4176 // Note that this may return NULL if there was an error parsing or building 4177 // one of the argument expressions. 4178 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 4179 return Args[FirstDataArg + i]; 4180 } 4181 4182 void CheckFormatHandler::DoneProcessing() { 4183 // Does the number of data arguments exceed the number of 4184 // format conversions in the format string? 4185 if (!HasVAListArg) { 4186 // Find any arguments that weren't covered. 4187 CoveredArgs.flip(); 4188 signed notCoveredArg = CoveredArgs.find_first(); 4189 if (notCoveredArg >= 0) { 4190 assert((unsigned)notCoveredArg < NumDataArgs); 4191 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 4192 } else { 4193 UncoveredArg.setAllCovered(); 4194 } 4195 } 4196 } 4197 4198 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 4199 const Expr *ArgExpr) { 4200 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 4201 "Invalid state"); 4202 4203 if (!ArgExpr) 4204 return; 4205 4206 SourceLocation Loc = ArgExpr->getLocStart(); 4207 4208 if (S.getSourceManager().isInSystemMacro(Loc)) 4209 return; 4210 4211 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 4212 for (auto E : DiagnosticExprs) 4213 PDiag << E->getSourceRange(); 4214 4215 CheckFormatHandler::EmitFormatDiagnostic( 4216 S, IsFunctionCall, DiagnosticExprs[0], 4217 PDiag, Loc, /*IsStringLocation*/false, 4218 DiagnosticExprs[0]->getSourceRange()); 4219 } 4220 4221 bool 4222 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 4223 SourceLocation Loc, 4224 const char *startSpec, 4225 unsigned specifierLen, 4226 const char *csStart, 4227 unsigned csLen) { 4228 bool keepGoing = true; 4229 if (argIndex < NumDataArgs) { 4230 // Consider the argument coverered, even though the specifier doesn't 4231 // make sense. 4232 CoveredArgs.set(argIndex); 4233 } 4234 else { 4235 // If argIndex exceeds the number of data arguments we 4236 // don't issue a warning because that is just a cascade of warnings (and 4237 // they may have intended '%%' anyway). We don't want to continue processing 4238 // the format string after this point, however, as we will like just get 4239 // gibberish when trying to match arguments. 4240 keepGoing = false; 4241 } 4242 4243 StringRef Specifier(csStart, csLen); 4244 4245 // If the specifier in non-printable, it could be the first byte of a UTF-8 4246 // sequence. In that case, print the UTF-8 code point. If not, print the byte 4247 // hex value. 4248 std::string CodePointStr; 4249 if (!llvm::sys::locale::isPrint(*csStart)) { 4250 UTF32 CodePoint; 4251 const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart); 4252 const UTF8 *E = 4253 reinterpret_cast<const UTF8 *>(csStart + csLen); 4254 ConversionResult Result = 4255 llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion); 4256 4257 if (Result != conversionOK) { 4258 unsigned char FirstChar = *csStart; 4259 CodePoint = (UTF32)FirstChar; 4260 } 4261 4262 llvm::raw_string_ostream OS(CodePointStr); 4263 if (CodePoint < 256) 4264 OS << "\\x" << llvm::format("%02x", CodePoint); 4265 else if (CodePoint <= 0xFFFF) 4266 OS << "\\u" << llvm::format("%04x", CodePoint); 4267 else 4268 OS << "\\U" << llvm::format("%08x", CodePoint); 4269 OS.flush(); 4270 Specifier = CodePointStr; 4271 } 4272 4273 EmitFormatDiagnostic( 4274 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 4275 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 4276 4277 return keepGoing; 4278 } 4279 4280 void 4281 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 4282 const char *startSpec, 4283 unsigned specifierLen) { 4284 EmitFormatDiagnostic( 4285 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 4286 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 4287 } 4288 4289 bool 4290 CheckFormatHandler::CheckNumArgs( 4291 const analyze_format_string::FormatSpecifier &FS, 4292 const analyze_format_string::ConversionSpecifier &CS, 4293 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 4294 4295 if (argIndex >= NumDataArgs) { 4296 PartialDiagnostic PDiag = FS.usesPositionalArg() 4297 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 4298 << (argIndex+1) << NumDataArgs) 4299 : S.PDiag(diag::warn_printf_insufficient_data_args); 4300 EmitFormatDiagnostic( 4301 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 4302 getSpecifierRange(startSpecifier, specifierLen)); 4303 4304 // Since more arguments than conversion tokens are given, by extension 4305 // all arguments are covered, so mark this as so. 4306 UncoveredArg.setAllCovered(); 4307 return false; 4308 } 4309 return true; 4310 } 4311 4312 template<typename Range> 4313 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 4314 SourceLocation Loc, 4315 bool IsStringLocation, 4316 Range StringRange, 4317 ArrayRef<FixItHint> FixIt) { 4318 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 4319 Loc, IsStringLocation, StringRange, FixIt); 4320 } 4321 4322 /// \brief If the format string is not within the funcion call, emit a note 4323 /// so that the function call and string are in diagnostic messages. 4324 /// 4325 /// \param InFunctionCall if true, the format string is within the function 4326 /// call and only one diagnostic message will be produced. Otherwise, an 4327 /// extra note will be emitted pointing to location of the format string. 4328 /// 4329 /// \param ArgumentExpr the expression that is passed as the format string 4330 /// argument in the function call. Used for getting locations when two 4331 /// diagnostics are emitted. 4332 /// 4333 /// \param PDiag the callee should already have provided any strings for the 4334 /// diagnostic message. This function only adds locations and fixits 4335 /// to diagnostics. 4336 /// 4337 /// \param Loc primary location for diagnostic. If two diagnostics are 4338 /// required, one will be at Loc and a new SourceLocation will be created for 4339 /// the other one. 4340 /// 4341 /// \param IsStringLocation if true, Loc points to the format string should be 4342 /// used for the note. Otherwise, Loc points to the argument list and will 4343 /// be used with PDiag. 4344 /// 4345 /// \param StringRange some or all of the string to highlight. This is 4346 /// templated so it can accept either a CharSourceRange or a SourceRange. 4347 /// 4348 /// \param FixIt optional fix it hint for the format string. 4349 template <typename Range> 4350 void CheckFormatHandler::EmitFormatDiagnostic( 4351 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 4352 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 4353 Range StringRange, ArrayRef<FixItHint> FixIt) { 4354 if (InFunctionCall) { 4355 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 4356 D << StringRange; 4357 D << FixIt; 4358 } else { 4359 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 4360 << ArgumentExpr->getSourceRange(); 4361 4362 const Sema::SemaDiagnosticBuilder &Note = 4363 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 4364 diag::note_format_string_defined); 4365 4366 Note << StringRange; 4367 Note << FixIt; 4368 } 4369 } 4370 4371 //===--- CHECK: Printf format string checking ------------------------------===// 4372 4373 namespace { 4374 class CheckPrintfHandler : public CheckFormatHandler { 4375 bool ObjCContext; 4376 4377 public: 4378 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr, 4379 const Expr *origFormatExpr, unsigned firstDataArg, 4380 unsigned numDataArgs, bool isObjC, 4381 const char *beg, bool hasVAListArg, 4382 ArrayRef<const Expr *> Args, 4383 unsigned formatIdx, bool inFunctionCall, 4384 Sema::VariadicCallType CallType, 4385 llvm::SmallBitVector &CheckedVarArgs, 4386 UncoveredArgHandler &UncoveredArg) 4387 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 4388 numDataArgs, beg, hasVAListArg, Args, 4389 formatIdx, inFunctionCall, CallType, CheckedVarArgs, 4390 UncoveredArg), 4391 ObjCContext(isObjC) 4392 {} 4393 4394 bool HandleInvalidPrintfConversionSpecifier( 4395 const analyze_printf::PrintfSpecifier &FS, 4396 const char *startSpecifier, 4397 unsigned specifierLen) override; 4398 4399 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 4400 const char *startSpecifier, 4401 unsigned specifierLen) override; 4402 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 4403 const char *StartSpecifier, 4404 unsigned SpecifierLen, 4405 const Expr *E); 4406 4407 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 4408 const char *startSpecifier, unsigned specifierLen); 4409 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 4410 const analyze_printf::OptionalAmount &Amt, 4411 unsigned type, 4412 const char *startSpecifier, unsigned specifierLen); 4413 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 4414 const analyze_printf::OptionalFlag &flag, 4415 const char *startSpecifier, unsigned specifierLen); 4416 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 4417 const analyze_printf::OptionalFlag &ignoredFlag, 4418 const analyze_printf::OptionalFlag &flag, 4419 const char *startSpecifier, unsigned specifierLen); 4420 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 4421 const Expr *E); 4422 4423 void HandleEmptyObjCModifierFlag(const char *startFlag, 4424 unsigned flagLen) override; 4425 4426 void HandleInvalidObjCModifierFlag(const char *startFlag, 4427 unsigned flagLen) override; 4428 4429 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 4430 const char *flagsEnd, 4431 const char *conversionPosition) 4432 override; 4433 }; 4434 } // end anonymous namespace 4435 4436 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 4437 const analyze_printf::PrintfSpecifier &FS, 4438 const char *startSpecifier, 4439 unsigned specifierLen) { 4440 const analyze_printf::PrintfConversionSpecifier &CS = 4441 FS.getConversionSpecifier(); 4442 4443 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 4444 getLocationOfByte(CS.getStart()), 4445 startSpecifier, specifierLen, 4446 CS.getStart(), CS.getLength()); 4447 } 4448 4449 bool CheckPrintfHandler::HandleAmount( 4450 const analyze_format_string::OptionalAmount &Amt, 4451 unsigned k, const char *startSpecifier, 4452 unsigned specifierLen) { 4453 if (Amt.hasDataArgument()) { 4454 if (!HasVAListArg) { 4455 unsigned argIndex = Amt.getArgIndex(); 4456 if (argIndex >= NumDataArgs) { 4457 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 4458 << k, 4459 getLocationOfByte(Amt.getStart()), 4460 /*IsStringLocation*/true, 4461 getSpecifierRange(startSpecifier, specifierLen)); 4462 // Don't do any more checking. We will just emit 4463 // spurious errors. 4464 return false; 4465 } 4466 4467 // Type check the data argument. It should be an 'int'. 4468 // Although not in conformance with C99, we also allow the argument to be 4469 // an 'unsigned int' as that is a reasonably safe case. GCC also 4470 // doesn't emit a warning for that case. 4471 CoveredArgs.set(argIndex); 4472 const Expr *Arg = getDataArg(argIndex); 4473 if (!Arg) 4474 return false; 4475 4476 QualType T = Arg->getType(); 4477 4478 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 4479 assert(AT.isValid()); 4480 4481 if (!AT.matchesType(S.Context, T)) { 4482 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 4483 << k << AT.getRepresentativeTypeName(S.Context) 4484 << T << Arg->getSourceRange(), 4485 getLocationOfByte(Amt.getStart()), 4486 /*IsStringLocation*/true, 4487 getSpecifierRange(startSpecifier, specifierLen)); 4488 // Don't do any more checking. We will just emit 4489 // spurious errors. 4490 return false; 4491 } 4492 } 4493 } 4494 return true; 4495 } 4496 4497 void CheckPrintfHandler::HandleInvalidAmount( 4498 const analyze_printf::PrintfSpecifier &FS, 4499 const analyze_printf::OptionalAmount &Amt, 4500 unsigned type, 4501 const char *startSpecifier, 4502 unsigned specifierLen) { 4503 const analyze_printf::PrintfConversionSpecifier &CS = 4504 FS.getConversionSpecifier(); 4505 4506 FixItHint fixit = 4507 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 4508 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 4509 Amt.getConstantLength())) 4510 : FixItHint(); 4511 4512 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 4513 << type << CS.toString(), 4514 getLocationOfByte(Amt.getStart()), 4515 /*IsStringLocation*/true, 4516 getSpecifierRange(startSpecifier, specifierLen), 4517 fixit); 4518 } 4519 4520 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 4521 const analyze_printf::OptionalFlag &flag, 4522 const char *startSpecifier, 4523 unsigned specifierLen) { 4524 // Warn about pointless flag with a fixit removal. 4525 const analyze_printf::PrintfConversionSpecifier &CS = 4526 FS.getConversionSpecifier(); 4527 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 4528 << flag.toString() << CS.toString(), 4529 getLocationOfByte(flag.getPosition()), 4530 /*IsStringLocation*/true, 4531 getSpecifierRange(startSpecifier, specifierLen), 4532 FixItHint::CreateRemoval( 4533 getSpecifierRange(flag.getPosition(), 1))); 4534 } 4535 4536 void CheckPrintfHandler::HandleIgnoredFlag( 4537 const analyze_printf::PrintfSpecifier &FS, 4538 const analyze_printf::OptionalFlag &ignoredFlag, 4539 const analyze_printf::OptionalFlag &flag, 4540 const char *startSpecifier, 4541 unsigned specifierLen) { 4542 // Warn about ignored flag with a fixit removal. 4543 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 4544 << ignoredFlag.toString() << flag.toString(), 4545 getLocationOfByte(ignoredFlag.getPosition()), 4546 /*IsStringLocation*/true, 4547 getSpecifierRange(startSpecifier, specifierLen), 4548 FixItHint::CreateRemoval( 4549 getSpecifierRange(ignoredFlag.getPosition(), 1))); 4550 } 4551 4552 // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 4553 // bool IsStringLocation, Range StringRange, 4554 // ArrayRef<FixItHint> Fixit = None); 4555 4556 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 4557 unsigned flagLen) { 4558 // Warn about an empty flag. 4559 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 4560 getLocationOfByte(startFlag), 4561 /*IsStringLocation*/true, 4562 getSpecifierRange(startFlag, flagLen)); 4563 } 4564 4565 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 4566 unsigned flagLen) { 4567 // Warn about an invalid flag. 4568 auto Range = getSpecifierRange(startFlag, flagLen); 4569 StringRef flag(startFlag, flagLen); 4570 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 4571 getLocationOfByte(startFlag), 4572 /*IsStringLocation*/true, 4573 Range, FixItHint::CreateRemoval(Range)); 4574 } 4575 4576 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 4577 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 4578 // Warn about using '[...]' without a '@' conversion. 4579 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 4580 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 4581 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 4582 getLocationOfByte(conversionPosition), 4583 /*IsStringLocation*/true, 4584 Range, FixItHint::CreateRemoval(Range)); 4585 } 4586 4587 // Determines if the specified is a C++ class or struct containing 4588 // a member with the specified name and kind (e.g. a CXXMethodDecl named 4589 // "c_str()"). 4590 template<typename MemberKind> 4591 static llvm::SmallPtrSet<MemberKind*, 1> 4592 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 4593 const RecordType *RT = Ty->getAs<RecordType>(); 4594 llvm::SmallPtrSet<MemberKind*, 1> Results; 4595 4596 if (!RT) 4597 return Results; 4598 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 4599 if (!RD || !RD->getDefinition()) 4600 return Results; 4601 4602 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 4603 Sema::LookupMemberName); 4604 R.suppressDiagnostics(); 4605 4606 // We just need to include all members of the right kind turned up by the 4607 // filter, at this point. 4608 if (S.LookupQualifiedName(R, RT->getDecl())) 4609 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 4610 NamedDecl *decl = (*I)->getUnderlyingDecl(); 4611 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 4612 Results.insert(FK); 4613 } 4614 return Results; 4615 } 4616 4617 /// Check if we could call '.c_str()' on an object. 4618 /// 4619 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 4620 /// allow the call, or if it would be ambiguous). 4621 bool Sema::hasCStrMethod(const Expr *E) { 4622 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 4623 MethodSet Results = 4624 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 4625 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 4626 MI != ME; ++MI) 4627 if ((*MI)->getMinRequiredArguments() == 0) 4628 return true; 4629 return false; 4630 } 4631 4632 // Check if a (w)string was passed when a (w)char* was needed, and offer a 4633 // better diagnostic if so. AT is assumed to be valid. 4634 // Returns true when a c_str() conversion method is found. 4635 bool CheckPrintfHandler::checkForCStrMembers( 4636 const analyze_printf::ArgType &AT, const Expr *E) { 4637 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet; 4638 4639 MethodSet Results = 4640 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 4641 4642 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 4643 MI != ME; ++MI) { 4644 const CXXMethodDecl *Method = *MI; 4645 if (Method->getMinRequiredArguments() == 0 && 4646 AT.matchesType(S.Context, Method->getReturnType())) { 4647 // FIXME: Suggest parens if the expression needs them. 4648 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 4649 S.Diag(E->getLocStart(), diag::note_printf_c_str) 4650 << "c_str()" 4651 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 4652 return true; 4653 } 4654 } 4655 4656 return false; 4657 } 4658 4659 bool 4660 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 4661 &FS, 4662 const char *startSpecifier, 4663 unsigned specifierLen) { 4664 using namespace analyze_format_string; 4665 using namespace analyze_printf; 4666 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 4667 4668 if (FS.consumesDataArgument()) { 4669 if (atFirstArg) { 4670 atFirstArg = false; 4671 usesPositionalArgs = FS.usesPositionalArg(); 4672 } 4673 else if (usesPositionalArgs != FS.usesPositionalArg()) { 4674 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 4675 startSpecifier, specifierLen); 4676 return false; 4677 } 4678 } 4679 4680 // First check if the field width, precision, and conversion specifier 4681 // have matching data arguments. 4682 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 4683 startSpecifier, specifierLen)) { 4684 return false; 4685 } 4686 4687 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 4688 startSpecifier, specifierLen)) { 4689 return false; 4690 } 4691 4692 if (!CS.consumesDataArgument()) { 4693 // FIXME: Technically specifying a precision or field width here 4694 // makes no sense. Worth issuing a warning at some point. 4695 return true; 4696 } 4697 4698 // Consume the argument. 4699 unsigned argIndex = FS.getArgIndex(); 4700 if (argIndex < NumDataArgs) { 4701 // The check to see if the argIndex is valid will come later. 4702 // We set the bit here because we may exit early from this 4703 // function if we encounter some other error. 4704 CoveredArgs.set(argIndex); 4705 } 4706 4707 // FreeBSD kernel extensions. 4708 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 4709 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 4710 // We need at least two arguments. 4711 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 4712 return false; 4713 4714 // Claim the second argument. 4715 CoveredArgs.set(argIndex + 1); 4716 4717 // Type check the first argument (int for %b, pointer for %D) 4718 const Expr *Ex = getDataArg(argIndex); 4719 const analyze_printf::ArgType &AT = 4720 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 4721 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 4722 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 4723 EmitFormatDiagnostic( 4724 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4725 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 4726 << false << Ex->getSourceRange(), 4727 Ex->getLocStart(), /*IsStringLocation*/false, 4728 getSpecifierRange(startSpecifier, specifierLen)); 4729 4730 // Type check the second argument (char * for both %b and %D) 4731 Ex = getDataArg(argIndex + 1); 4732 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 4733 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 4734 EmitFormatDiagnostic( 4735 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 4736 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 4737 << false << Ex->getSourceRange(), 4738 Ex->getLocStart(), /*IsStringLocation*/false, 4739 getSpecifierRange(startSpecifier, specifierLen)); 4740 4741 return true; 4742 } 4743 4744 // Check for using an Objective-C specific conversion specifier 4745 // in a non-ObjC literal. 4746 if (!ObjCContext && CS.isObjCArg()) { 4747 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 4748 specifierLen); 4749 } 4750 4751 // Check for invalid use of field width 4752 if (!FS.hasValidFieldWidth()) { 4753 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 4754 startSpecifier, specifierLen); 4755 } 4756 4757 // Check for invalid use of precision 4758 if (!FS.hasValidPrecision()) { 4759 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 4760 startSpecifier, specifierLen); 4761 } 4762 4763 // Check each flag does not conflict with any other component. 4764 if (!FS.hasValidThousandsGroupingPrefix()) 4765 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 4766 if (!FS.hasValidLeadingZeros()) 4767 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 4768 if (!FS.hasValidPlusPrefix()) 4769 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 4770 if (!FS.hasValidSpacePrefix()) 4771 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 4772 if (!FS.hasValidAlternativeForm()) 4773 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 4774 if (!FS.hasValidLeftJustified()) 4775 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 4776 4777 // Check that flags are not ignored by another flag 4778 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 4779 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 4780 startSpecifier, specifierLen); 4781 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 4782 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 4783 startSpecifier, specifierLen); 4784 4785 // Check the length modifier is valid with the given conversion specifier. 4786 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 4787 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 4788 diag::warn_format_nonsensical_length); 4789 else if (!FS.hasStandardLengthModifier()) 4790 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 4791 else if (!FS.hasStandardLengthConversionCombination()) 4792 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 4793 diag::warn_format_non_standard_conversion_spec); 4794 4795 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 4796 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 4797 4798 // The remaining checks depend on the data arguments. 4799 if (HasVAListArg) 4800 return true; 4801 4802 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 4803 return false; 4804 4805 const Expr *Arg = getDataArg(argIndex); 4806 if (!Arg) 4807 return true; 4808 4809 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 4810 } 4811 4812 static bool requiresParensToAddCast(const Expr *E) { 4813 // FIXME: We should have a general way to reason about operator 4814 // precedence and whether parens are actually needed here. 4815 // Take care of a few common cases where they aren't. 4816 const Expr *Inside = E->IgnoreImpCasts(); 4817 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 4818 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 4819 4820 switch (Inside->getStmtClass()) { 4821 case Stmt::ArraySubscriptExprClass: 4822 case Stmt::CallExprClass: 4823 case Stmt::CharacterLiteralClass: 4824 case Stmt::CXXBoolLiteralExprClass: 4825 case Stmt::DeclRefExprClass: 4826 case Stmt::FloatingLiteralClass: 4827 case Stmt::IntegerLiteralClass: 4828 case Stmt::MemberExprClass: 4829 case Stmt::ObjCArrayLiteralClass: 4830 case Stmt::ObjCBoolLiteralExprClass: 4831 case Stmt::ObjCBoxedExprClass: 4832 case Stmt::ObjCDictionaryLiteralClass: 4833 case Stmt::ObjCEncodeExprClass: 4834 case Stmt::ObjCIvarRefExprClass: 4835 case Stmt::ObjCMessageExprClass: 4836 case Stmt::ObjCPropertyRefExprClass: 4837 case Stmt::ObjCStringLiteralClass: 4838 case Stmt::ObjCSubscriptRefExprClass: 4839 case Stmt::ParenExprClass: 4840 case Stmt::StringLiteralClass: 4841 case Stmt::UnaryOperatorClass: 4842 return false; 4843 default: 4844 return true; 4845 } 4846 } 4847 4848 static std::pair<QualType, StringRef> 4849 shouldNotPrintDirectly(const ASTContext &Context, 4850 QualType IntendedTy, 4851 const Expr *E) { 4852 // Use a 'while' to peel off layers of typedefs. 4853 QualType TyTy = IntendedTy; 4854 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 4855 StringRef Name = UserTy->getDecl()->getName(); 4856 QualType CastTy = llvm::StringSwitch<QualType>(Name) 4857 .Case("NSInteger", Context.LongTy) 4858 .Case("NSUInteger", Context.UnsignedLongTy) 4859 .Case("SInt32", Context.IntTy) 4860 .Case("UInt32", Context.UnsignedIntTy) 4861 .Default(QualType()); 4862 4863 if (!CastTy.isNull()) 4864 return std::make_pair(CastTy, Name); 4865 4866 TyTy = UserTy->desugar(); 4867 } 4868 4869 // Strip parens if necessary. 4870 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 4871 return shouldNotPrintDirectly(Context, 4872 PE->getSubExpr()->getType(), 4873 PE->getSubExpr()); 4874 4875 // If this is a conditional expression, then its result type is constructed 4876 // via usual arithmetic conversions and thus there might be no necessary 4877 // typedef sugar there. Recurse to operands to check for NSInteger & 4878 // Co. usage condition. 4879 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 4880 QualType TrueTy, FalseTy; 4881 StringRef TrueName, FalseName; 4882 4883 std::tie(TrueTy, TrueName) = 4884 shouldNotPrintDirectly(Context, 4885 CO->getTrueExpr()->getType(), 4886 CO->getTrueExpr()); 4887 std::tie(FalseTy, FalseName) = 4888 shouldNotPrintDirectly(Context, 4889 CO->getFalseExpr()->getType(), 4890 CO->getFalseExpr()); 4891 4892 if (TrueTy == FalseTy) 4893 return std::make_pair(TrueTy, TrueName); 4894 else if (TrueTy.isNull()) 4895 return std::make_pair(FalseTy, FalseName); 4896 else if (FalseTy.isNull()) 4897 return std::make_pair(TrueTy, TrueName); 4898 } 4899 4900 return std::make_pair(QualType(), StringRef()); 4901 } 4902 4903 bool 4904 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 4905 const char *StartSpecifier, 4906 unsigned SpecifierLen, 4907 const Expr *E) { 4908 using namespace analyze_format_string; 4909 using namespace analyze_printf; 4910 // Now type check the data expression that matches the 4911 // format specifier. 4912 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, 4913 ObjCContext); 4914 if (!AT.isValid()) 4915 return true; 4916 4917 QualType ExprTy = E->getType(); 4918 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 4919 ExprTy = TET->getUnderlyingExpr()->getType(); 4920 } 4921 4922 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 4923 4924 if (match == analyze_printf::ArgType::Match) { 4925 return true; 4926 } 4927 4928 // Look through argument promotions for our error message's reported type. 4929 // This includes the integral and floating promotions, but excludes array 4930 // and function pointer decay; seeing that an argument intended to be a 4931 // string has type 'char [6]' is probably more confusing than 'char *'. 4932 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 4933 if (ICE->getCastKind() == CK_IntegralCast || 4934 ICE->getCastKind() == CK_FloatingCast) { 4935 E = ICE->getSubExpr(); 4936 ExprTy = E->getType(); 4937 4938 // Check if we didn't match because of an implicit cast from a 'char' 4939 // or 'short' to an 'int'. This is done because printf is a varargs 4940 // function. 4941 if (ICE->getType() == S.Context.IntTy || 4942 ICE->getType() == S.Context.UnsignedIntTy) { 4943 // All further checking is done on the subexpression. 4944 if (AT.matchesType(S.Context, ExprTy)) 4945 return true; 4946 } 4947 } 4948 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 4949 // Special case for 'a', which has type 'int' in C. 4950 // Note, however, that we do /not/ want to treat multibyte constants like 4951 // 'MooV' as characters! This form is deprecated but still exists. 4952 if (ExprTy == S.Context.IntTy) 4953 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 4954 ExprTy = S.Context.CharTy; 4955 } 4956 4957 // Look through enums to their underlying type. 4958 bool IsEnum = false; 4959 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 4960 ExprTy = EnumTy->getDecl()->getIntegerType(); 4961 IsEnum = true; 4962 } 4963 4964 // %C in an Objective-C context prints a unichar, not a wchar_t. 4965 // If the argument is an integer of some kind, believe the %C and suggest 4966 // a cast instead of changing the conversion specifier. 4967 QualType IntendedTy = ExprTy; 4968 if (ObjCContext && 4969 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 4970 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 4971 !ExprTy->isCharType()) { 4972 // 'unichar' is defined as a typedef of unsigned short, but we should 4973 // prefer using the typedef if it is visible. 4974 IntendedTy = S.Context.UnsignedShortTy; 4975 4976 // While we are here, check if the value is an IntegerLiteral that happens 4977 // to be within the valid range. 4978 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 4979 const llvm::APInt &V = IL->getValue(); 4980 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 4981 return true; 4982 } 4983 4984 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 4985 Sema::LookupOrdinaryName); 4986 if (S.LookupName(Result, S.getCurScope())) { 4987 NamedDecl *ND = Result.getFoundDecl(); 4988 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 4989 if (TD->getUnderlyingType() == IntendedTy) 4990 IntendedTy = S.Context.getTypedefType(TD); 4991 } 4992 } 4993 } 4994 4995 // Special-case some of Darwin's platform-independence types by suggesting 4996 // casts to primitive types that are known to be large enough. 4997 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 4998 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 4999 QualType CastTy; 5000 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 5001 if (!CastTy.isNull()) { 5002 IntendedTy = CastTy; 5003 ShouldNotPrintDirectly = true; 5004 } 5005 } 5006 5007 // We may be able to offer a FixItHint if it is a supported type. 5008 PrintfSpecifier fixedFS = FS; 5009 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(), 5010 S.Context, ObjCContext); 5011 5012 if (success) { 5013 // Get the fix string from the fixed format specifier 5014 SmallString<16> buf; 5015 llvm::raw_svector_ostream os(buf); 5016 fixedFS.toString(os); 5017 5018 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 5019 5020 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 5021 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5022 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5023 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5024 } 5025 // In this case, the specifier is wrong and should be changed to match 5026 // the argument. 5027 EmitFormatDiagnostic(S.PDiag(diag) 5028 << AT.getRepresentativeTypeName(S.Context) 5029 << IntendedTy << IsEnum << E->getSourceRange(), 5030 E->getLocStart(), 5031 /*IsStringLocation*/ false, SpecRange, 5032 FixItHint::CreateReplacement(SpecRange, os.str())); 5033 } else { 5034 // The canonical type for formatting this value is different from the 5035 // actual type of the expression. (This occurs, for example, with Darwin's 5036 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 5037 // should be printed as 'long' for 64-bit compatibility.) 5038 // Rather than emitting a normal format/argument mismatch, we want to 5039 // add a cast to the recommended type (and correct the format string 5040 // if necessary). 5041 SmallString<16> CastBuf; 5042 llvm::raw_svector_ostream CastFix(CastBuf); 5043 CastFix << "("; 5044 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 5045 CastFix << ")"; 5046 5047 SmallVector<FixItHint,4> Hints; 5048 if (!AT.matchesType(S.Context, IntendedTy)) 5049 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 5050 5051 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 5052 // If there's already a cast present, just replace it. 5053 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 5054 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 5055 5056 } else if (!requiresParensToAddCast(E)) { 5057 // If the expression has high enough precedence, 5058 // just write the C-style cast. 5059 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5060 CastFix.str())); 5061 } else { 5062 // Otherwise, add parens around the expression as well as the cast. 5063 CastFix << "("; 5064 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 5065 CastFix.str())); 5066 5067 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 5068 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 5069 } 5070 5071 if (ShouldNotPrintDirectly) { 5072 // The expression has a type that should not be printed directly. 5073 // We extract the name from the typedef because we don't want to show 5074 // the underlying type in the diagnostic. 5075 StringRef Name; 5076 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 5077 Name = TypedefTy->getDecl()->getName(); 5078 else 5079 Name = CastTyName; 5080 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 5081 << Name << IntendedTy << IsEnum 5082 << E->getSourceRange(), 5083 E->getLocStart(), /*IsStringLocation=*/false, 5084 SpecRange, Hints); 5085 } else { 5086 // In this case, the expression could be printed using a different 5087 // specifier, but we've decided that the specifier is probably correct 5088 // and we should cast instead. Just use the normal warning message. 5089 EmitFormatDiagnostic( 5090 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 5091 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 5092 << E->getSourceRange(), 5093 E->getLocStart(), /*IsStringLocation*/false, 5094 SpecRange, Hints); 5095 } 5096 } 5097 } else { 5098 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 5099 SpecifierLen); 5100 // Since the warning for passing non-POD types to variadic functions 5101 // was deferred until now, we emit a warning for non-POD 5102 // arguments here. 5103 switch (S.isValidVarArgType(ExprTy)) { 5104 case Sema::VAK_Valid: 5105 case Sema::VAK_ValidInCXX11: { 5106 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5107 if (match == analyze_printf::ArgType::NoMatchPedantic) { 5108 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5109 } 5110 5111 EmitFormatDiagnostic( 5112 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 5113 << IsEnum << CSR << E->getSourceRange(), 5114 E->getLocStart(), /*IsStringLocation*/ false, CSR); 5115 break; 5116 } 5117 case Sema::VAK_Undefined: 5118 case Sema::VAK_MSVCUndefined: 5119 EmitFormatDiagnostic( 5120 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 5121 << S.getLangOpts().CPlusPlus11 5122 << ExprTy 5123 << CallType 5124 << AT.getRepresentativeTypeName(S.Context) 5125 << CSR 5126 << E->getSourceRange(), 5127 E->getLocStart(), /*IsStringLocation*/false, CSR); 5128 checkForCStrMembers(AT, E); 5129 break; 5130 5131 case Sema::VAK_Invalid: 5132 if (ExprTy->isObjCObjectType()) 5133 EmitFormatDiagnostic( 5134 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 5135 << S.getLangOpts().CPlusPlus11 5136 << ExprTy 5137 << CallType 5138 << AT.getRepresentativeTypeName(S.Context) 5139 << CSR 5140 << E->getSourceRange(), 5141 E->getLocStart(), /*IsStringLocation*/false, CSR); 5142 else 5143 // FIXME: If this is an initializer list, suggest removing the braces 5144 // or inserting a cast to the target type. 5145 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 5146 << isa<InitListExpr>(E) << ExprTy << CallType 5147 << AT.getRepresentativeTypeName(S.Context) 5148 << E->getSourceRange(); 5149 break; 5150 } 5151 5152 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 5153 "format string specifier index out of range"); 5154 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 5155 } 5156 5157 return true; 5158 } 5159 5160 //===--- CHECK: Scanf format string checking ------------------------------===// 5161 5162 namespace { 5163 class CheckScanfHandler : public CheckFormatHandler { 5164 public: 5165 CheckScanfHandler(Sema &s, const StringLiteral *fexpr, 5166 const Expr *origFormatExpr, unsigned firstDataArg, 5167 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5168 ArrayRef<const Expr *> Args, 5169 unsigned formatIdx, bool inFunctionCall, 5170 Sema::VariadicCallType CallType, 5171 llvm::SmallBitVector &CheckedVarArgs, 5172 UncoveredArgHandler &UncoveredArg) 5173 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg, 5174 numDataArgs, beg, hasVAListArg, 5175 Args, formatIdx, inFunctionCall, CallType, 5176 CheckedVarArgs, UncoveredArg) 5177 {} 5178 5179 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 5180 const char *startSpecifier, 5181 unsigned specifierLen) override; 5182 5183 bool HandleInvalidScanfConversionSpecifier( 5184 const analyze_scanf::ScanfSpecifier &FS, 5185 const char *startSpecifier, 5186 unsigned specifierLen) override; 5187 5188 void HandleIncompleteScanList(const char *start, const char *end) override; 5189 }; 5190 } // end anonymous namespace 5191 5192 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 5193 const char *end) { 5194 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 5195 getLocationOfByte(end), /*IsStringLocation*/true, 5196 getSpecifierRange(start, end - start)); 5197 } 5198 5199 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 5200 const analyze_scanf::ScanfSpecifier &FS, 5201 const char *startSpecifier, 5202 unsigned specifierLen) { 5203 5204 const analyze_scanf::ScanfConversionSpecifier &CS = 5205 FS.getConversionSpecifier(); 5206 5207 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 5208 getLocationOfByte(CS.getStart()), 5209 startSpecifier, specifierLen, 5210 CS.getStart(), CS.getLength()); 5211 } 5212 5213 bool CheckScanfHandler::HandleScanfSpecifier( 5214 const analyze_scanf::ScanfSpecifier &FS, 5215 const char *startSpecifier, 5216 unsigned specifierLen) { 5217 using namespace analyze_scanf; 5218 using namespace analyze_format_string; 5219 5220 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 5221 5222 // Handle case where '%' and '*' don't consume an argument. These shouldn't 5223 // be used to decide if we are using positional arguments consistently. 5224 if (FS.consumesDataArgument()) { 5225 if (atFirstArg) { 5226 atFirstArg = false; 5227 usesPositionalArgs = FS.usesPositionalArg(); 5228 } 5229 else if (usesPositionalArgs != FS.usesPositionalArg()) { 5230 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 5231 startSpecifier, specifierLen); 5232 return false; 5233 } 5234 } 5235 5236 // Check if the field with is non-zero. 5237 const OptionalAmount &Amt = FS.getFieldWidth(); 5238 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 5239 if (Amt.getConstantAmount() == 0) { 5240 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 5241 Amt.getConstantLength()); 5242 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 5243 getLocationOfByte(Amt.getStart()), 5244 /*IsStringLocation*/true, R, 5245 FixItHint::CreateRemoval(R)); 5246 } 5247 } 5248 5249 if (!FS.consumesDataArgument()) { 5250 // FIXME: Technically specifying a precision or field width here 5251 // makes no sense. Worth issuing a warning at some point. 5252 return true; 5253 } 5254 5255 // Consume the argument. 5256 unsigned argIndex = FS.getArgIndex(); 5257 if (argIndex < NumDataArgs) { 5258 // The check to see if the argIndex is valid will come later. 5259 // We set the bit here because we may exit early from this 5260 // function if we encounter some other error. 5261 CoveredArgs.set(argIndex); 5262 } 5263 5264 // Check the length modifier is valid with the given conversion specifier. 5265 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 5266 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5267 diag::warn_format_nonsensical_length); 5268 else if (!FS.hasStandardLengthModifier()) 5269 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 5270 else if (!FS.hasStandardLengthConversionCombination()) 5271 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 5272 diag::warn_format_non_standard_conversion_spec); 5273 5274 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 5275 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 5276 5277 // The remaining checks depend on the data arguments. 5278 if (HasVAListArg) 5279 return true; 5280 5281 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 5282 return false; 5283 5284 // Check that the argument type matches the format specifier. 5285 const Expr *Ex = getDataArg(argIndex); 5286 if (!Ex) 5287 return true; 5288 5289 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 5290 5291 if (!AT.isValid()) { 5292 return true; 5293 } 5294 5295 analyze_format_string::ArgType::MatchKind match = 5296 AT.matchesType(S.Context, Ex->getType()); 5297 if (match == analyze_format_string::ArgType::Match) { 5298 return true; 5299 } 5300 5301 ScanfSpecifier fixedFS = FS; 5302 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 5303 S.getLangOpts(), S.Context); 5304 5305 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 5306 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 5307 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 5308 } 5309 5310 if (success) { 5311 // Get the fix string from the fixed format specifier. 5312 SmallString<128> buf; 5313 llvm::raw_svector_ostream os(buf); 5314 fixedFS.toString(os); 5315 5316 EmitFormatDiagnostic( 5317 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 5318 << Ex->getType() << false << Ex->getSourceRange(), 5319 Ex->getLocStart(), 5320 /*IsStringLocation*/ false, 5321 getSpecifierRange(startSpecifier, specifierLen), 5322 FixItHint::CreateReplacement( 5323 getSpecifierRange(startSpecifier, specifierLen), os.str())); 5324 } else { 5325 EmitFormatDiagnostic(S.PDiag(diag) 5326 << AT.getRepresentativeTypeName(S.Context) 5327 << Ex->getType() << false << Ex->getSourceRange(), 5328 Ex->getLocStart(), 5329 /*IsStringLocation*/ false, 5330 getSpecifierRange(startSpecifier, specifierLen)); 5331 } 5332 5333 return true; 5334 } 5335 5336 static void CheckFormatString(Sema &S, const StringLiteral *FExpr, 5337 const Expr *OrigFormatExpr, 5338 ArrayRef<const Expr *> Args, 5339 bool HasVAListArg, unsigned format_idx, 5340 unsigned firstDataArg, 5341 Sema::FormatStringType Type, 5342 bool inFunctionCall, 5343 Sema::VariadicCallType CallType, 5344 llvm::SmallBitVector &CheckedVarArgs, 5345 UncoveredArgHandler &UncoveredArg) { 5346 // CHECK: is the format string a wide literal? 5347 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 5348 CheckFormatHandler::EmitFormatDiagnostic( 5349 S, inFunctionCall, Args[format_idx], 5350 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 5351 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 5352 return; 5353 } 5354 5355 // Str - The format string. NOTE: this is NOT null-terminated! 5356 StringRef StrRef = FExpr->getString(); 5357 const char *Str = StrRef.data(); 5358 // Account for cases where the string literal is truncated in a declaration. 5359 const ConstantArrayType *T = 5360 S.Context.getAsConstantArrayType(FExpr->getType()); 5361 assert(T && "String literal not of constant array type!"); 5362 size_t TypeSize = T->getSize().getZExtValue(); 5363 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 5364 const unsigned numDataArgs = Args.size() - firstDataArg; 5365 5366 // Emit a warning if the string literal is truncated and does not contain an 5367 // embedded null character. 5368 if (TypeSize <= StrRef.size() && 5369 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 5370 CheckFormatHandler::EmitFormatDiagnostic( 5371 S, inFunctionCall, Args[format_idx], 5372 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 5373 FExpr->getLocStart(), 5374 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 5375 return; 5376 } 5377 5378 // CHECK: empty format string? 5379 if (StrLen == 0 && numDataArgs > 0) { 5380 CheckFormatHandler::EmitFormatDiagnostic( 5381 S, inFunctionCall, Args[format_idx], 5382 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 5383 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 5384 return; 5385 } 5386 5387 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 5388 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) { 5389 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, 5390 numDataArgs, (Type == Sema::FST_NSString || 5391 Type == Sema::FST_OSTrace), 5392 Str, HasVAListArg, Args, format_idx, 5393 inFunctionCall, CallType, CheckedVarArgs, 5394 UncoveredArg); 5395 5396 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 5397 S.getLangOpts(), 5398 S.Context.getTargetInfo(), 5399 Type == Sema::FST_FreeBSDKPrintf)) 5400 H.DoneProcessing(); 5401 } else if (Type == Sema::FST_Scanf) { 5402 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs, 5403 Str, HasVAListArg, Args, format_idx, 5404 inFunctionCall, CallType, CheckedVarArgs, 5405 UncoveredArg); 5406 5407 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 5408 S.getLangOpts(), 5409 S.Context.getTargetInfo())) 5410 H.DoneProcessing(); 5411 } // TODO: handle other formats 5412 } 5413 5414 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 5415 // Str - The format string. NOTE: this is NOT null-terminated! 5416 StringRef StrRef = FExpr->getString(); 5417 const char *Str = StrRef.data(); 5418 // Account for cases where the string literal is truncated in a declaration. 5419 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 5420 assert(T && "String literal not of constant array type!"); 5421 size_t TypeSize = T->getSize().getZExtValue(); 5422 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 5423 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 5424 getLangOpts(), 5425 Context.getTargetInfo()); 5426 } 5427 5428 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 5429 5430 // Returns the related absolute value function that is larger, of 0 if one 5431 // does not exist. 5432 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 5433 switch (AbsFunction) { 5434 default: 5435 return 0; 5436 5437 case Builtin::BI__builtin_abs: 5438 return Builtin::BI__builtin_labs; 5439 case Builtin::BI__builtin_labs: 5440 return Builtin::BI__builtin_llabs; 5441 case Builtin::BI__builtin_llabs: 5442 return 0; 5443 5444 case Builtin::BI__builtin_fabsf: 5445 return Builtin::BI__builtin_fabs; 5446 case Builtin::BI__builtin_fabs: 5447 return Builtin::BI__builtin_fabsl; 5448 case Builtin::BI__builtin_fabsl: 5449 return 0; 5450 5451 case Builtin::BI__builtin_cabsf: 5452 return Builtin::BI__builtin_cabs; 5453 case Builtin::BI__builtin_cabs: 5454 return Builtin::BI__builtin_cabsl; 5455 case Builtin::BI__builtin_cabsl: 5456 return 0; 5457 5458 case Builtin::BIabs: 5459 return Builtin::BIlabs; 5460 case Builtin::BIlabs: 5461 return Builtin::BIllabs; 5462 case Builtin::BIllabs: 5463 return 0; 5464 5465 case Builtin::BIfabsf: 5466 return Builtin::BIfabs; 5467 case Builtin::BIfabs: 5468 return Builtin::BIfabsl; 5469 case Builtin::BIfabsl: 5470 return 0; 5471 5472 case Builtin::BIcabsf: 5473 return Builtin::BIcabs; 5474 case Builtin::BIcabs: 5475 return Builtin::BIcabsl; 5476 case Builtin::BIcabsl: 5477 return 0; 5478 } 5479 } 5480 5481 // Returns the argument type of the absolute value function. 5482 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 5483 unsigned AbsType) { 5484 if (AbsType == 0) 5485 return QualType(); 5486 5487 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 5488 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 5489 if (Error != ASTContext::GE_None) 5490 return QualType(); 5491 5492 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 5493 if (!FT) 5494 return QualType(); 5495 5496 if (FT->getNumParams() != 1) 5497 return QualType(); 5498 5499 return FT->getParamType(0); 5500 } 5501 5502 // Returns the best absolute value function, or zero, based on type and 5503 // current absolute value function. 5504 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 5505 unsigned AbsFunctionKind) { 5506 unsigned BestKind = 0; 5507 uint64_t ArgSize = Context.getTypeSize(ArgType); 5508 for (unsigned Kind = AbsFunctionKind; Kind != 0; 5509 Kind = getLargerAbsoluteValueFunction(Kind)) { 5510 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 5511 if (Context.getTypeSize(ParamType) >= ArgSize) { 5512 if (BestKind == 0) 5513 BestKind = Kind; 5514 else if (Context.hasSameType(ParamType, ArgType)) { 5515 BestKind = Kind; 5516 break; 5517 } 5518 } 5519 } 5520 return BestKind; 5521 } 5522 5523 enum AbsoluteValueKind { 5524 AVK_Integer, 5525 AVK_Floating, 5526 AVK_Complex 5527 }; 5528 5529 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 5530 if (T->isIntegralOrEnumerationType()) 5531 return AVK_Integer; 5532 if (T->isRealFloatingType()) 5533 return AVK_Floating; 5534 if (T->isAnyComplexType()) 5535 return AVK_Complex; 5536 5537 llvm_unreachable("Type not integer, floating, or complex"); 5538 } 5539 5540 // Changes the absolute value function to a different type. Preserves whether 5541 // the function is a builtin. 5542 static unsigned changeAbsFunction(unsigned AbsKind, 5543 AbsoluteValueKind ValueKind) { 5544 switch (ValueKind) { 5545 case AVK_Integer: 5546 switch (AbsKind) { 5547 default: 5548 return 0; 5549 case Builtin::BI__builtin_fabsf: 5550 case Builtin::BI__builtin_fabs: 5551 case Builtin::BI__builtin_fabsl: 5552 case Builtin::BI__builtin_cabsf: 5553 case Builtin::BI__builtin_cabs: 5554 case Builtin::BI__builtin_cabsl: 5555 return Builtin::BI__builtin_abs; 5556 case Builtin::BIfabsf: 5557 case Builtin::BIfabs: 5558 case Builtin::BIfabsl: 5559 case Builtin::BIcabsf: 5560 case Builtin::BIcabs: 5561 case Builtin::BIcabsl: 5562 return Builtin::BIabs; 5563 } 5564 case AVK_Floating: 5565 switch (AbsKind) { 5566 default: 5567 return 0; 5568 case Builtin::BI__builtin_abs: 5569 case Builtin::BI__builtin_labs: 5570 case Builtin::BI__builtin_llabs: 5571 case Builtin::BI__builtin_cabsf: 5572 case Builtin::BI__builtin_cabs: 5573 case Builtin::BI__builtin_cabsl: 5574 return Builtin::BI__builtin_fabsf; 5575 case Builtin::BIabs: 5576 case Builtin::BIlabs: 5577 case Builtin::BIllabs: 5578 case Builtin::BIcabsf: 5579 case Builtin::BIcabs: 5580 case Builtin::BIcabsl: 5581 return Builtin::BIfabsf; 5582 } 5583 case AVK_Complex: 5584 switch (AbsKind) { 5585 default: 5586 return 0; 5587 case Builtin::BI__builtin_abs: 5588 case Builtin::BI__builtin_labs: 5589 case Builtin::BI__builtin_llabs: 5590 case Builtin::BI__builtin_fabsf: 5591 case Builtin::BI__builtin_fabs: 5592 case Builtin::BI__builtin_fabsl: 5593 return Builtin::BI__builtin_cabsf; 5594 case Builtin::BIabs: 5595 case Builtin::BIlabs: 5596 case Builtin::BIllabs: 5597 case Builtin::BIfabsf: 5598 case Builtin::BIfabs: 5599 case Builtin::BIfabsl: 5600 return Builtin::BIcabsf; 5601 } 5602 } 5603 llvm_unreachable("Unable to convert function"); 5604 } 5605 5606 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 5607 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5608 if (!FnInfo) 5609 return 0; 5610 5611 switch (FDecl->getBuiltinID()) { 5612 default: 5613 return 0; 5614 case Builtin::BI__builtin_abs: 5615 case Builtin::BI__builtin_fabs: 5616 case Builtin::BI__builtin_fabsf: 5617 case Builtin::BI__builtin_fabsl: 5618 case Builtin::BI__builtin_labs: 5619 case Builtin::BI__builtin_llabs: 5620 case Builtin::BI__builtin_cabs: 5621 case Builtin::BI__builtin_cabsf: 5622 case Builtin::BI__builtin_cabsl: 5623 case Builtin::BIabs: 5624 case Builtin::BIlabs: 5625 case Builtin::BIllabs: 5626 case Builtin::BIfabs: 5627 case Builtin::BIfabsf: 5628 case Builtin::BIfabsl: 5629 case Builtin::BIcabs: 5630 case Builtin::BIcabsf: 5631 case Builtin::BIcabsl: 5632 return FDecl->getBuiltinID(); 5633 } 5634 llvm_unreachable("Unknown Builtin type"); 5635 } 5636 5637 // If the replacement is valid, emit a note with replacement function. 5638 // Additionally, suggest including the proper header if not already included. 5639 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 5640 unsigned AbsKind, QualType ArgType) { 5641 bool EmitHeaderHint = true; 5642 const char *HeaderName = nullptr; 5643 const char *FunctionName = nullptr; 5644 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 5645 FunctionName = "std::abs"; 5646 if (ArgType->isIntegralOrEnumerationType()) { 5647 HeaderName = "cstdlib"; 5648 } else if (ArgType->isRealFloatingType()) { 5649 HeaderName = "cmath"; 5650 } else { 5651 llvm_unreachable("Invalid Type"); 5652 } 5653 5654 // Lookup all std::abs 5655 if (NamespaceDecl *Std = S.getStdNamespace()) { 5656 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 5657 R.suppressDiagnostics(); 5658 S.LookupQualifiedName(R, Std); 5659 5660 for (const auto *I : R) { 5661 const FunctionDecl *FDecl = nullptr; 5662 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 5663 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 5664 } else { 5665 FDecl = dyn_cast<FunctionDecl>(I); 5666 } 5667 if (!FDecl) 5668 continue; 5669 5670 // Found std::abs(), check that they are the right ones. 5671 if (FDecl->getNumParams() != 1) 5672 continue; 5673 5674 // Check that the parameter type can handle the argument. 5675 QualType ParamType = FDecl->getParamDecl(0)->getType(); 5676 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 5677 S.Context.getTypeSize(ArgType) <= 5678 S.Context.getTypeSize(ParamType)) { 5679 // Found a function, don't need the header hint. 5680 EmitHeaderHint = false; 5681 break; 5682 } 5683 } 5684 } 5685 } else { 5686 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 5687 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 5688 5689 if (HeaderName) { 5690 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 5691 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 5692 R.suppressDiagnostics(); 5693 S.LookupName(R, S.getCurScope()); 5694 5695 if (R.isSingleResult()) { 5696 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 5697 if (FD && FD->getBuiltinID() == AbsKind) { 5698 EmitHeaderHint = false; 5699 } else { 5700 return; 5701 } 5702 } else if (!R.empty()) { 5703 return; 5704 } 5705 } 5706 } 5707 5708 S.Diag(Loc, diag::note_replace_abs_function) 5709 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 5710 5711 if (!HeaderName) 5712 return; 5713 5714 if (!EmitHeaderHint) 5715 return; 5716 5717 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 5718 << FunctionName; 5719 } 5720 5721 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) { 5722 if (!FDecl) 5723 return false; 5724 5725 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs")) 5726 return false; 5727 5728 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext()); 5729 5730 while (ND && ND->isInlineNamespace()) { 5731 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext()); 5732 } 5733 5734 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std")) 5735 return false; 5736 5737 if (!isa<TranslationUnitDecl>(ND->getDeclContext())) 5738 return false; 5739 5740 return true; 5741 } 5742 5743 // Warn when using the wrong abs() function. 5744 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 5745 const FunctionDecl *FDecl, 5746 IdentifierInfo *FnInfo) { 5747 if (Call->getNumArgs() != 1) 5748 return; 5749 5750 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 5751 bool IsStdAbs = IsFunctionStdAbs(FDecl); 5752 if (AbsKind == 0 && !IsStdAbs) 5753 return; 5754 5755 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 5756 QualType ParamType = Call->getArg(0)->getType(); 5757 5758 // Unsigned types cannot be negative. Suggest removing the absolute value 5759 // function call. 5760 if (ArgType->isUnsignedIntegerType()) { 5761 const char *FunctionName = 5762 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 5763 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 5764 Diag(Call->getExprLoc(), diag::note_remove_abs) 5765 << FunctionName 5766 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 5767 return; 5768 } 5769 5770 // Taking the absolute value of a pointer is very suspicious, they probably 5771 // wanted to index into an array, dereference a pointer, call a function, etc. 5772 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 5773 unsigned DiagType = 0; 5774 if (ArgType->isFunctionType()) 5775 DiagType = 1; 5776 else if (ArgType->isArrayType()) 5777 DiagType = 2; 5778 5779 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 5780 return; 5781 } 5782 5783 // std::abs has overloads which prevent most of the absolute value problems 5784 // from occurring. 5785 if (IsStdAbs) 5786 return; 5787 5788 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 5789 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 5790 5791 // The argument and parameter are the same kind. Check if they are the right 5792 // size. 5793 if (ArgValueKind == ParamValueKind) { 5794 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 5795 return; 5796 5797 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 5798 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 5799 << FDecl << ArgType << ParamType; 5800 5801 if (NewAbsKind == 0) 5802 return; 5803 5804 emitReplacement(*this, Call->getExprLoc(), 5805 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 5806 return; 5807 } 5808 5809 // ArgValueKind != ParamValueKind 5810 // The wrong type of absolute value function was used. Attempt to find the 5811 // proper one. 5812 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 5813 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 5814 if (NewAbsKind == 0) 5815 return; 5816 5817 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 5818 << FDecl << ParamValueKind << ArgValueKind; 5819 5820 emitReplacement(*this, Call->getExprLoc(), 5821 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 5822 } 5823 5824 //===--- CHECK: Standard memory functions ---------------------------------===// 5825 5826 /// \brief Takes the expression passed to the size_t parameter of functions 5827 /// such as memcmp, strncat, etc and warns if it's a comparison. 5828 /// 5829 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 5830 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 5831 IdentifierInfo *FnName, 5832 SourceLocation FnLoc, 5833 SourceLocation RParenLoc) { 5834 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 5835 if (!Size) 5836 return false; 5837 5838 // if E is binop and op is >, <, >=, <=, ==, &&, ||: 5839 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp()) 5840 return false; 5841 5842 SourceRange SizeRange = Size->getSourceRange(); 5843 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 5844 << SizeRange << FnName; 5845 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 5846 << FnName << FixItHint::CreateInsertion( 5847 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 5848 << FixItHint::CreateRemoval(RParenLoc); 5849 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 5850 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 5851 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 5852 ")"); 5853 5854 return true; 5855 } 5856 5857 /// \brief Determine whether the given type is or contains a dynamic class type 5858 /// (e.g., whether it has a vtable). 5859 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 5860 bool &IsContained) { 5861 // Look through array types while ignoring qualifiers. 5862 const Type *Ty = T->getBaseElementTypeUnsafe(); 5863 IsContained = false; 5864 5865 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 5866 RD = RD ? RD->getDefinition() : nullptr; 5867 if (!RD || RD->isInvalidDecl()) 5868 return nullptr; 5869 5870 if (RD->isDynamicClass()) 5871 return RD; 5872 5873 // Check all the fields. If any bases were dynamic, the class is dynamic. 5874 // It's impossible for a class to transitively contain itself by value, so 5875 // infinite recursion is impossible. 5876 for (auto *FD : RD->fields()) { 5877 bool SubContained; 5878 if (const CXXRecordDecl *ContainedRD = 5879 getContainedDynamicClass(FD->getType(), SubContained)) { 5880 IsContained = true; 5881 return ContainedRD; 5882 } 5883 } 5884 5885 return nullptr; 5886 } 5887 5888 /// \brief If E is a sizeof expression, returns its argument expression, 5889 /// otherwise returns NULL. 5890 static const Expr *getSizeOfExprArg(const Expr *E) { 5891 if (const UnaryExprOrTypeTraitExpr *SizeOf = 5892 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 5893 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType()) 5894 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 5895 5896 return nullptr; 5897 } 5898 5899 /// \brief If E is a sizeof expression, returns its argument type. 5900 static QualType getSizeOfArgType(const Expr *E) { 5901 if (const UnaryExprOrTypeTraitExpr *SizeOf = 5902 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 5903 if (SizeOf->getKind() == clang::UETT_SizeOf) 5904 return SizeOf->getTypeOfArgument(); 5905 5906 return QualType(); 5907 } 5908 5909 /// \brief Check for dangerous or invalid arguments to memset(). 5910 /// 5911 /// This issues warnings on known problematic, dangerous or unspecified 5912 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 5913 /// function calls. 5914 /// 5915 /// \param Call The call expression to diagnose. 5916 void Sema::CheckMemaccessArguments(const CallExpr *Call, 5917 unsigned BId, 5918 IdentifierInfo *FnName) { 5919 assert(BId != 0); 5920 5921 // It is possible to have a non-standard definition of memset. Validate 5922 // we have enough arguments, and if not, abort further checking. 5923 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3); 5924 if (Call->getNumArgs() < ExpectedNumArgs) 5925 return; 5926 5927 unsigned LastArg = (BId == Builtin::BImemset || 5928 BId == Builtin::BIstrndup ? 1 : 2); 5929 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2); 5930 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 5931 5932 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 5933 Call->getLocStart(), Call->getRParenLoc())) 5934 return; 5935 5936 // We have special checking when the length is a sizeof expression. 5937 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 5938 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 5939 llvm::FoldingSetNodeID SizeOfArgID; 5940 5941 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 5942 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 5943 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 5944 5945 QualType DestTy = Dest->getType(); 5946 QualType PointeeTy; 5947 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 5948 PointeeTy = DestPtrTy->getPointeeType(); 5949 5950 // Never warn about void type pointers. This can be used to suppress 5951 // false positives. 5952 if (PointeeTy->isVoidType()) 5953 continue; 5954 5955 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 5956 // actually comparing the expressions for equality. Because computing the 5957 // expression IDs can be expensive, we only do this if the diagnostic is 5958 // enabled. 5959 if (SizeOfArg && 5960 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 5961 SizeOfArg->getExprLoc())) { 5962 // We only compute IDs for expressions if the warning is enabled, and 5963 // cache the sizeof arg's ID. 5964 if (SizeOfArgID == llvm::FoldingSetNodeID()) 5965 SizeOfArg->Profile(SizeOfArgID, Context, true); 5966 llvm::FoldingSetNodeID DestID; 5967 Dest->Profile(DestID, Context, true); 5968 if (DestID == SizeOfArgID) { 5969 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 5970 // over sizeof(src) as well. 5971 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 5972 StringRef ReadableName = FnName->getName(); 5973 5974 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 5975 if (UnaryOp->getOpcode() == UO_AddrOf) 5976 ActionIdx = 1; // If its an address-of operator, just remove it. 5977 if (!PointeeTy->isIncompleteType() && 5978 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 5979 ActionIdx = 2; // If the pointee's size is sizeof(char), 5980 // suggest an explicit length. 5981 5982 // If the function is defined as a builtin macro, do not show macro 5983 // expansion. 5984 SourceLocation SL = SizeOfArg->getExprLoc(); 5985 SourceRange DSR = Dest->getSourceRange(); 5986 SourceRange SSR = SizeOfArg->getSourceRange(); 5987 SourceManager &SM = getSourceManager(); 5988 5989 if (SM.isMacroArgExpansion(SL)) { 5990 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 5991 SL = SM.getSpellingLoc(SL); 5992 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 5993 SM.getSpellingLoc(DSR.getEnd())); 5994 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 5995 SM.getSpellingLoc(SSR.getEnd())); 5996 } 5997 5998 DiagRuntimeBehavior(SL, SizeOfArg, 5999 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 6000 << ReadableName 6001 << PointeeTy 6002 << DestTy 6003 << DSR 6004 << SSR); 6005 DiagRuntimeBehavior(SL, SizeOfArg, 6006 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 6007 << ActionIdx 6008 << SSR); 6009 6010 break; 6011 } 6012 } 6013 6014 // Also check for cases where the sizeof argument is the exact same 6015 // type as the memory argument, and where it points to a user-defined 6016 // record type. 6017 if (SizeOfArgTy != QualType()) { 6018 if (PointeeTy->isRecordType() && 6019 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 6020 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 6021 PDiag(diag::warn_sizeof_pointer_type_memaccess) 6022 << FnName << SizeOfArgTy << ArgIdx 6023 << PointeeTy << Dest->getSourceRange() 6024 << LenExpr->getSourceRange()); 6025 break; 6026 } 6027 } 6028 } else if (DestTy->isArrayType()) { 6029 PointeeTy = DestTy; 6030 } 6031 6032 if (PointeeTy == QualType()) 6033 continue; 6034 6035 // Always complain about dynamic classes. 6036 bool IsContained; 6037 if (const CXXRecordDecl *ContainedRD = 6038 getContainedDynamicClass(PointeeTy, IsContained)) { 6039 6040 unsigned OperationType = 0; 6041 // "overwritten" if we're warning about the destination for any call 6042 // but memcmp; otherwise a verb appropriate to the call. 6043 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 6044 if (BId == Builtin::BImemcpy) 6045 OperationType = 1; 6046 else if(BId == Builtin::BImemmove) 6047 OperationType = 2; 6048 else if (BId == Builtin::BImemcmp) 6049 OperationType = 3; 6050 } 6051 6052 DiagRuntimeBehavior( 6053 Dest->getExprLoc(), Dest, 6054 PDiag(diag::warn_dyn_class_memaccess) 6055 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 6056 << FnName << IsContained << ContainedRD << OperationType 6057 << Call->getCallee()->getSourceRange()); 6058 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 6059 BId != Builtin::BImemset) 6060 DiagRuntimeBehavior( 6061 Dest->getExprLoc(), Dest, 6062 PDiag(diag::warn_arc_object_memaccess) 6063 << ArgIdx << FnName << PointeeTy 6064 << Call->getCallee()->getSourceRange()); 6065 else 6066 continue; 6067 6068 DiagRuntimeBehavior( 6069 Dest->getExprLoc(), Dest, 6070 PDiag(diag::note_bad_memaccess_silence) 6071 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 6072 break; 6073 } 6074 } 6075 6076 // A little helper routine: ignore addition and subtraction of integer literals. 6077 // This intentionally does not ignore all integer constant expressions because 6078 // we don't want to remove sizeof(). 6079 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 6080 Ex = Ex->IgnoreParenCasts(); 6081 6082 for (;;) { 6083 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 6084 if (!BO || !BO->isAdditiveOp()) 6085 break; 6086 6087 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 6088 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 6089 6090 if (isa<IntegerLiteral>(RHS)) 6091 Ex = LHS; 6092 else if (isa<IntegerLiteral>(LHS)) 6093 Ex = RHS; 6094 else 6095 break; 6096 } 6097 6098 return Ex; 6099 } 6100 6101 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 6102 ASTContext &Context) { 6103 // Only handle constant-sized or VLAs, but not flexible members. 6104 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 6105 // Only issue the FIXIT for arrays of size > 1. 6106 if (CAT->getSize().getSExtValue() <= 1) 6107 return false; 6108 } else if (!Ty->isVariableArrayType()) { 6109 return false; 6110 } 6111 return true; 6112 } 6113 6114 // Warn if the user has made the 'size' argument to strlcpy or strlcat 6115 // be the size of the source, instead of the destination. 6116 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 6117 IdentifierInfo *FnName) { 6118 6119 // Don't crash if the user has the wrong number of arguments 6120 unsigned NumArgs = Call->getNumArgs(); 6121 if ((NumArgs != 3) && (NumArgs != 4)) 6122 return; 6123 6124 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 6125 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 6126 const Expr *CompareWithSrc = nullptr; 6127 6128 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 6129 Call->getLocStart(), Call->getRParenLoc())) 6130 return; 6131 6132 // Look for 'strlcpy(dst, x, sizeof(x))' 6133 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 6134 CompareWithSrc = Ex; 6135 else { 6136 // Look for 'strlcpy(dst, x, strlen(x))' 6137 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 6138 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 6139 SizeCall->getNumArgs() == 1) 6140 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 6141 } 6142 } 6143 6144 if (!CompareWithSrc) 6145 return; 6146 6147 // Determine if the argument to sizeof/strlen is equal to the source 6148 // argument. In principle there's all kinds of things you could do 6149 // here, for instance creating an == expression and evaluating it with 6150 // EvaluateAsBooleanCondition, but this uses a more direct technique: 6151 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 6152 if (!SrcArgDRE) 6153 return; 6154 6155 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 6156 if (!CompareWithSrcDRE || 6157 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 6158 return; 6159 6160 const Expr *OriginalSizeArg = Call->getArg(2); 6161 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 6162 << OriginalSizeArg->getSourceRange() << FnName; 6163 6164 // Output a FIXIT hint if the destination is an array (rather than a 6165 // pointer to an array). This could be enhanced to handle some 6166 // pointers if we know the actual size, like if DstArg is 'array+2' 6167 // we could say 'sizeof(array)-2'. 6168 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 6169 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 6170 return; 6171 6172 SmallString<128> sizeString; 6173 llvm::raw_svector_ostream OS(sizeString); 6174 OS << "sizeof("; 6175 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6176 OS << ")"; 6177 6178 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 6179 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 6180 OS.str()); 6181 } 6182 6183 /// Check if two expressions refer to the same declaration. 6184 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 6185 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 6186 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 6187 return D1->getDecl() == D2->getDecl(); 6188 return false; 6189 } 6190 6191 static const Expr *getStrlenExprArg(const Expr *E) { 6192 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6193 const FunctionDecl *FD = CE->getDirectCallee(); 6194 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 6195 return nullptr; 6196 return CE->getArg(0)->IgnoreParenCasts(); 6197 } 6198 return nullptr; 6199 } 6200 6201 // Warn on anti-patterns as the 'size' argument to strncat. 6202 // The correct size argument should look like following: 6203 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 6204 void Sema::CheckStrncatArguments(const CallExpr *CE, 6205 IdentifierInfo *FnName) { 6206 // Don't crash if the user has the wrong number of arguments. 6207 if (CE->getNumArgs() < 3) 6208 return; 6209 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 6210 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 6211 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 6212 6213 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 6214 CE->getRParenLoc())) 6215 return; 6216 6217 // Identify common expressions, which are wrongly used as the size argument 6218 // to strncat and may lead to buffer overflows. 6219 unsigned PatternType = 0; 6220 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 6221 // - sizeof(dst) 6222 if (referToTheSameDecl(SizeOfArg, DstArg)) 6223 PatternType = 1; 6224 // - sizeof(src) 6225 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 6226 PatternType = 2; 6227 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 6228 if (BE->getOpcode() == BO_Sub) { 6229 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 6230 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 6231 // - sizeof(dst) - strlen(dst) 6232 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 6233 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 6234 PatternType = 1; 6235 // - sizeof(src) - (anything) 6236 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 6237 PatternType = 2; 6238 } 6239 } 6240 6241 if (PatternType == 0) 6242 return; 6243 6244 // Generate the diagnostic. 6245 SourceLocation SL = LenArg->getLocStart(); 6246 SourceRange SR = LenArg->getSourceRange(); 6247 SourceManager &SM = getSourceManager(); 6248 6249 // If the function is defined as a builtin macro, do not show macro expansion. 6250 if (SM.isMacroArgExpansion(SL)) { 6251 SL = SM.getSpellingLoc(SL); 6252 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 6253 SM.getSpellingLoc(SR.getEnd())); 6254 } 6255 6256 // Check if the destination is an array (rather than a pointer to an array). 6257 QualType DstTy = DstArg->getType(); 6258 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 6259 Context); 6260 if (!isKnownSizeArray) { 6261 if (PatternType == 1) 6262 Diag(SL, diag::warn_strncat_wrong_size) << SR; 6263 else 6264 Diag(SL, diag::warn_strncat_src_size) << SR; 6265 return; 6266 } 6267 6268 if (PatternType == 1) 6269 Diag(SL, diag::warn_strncat_large_size) << SR; 6270 else 6271 Diag(SL, diag::warn_strncat_src_size) << SR; 6272 6273 SmallString<128> sizeString; 6274 llvm::raw_svector_ostream OS(sizeString); 6275 OS << "sizeof("; 6276 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6277 OS << ") - "; 6278 OS << "strlen("; 6279 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 6280 OS << ") - 1"; 6281 6282 Diag(SL, diag::note_strncat_wrong_size) 6283 << FixItHint::CreateReplacement(SR, OS.str()); 6284 } 6285 6286 //===--- CHECK: Return Address of Stack Variable --------------------------===// 6287 6288 static const Expr *EvalVal(const Expr *E, 6289 SmallVectorImpl<const DeclRefExpr *> &refVars, 6290 const Decl *ParentDecl); 6291 static const Expr *EvalAddr(const Expr *E, 6292 SmallVectorImpl<const DeclRefExpr *> &refVars, 6293 const Decl *ParentDecl); 6294 6295 /// CheckReturnStackAddr - Check if a return statement returns the address 6296 /// of a stack variable. 6297 static void 6298 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 6299 SourceLocation ReturnLoc) { 6300 6301 const Expr *stackE = nullptr; 6302 SmallVector<const DeclRefExpr *, 8> refVars; 6303 6304 // Perform checking for returned stack addresses, local blocks, 6305 // label addresses or references to temporaries. 6306 if (lhsType->isPointerType() || 6307 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 6308 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 6309 } else if (lhsType->isReferenceType()) { 6310 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 6311 } 6312 6313 if (!stackE) 6314 return; // Nothing suspicious was found. 6315 6316 SourceLocation diagLoc; 6317 SourceRange diagRange; 6318 if (refVars.empty()) { 6319 diagLoc = stackE->getLocStart(); 6320 diagRange = stackE->getSourceRange(); 6321 } else { 6322 // We followed through a reference variable. 'stackE' contains the 6323 // problematic expression but we will warn at the return statement pointing 6324 // at the reference variable. We will later display the "trail" of 6325 // reference variables using notes. 6326 diagLoc = refVars[0]->getLocStart(); 6327 diagRange = refVars[0]->getSourceRange(); 6328 } 6329 6330 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 6331 // address of local var 6332 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 6333 << DR->getDecl()->getDeclName() << diagRange; 6334 } else if (isa<BlockExpr>(stackE)) { // local block. 6335 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 6336 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 6337 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 6338 } else { // local temporary. 6339 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 6340 << lhsType->isReferenceType() << diagRange; 6341 } 6342 6343 // Display the "trail" of reference variables that we followed until we 6344 // found the problematic expression using notes. 6345 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 6346 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 6347 // If this var binds to another reference var, show the range of the next 6348 // var, otherwise the var binds to the problematic expression, in which case 6349 // show the range of the expression. 6350 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 6351 : stackE->getSourceRange(); 6352 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 6353 << VD->getDeclName() << range; 6354 } 6355 } 6356 6357 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 6358 /// check if the expression in a return statement evaluates to an address 6359 /// to a location on the stack, a local block, an address of a label, or a 6360 /// reference to local temporary. The recursion is used to traverse the 6361 /// AST of the return expression, with recursion backtracking when we 6362 /// encounter a subexpression that (1) clearly does not lead to one of the 6363 /// above problematic expressions (2) is something we cannot determine leads to 6364 /// a problematic expression based on such local checking. 6365 /// 6366 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 6367 /// the expression that they point to. Such variables are added to the 6368 /// 'refVars' vector so that we know what the reference variable "trail" was. 6369 /// 6370 /// EvalAddr processes expressions that are pointers that are used as 6371 /// references (and not L-values). EvalVal handles all other values. 6372 /// At the base case of the recursion is a check for the above problematic 6373 /// expressions. 6374 /// 6375 /// This implementation handles: 6376 /// 6377 /// * pointer-to-pointer casts 6378 /// * implicit conversions from array references to pointers 6379 /// * taking the address of fields 6380 /// * arbitrary interplay between "&" and "*" operators 6381 /// * pointer arithmetic from an address of a stack variable 6382 /// * taking the address of an array element where the array is on the stack 6383 static const Expr *EvalAddr(const Expr *E, 6384 SmallVectorImpl<const DeclRefExpr *> &refVars, 6385 const Decl *ParentDecl) { 6386 if (E->isTypeDependent()) 6387 return nullptr; 6388 6389 // We should only be called for evaluating pointer expressions. 6390 assert((E->getType()->isAnyPointerType() || 6391 E->getType()->isBlockPointerType() || 6392 E->getType()->isObjCQualifiedIdType()) && 6393 "EvalAddr only works on pointers"); 6394 6395 E = E->IgnoreParens(); 6396 6397 // Our "symbolic interpreter" is just a dispatch off the currently 6398 // viewed AST node. We then recursively traverse the AST by calling 6399 // EvalAddr and EvalVal appropriately. 6400 switch (E->getStmtClass()) { 6401 case Stmt::DeclRefExprClass: { 6402 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6403 6404 // If we leave the immediate function, the lifetime isn't about to end. 6405 if (DR->refersToEnclosingVariableOrCapture()) 6406 return nullptr; 6407 6408 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 6409 // If this is a reference variable, follow through to the expression that 6410 // it points to. 6411 if (V->hasLocalStorage() && 6412 V->getType()->isReferenceType() && V->hasInit()) { 6413 // Add the reference variable to the "trail". 6414 refVars.push_back(DR); 6415 return EvalAddr(V->getInit(), refVars, ParentDecl); 6416 } 6417 6418 return nullptr; 6419 } 6420 6421 case Stmt::UnaryOperatorClass: { 6422 // The only unary operator that make sense to handle here 6423 // is AddrOf. All others don't make sense as pointers. 6424 const UnaryOperator *U = cast<UnaryOperator>(E); 6425 6426 if (U->getOpcode() == UO_AddrOf) 6427 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 6428 return nullptr; 6429 } 6430 6431 case Stmt::BinaryOperatorClass: { 6432 // Handle pointer arithmetic. All other binary operators are not valid 6433 // in this context. 6434 const BinaryOperator *B = cast<BinaryOperator>(E); 6435 BinaryOperatorKind op = B->getOpcode(); 6436 6437 if (op != BO_Add && op != BO_Sub) 6438 return nullptr; 6439 6440 const Expr *Base = B->getLHS(); 6441 6442 // Determine which argument is the real pointer base. It could be 6443 // the RHS argument instead of the LHS. 6444 if (!Base->getType()->isPointerType()) 6445 Base = B->getRHS(); 6446 6447 assert(Base->getType()->isPointerType()); 6448 return EvalAddr(Base, refVars, ParentDecl); 6449 } 6450 6451 // For conditional operators we need to see if either the LHS or RHS are 6452 // valid DeclRefExpr*s. If one of them is valid, we return it. 6453 case Stmt::ConditionalOperatorClass: { 6454 const ConditionalOperator *C = cast<ConditionalOperator>(E); 6455 6456 // Handle the GNU extension for missing LHS. 6457 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 6458 if (const Expr *LHSExpr = C->getLHS()) { 6459 // In C++, we can have a throw-expression, which has 'void' type. 6460 if (!LHSExpr->getType()->isVoidType()) 6461 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 6462 return LHS; 6463 } 6464 6465 // In C++, we can have a throw-expression, which has 'void' type. 6466 if (C->getRHS()->getType()->isVoidType()) 6467 return nullptr; 6468 6469 return EvalAddr(C->getRHS(), refVars, ParentDecl); 6470 } 6471 6472 case Stmt::BlockExprClass: 6473 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 6474 return E; // local block. 6475 return nullptr; 6476 6477 case Stmt::AddrLabelExprClass: 6478 return E; // address of label. 6479 6480 case Stmt::ExprWithCleanupsClass: 6481 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 6482 ParentDecl); 6483 6484 // For casts, we need to handle conversions from arrays to 6485 // pointer values, and pointer-to-pointer conversions. 6486 case Stmt::ImplicitCastExprClass: 6487 case Stmt::CStyleCastExprClass: 6488 case Stmt::CXXFunctionalCastExprClass: 6489 case Stmt::ObjCBridgedCastExprClass: 6490 case Stmt::CXXStaticCastExprClass: 6491 case Stmt::CXXDynamicCastExprClass: 6492 case Stmt::CXXConstCastExprClass: 6493 case Stmt::CXXReinterpretCastExprClass: { 6494 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 6495 switch (cast<CastExpr>(E)->getCastKind()) { 6496 case CK_LValueToRValue: 6497 case CK_NoOp: 6498 case CK_BaseToDerived: 6499 case CK_DerivedToBase: 6500 case CK_UncheckedDerivedToBase: 6501 case CK_Dynamic: 6502 case CK_CPointerToObjCPointerCast: 6503 case CK_BlockPointerToObjCPointerCast: 6504 case CK_AnyPointerToBlockPointerCast: 6505 return EvalAddr(SubExpr, refVars, ParentDecl); 6506 6507 case CK_ArrayToPointerDecay: 6508 return EvalVal(SubExpr, refVars, ParentDecl); 6509 6510 case CK_BitCast: 6511 if (SubExpr->getType()->isAnyPointerType() || 6512 SubExpr->getType()->isBlockPointerType() || 6513 SubExpr->getType()->isObjCQualifiedIdType()) 6514 return EvalAddr(SubExpr, refVars, ParentDecl); 6515 else 6516 return nullptr; 6517 6518 default: 6519 return nullptr; 6520 } 6521 } 6522 6523 case Stmt::MaterializeTemporaryExprClass: 6524 if (const Expr *Result = 6525 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 6526 refVars, ParentDecl)) 6527 return Result; 6528 return E; 6529 6530 // Everything else: we simply don't reason about them. 6531 default: 6532 return nullptr; 6533 } 6534 } 6535 6536 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 6537 /// See the comments for EvalAddr for more details. 6538 static const Expr *EvalVal(const Expr *E, 6539 SmallVectorImpl<const DeclRefExpr *> &refVars, 6540 const Decl *ParentDecl) { 6541 do { 6542 // We should only be called for evaluating non-pointer expressions, or 6543 // expressions with a pointer type that are not used as references but 6544 // instead 6545 // are l-values (e.g., DeclRefExpr with a pointer type). 6546 6547 // Our "symbolic interpreter" is just a dispatch off the currently 6548 // viewed AST node. We then recursively traverse the AST by calling 6549 // EvalAddr and EvalVal appropriately. 6550 6551 E = E->IgnoreParens(); 6552 switch (E->getStmtClass()) { 6553 case Stmt::ImplicitCastExprClass: { 6554 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 6555 if (IE->getValueKind() == VK_LValue) { 6556 E = IE->getSubExpr(); 6557 continue; 6558 } 6559 return nullptr; 6560 } 6561 6562 case Stmt::ExprWithCleanupsClass: 6563 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 6564 ParentDecl); 6565 6566 case Stmt::DeclRefExprClass: { 6567 // When we hit a DeclRefExpr we are looking at code that refers to a 6568 // variable's name. If it's not a reference variable we check if it has 6569 // local storage within the function, and if so, return the expression. 6570 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6571 6572 // If we leave the immediate function, the lifetime isn't about to end. 6573 if (DR->refersToEnclosingVariableOrCapture()) 6574 return nullptr; 6575 6576 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 6577 // Check if it refers to itself, e.g. "int& i = i;". 6578 if (V == ParentDecl) 6579 return DR; 6580 6581 if (V->hasLocalStorage()) { 6582 if (!V->getType()->isReferenceType()) 6583 return DR; 6584 6585 // Reference variable, follow through to the expression that 6586 // it points to. 6587 if (V->hasInit()) { 6588 // Add the reference variable to the "trail". 6589 refVars.push_back(DR); 6590 return EvalVal(V->getInit(), refVars, V); 6591 } 6592 } 6593 } 6594 6595 return nullptr; 6596 } 6597 6598 case Stmt::UnaryOperatorClass: { 6599 // The only unary operator that make sense to handle here 6600 // is Deref. All others don't resolve to a "name." This includes 6601 // handling all sorts of rvalues passed to a unary operator. 6602 const UnaryOperator *U = cast<UnaryOperator>(E); 6603 6604 if (U->getOpcode() == UO_Deref) 6605 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 6606 6607 return nullptr; 6608 } 6609 6610 case Stmt::ArraySubscriptExprClass: { 6611 // Array subscripts are potential references to data on the stack. We 6612 // retrieve the DeclRefExpr* for the array variable if it indeed 6613 // has local storage. 6614 const auto *ASE = cast<ArraySubscriptExpr>(E); 6615 if (ASE->isTypeDependent()) 6616 return nullptr; 6617 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 6618 } 6619 6620 case Stmt::OMPArraySectionExprClass: { 6621 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 6622 ParentDecl); 6623 } 6624 6625 case Stmt::ConditionalOperatorClass: { 6626 // For conditional operators we need to see if either the LHS or RHS are 6627 // non-NULL Expr's. If one is non-NULL, we return it. 6628 const ConditionalOperator *C = cast<ConditionalOperator>(E); 6629 6630 // Handle the GNU extension for missing LHS. 6631 if (const Expr *LHSExpr = C->getLHS()) { 6632 // In C++, we can have a throw-expression, which has 'void' type. 6633 if (!LHSExpr->getType()->isVoidType()) 6634 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 6635 return LHS; 6636 } 6637 6638 // In C++, we can have a throw-expression, which has 'void' type. 6639 if (C->getRHS()->getType()->isVoidType()) 6640 return nullptr; 6641 6642 return EvalVal(C->getRHS(), refVars, ParentDecl); 6643 } 6644 6645 // Accesses to members are potential references to data on the stack. 6646 case Stmt::MemberExprClass: { 6647 const MemberExpr *M = cast<MemberExpr>(E); 6648 6649 // Check for indirect access. We only want direct field accesses. 6650 if (M->isArrow()) 6651 return nullptr; 6652 6653 // Check whether the member type is itself a reference, in which case 6654 // we're not going to refer to the member, but to what the member refers 6655 // to. 6656 if (M->getMemberDecl()->getType()->isReferenceType()) 6657 return nullptr; 6658 6659 return EvalVal(M->getBase(), refVars, ParentDecl); 6660 } 6661 6662 case Stmt::MaterializeTemporaryExprClass: 6663 if (const Expr *Result = 6664 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 6665 refVars, ParentDecl)) 6666 return Result; 6667 return E; 6668 6669 default: 6670 // Check that we don't return or take the address of a reference to a 6671 // temporary. This is only useful in C++. 6672 if (!E->isTypeDependent() && E->isRValue()) 6673 return E; 6674 6675 // Everything else: we simply don't reason about them. 6676 return nullptr; 6677 } 6678 } while (true); 6679 } 6680 6681 void 6682 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 6683 SourceLocation ReturnLoc, 6684 bool isObjCMethod, 6685 const AttrVec *Attrs, 6686 const FunctionDecl *FD) { 6687 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 6688 6689 // Check if the return value is null but should not be. 6690 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 6691 (!isObjCMethod && isNonNullType(Context, lhsType))) && 6692 CheckNonNullExpr(*this, RetValExp)) 6693 Diag(ReturnLoc, diag::warn_null_ret) 6694 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 6695 6696 // C++11 [basic.stc.dynamic.allocation]p4: 6697 // If an allocation function declared with a non-throwing 6698 // exception-specification fails to allocate storage, it shall return 6699 // a null pointer. Any other allocation function that fails to allocate 6700 // storage shall indicate failure only by throwing an exception [...] 6701 if (FD) { 6702 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 6703 if (Op == OO_New || Op == OO_Array_New) { 6704 const FunctionProtoType *Proto 6705 = FD->getType()->castAs<FunctionProtoType>(); 6706 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) && 6707 CheckNonNullExpr(*this, RetValExp)) 6708 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 6709 << FD << getLangOpts().CPlusPlus11; 6710 } 6711 } 6712 } 6713 6714 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 6715 6716 /// Check for comparisons of floating point operands using != and ==. 6717 /// Issue a warning if these are no self-comparisons, as they are not likely 6718 /// to do what the programmer intended. 6719 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 6720 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 6721 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 6722 6723 // Special case: check for x == x (which is OK). 6724 // Do not emit warnings for such cases. 6725 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 6726 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 6727 if (DRL->getDecl() == DRR->getDecl()) 6728 return; 6729 6730 // Special case: check for comparisons against literals that can be exactly 6731 // represented by APFloat. In such cases, do not emit a warning. This 6732 // is a heuristic: often comparison against such literals are used to 6733 // detect if a value in a variable has not changed. This clearly can 6734 // lead to false negatives. 6735 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 6736 if (FLL->isExact()) 6737 return; 6738 } else 6739 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 6740 if (FLR->isExact()) 6741 return; 6742 6743 // Check for comparisons with builtin types. 6744 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 6745 if (CL->getBuiltinCallee()) 6746 return; 6747 6748 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 6749 if (CR->getBuiltinCallee()) 6750 return; 6751 6752 // Emit the diagnostic. 6753 Diag(Loc, diag::warn_floatingpoint_eq) 6754 << LHS->getSourceRange() << RHS->getSourceRange(); 6755 } 6756 6757 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 6758 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 6759 6760 namespace { 6761 6762 /// Structure recording the 'active' range of an integer-valued 6763 /// expression. 6764 struct IntRange { 6765 /// The number of bits active in the int. 6766 unsigned Width; 6767 6768 /// True if the int is known not to have negative values. 6769 bool NonNegative; 6770 6771 IntRange(unsigned Width, bool NonNegative) 6772 : Width(Width), NonNegative(NonNegative) 6773 {} 6774 6775 /// Returns the range of the bool type. 6776 static IntRange forBoolType() { 6777 return IntRange(1, true); 6778 } 6779 6780 /// Returns the range of an opaque value of the given integral type. 6781 static IntRange forValueOfType(ASTContext &C, QualType T) { 6782 return forValueOfCanonicalType(C, 6783 T->getCanonicalTypeInternal().getTypePtr()); 6784 } 6785 6786 /// Returns the range of an opaque value of a canonical integral type. 6787 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 6788 assert(T->isCanonicalUnqualified()); 6789 6790 if (const VectorType *VT = dyn_cast<VectorType>(T)) 6791 T = VT->getElementType().getTypePtr(); 6792 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 6793 T = CT->getElementType().getTypePtr(); 6794 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 6795 T = AT->getValueType().getTypePtr(); 6796 6797 // For enum types, use the known bit width of the enumerators. 6798 if (const EnumType *ET = dyn_cast<EnumType>(T)) { 6799 EnumDecl *Enum = ET->getDecl(); 6800 if (!Enum->isCompleteDefinition()) 6801 return IntRange(C.getIntWidth(QualType(T, 0)), false); 6802 6803 unsigned NumPositive = Enum->getNumPositiveBits(); 6804 unsigned NumNegative = Enum->getNumNegativeBits(); 6805 6806 if (NumNegative == 0) 6807 return IntRange(NumPositive, true/*NonNegative*/); 6808 else 6809 return IntRange(std::max(NumPositive + 1, NumNegative), 6810 false/*NonNegative*/); 6811 } 6812 6813 const BuiltinType *BT = cast<BuiltinType>(T); 6814 assert(BT->isInteger()); 6815 6816 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 6817 } 6818 6819 /// Returns the "target" range of a canonical integral type, i.e. 6820 /// the range of values expressible in the type. 6821 /// 6822 /// This matches forValueOfCanonicalType except that enums have the 6823 /// full range of their type, not the range of their enumerators. 6824 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 6825 assert(T->isCanonicalUnqualified()); 6826 6827 if (const VectorType *VT = dyn_cast<VectorType>(T)) 6828 T = VT->getElementType().getTypePtr(); 6829 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 6830 T = CT->getElementType().getTypePtr(); 6831 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 6832 T = AT->getValueType().getTypePtr(); 6833 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6834 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 6835 6836 const BuiltinType *BT = cast<BuiltinType>(T); 6837 assert(BT->isInteger()); 6838 6839 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 6840 } 6841 6842 /// Returns the supremum of two ranges: i.e. their conservative merge. 6843 static IntRange join(IntRange L, IntRange R) { 6844 return IntRange(std::max(L.Width, R.Width), 6845 L.NonNegative && R.NonNegative); 6846 } 6847 6848 /// Returns the infinum of two ranges: i.e. their aggressive merge. 6849 static IntRange meet(IntRange L, IntRange R) { 6850 return IntRange(std::min(L.Width, R.Width), 6851 L.NonNegative || R.NonNegative); 6852 } 6853 }; 6854 6855 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) { 6856 if (value.isSigned() && value.isNegative()) 6857 return IntRange(value.getMinSignedBits(), false); 6858 6859 if (value.getBitWidth() > MaxWidth) 6860 value = value.trunc(MaxWidth); 6861 6862 // isNonNegative() just checks the sign bit without considering 6863 // signedness. 6864 return IntRange(value.getActiveBits(), true); 6865 } 6866 6867 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 6868 unsigned MaxWidth) { 6869 if (result.isInt()) 6870 return GetValueRange(C, result.getInt(), MaxWidth); 6871 6872 if (result.isVector()) { 6873 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 6874 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 6875 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 6876 R = IntRange::join(R, El); 6877 } 6878 return R; 6879 } 6880 6881 if (result.isComplexInt()) { 6882 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 6883 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 6884 return IntRange::join(R, I); 6885 } 6886 6887 // This can happen with lossless casts to intptr_t of "based" lvalues. 6888 // Assume it might use arbitrary bits. 6889 // FIXME: The only reason we need to pass the type in here is to get 6890 // the sign right on this one case. It would be nice if APValue 6891 // preserved this. 6892 assert(result.isLValue() || result.isAddrLabelDiff()); 6893 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 6894 } 6895 6896 QualType GetExprType(const Expr *E) { 6897 QualType Ty = E->getType(); 6898 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 6899 Ty = AtomicRHS->getValueType(); 6900 return Ty; 6901 } 6902 6903 /// Pseudo-evaluate the given integer expression, estimating the 6904 /// range of values it might take. 6905 /// 6906 /// \param MaxWidth - the width to which the value will be truncated 6907 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 6908 E = E->IgnoreParens(); 6909 6910 // Try a full evaluation first. 6911 Expr::EvalResult result; 6912 if (E->EvaluateAsRValue(result, C)) 6913 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 6914 6915 // I think we only want to look through implicit casts here; if the 6916 // user has an explicit widening cast, we should treat the value as 6917 // being of the new, wider type. 6918 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 6919 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 6920 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 6921 6922 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 6923 6924 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 6925 CE->getCastKind() == CK_BooleanToSignedIntegral; 6926 6927 // Assume that non-integer casts can span the full range of the type. 6928 if (!isIntegerCast) 6929 return OutputTypeRange; 6930 6931 IntRange SubRange 6932 = GetExprRange(C, CE->getSubExpr(), 6933 std::min(MaxWidth, OutputTypeRange.Width)); 6934 6935 // Bail out if the subexpr's range is as wide as the cast type. 6936 if (SubRange.Width >= OutputTypeRange.Width) 6937 return OutputTypeRange; 6938 6939 // Otherwise, we take the smaller width, and we're non-negative if 6940 // either the output type or the subexpr is. 6941 return IntRange(SubRange.Width, 6942 SubRange.NonNegative || OutputTypeRange.NonNegative); 6943 } 6944 6945 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 6946 // If we can fold the condition, just take that operand. 6947 bool CondResult; 6948 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 6949 return GetExprRange(C, CondResult ? CO->getTrueExpr() 6950 : CO->getFalseExpr(), 6951 MaxWidth); 6952 6953 // Otherwise, conservatively merge. 6954 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 6955 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 6956 return IntRange::join(L, R); 6957 } 6958 6959 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 6960 switch (BO->getOpcode()) { 6961 6962 // Boolean-valued operations are single-bit and positive. 6963 case BO_LAnd: 6964 case BO_LOr: 6965 case BO_LT: 6966 case BO_GT: 6967 case BO_LE: 6968 case BO_GE: 6969 case BO_EQ: 6970 case BO_NE: 6971 return IntRange::forBoolType(); 6972 6973 // The type of the assignments is the type of the LHS, so the RHS 6974 // is not necessarily the same type. 6975 case BO_MulAssign: 6976 case BO_DivAssign: 6977 case BO_RemAssign: 6978 case BO_AddAssign: 6979 case BO_SubAssign: 6980 case BO_XorAssign: 6981 case BO_OrAssign: 6982 // TODO: bitfields? 6983 return IntRange::forValueOfType(C, GetExprType(E)); 6984 6985 // Simple assignments just pass through the RHS, which will have 6986 // been coerced to the LHS type. 6987 case BO_Assign: 6988 // TODO: bitfields? 6989 return GetExprRange(C, BO->getRHS(), MaxWidth); 6990 6991 // Operations with opaque sources are black-listed. 6992 case BO_PtrMemD: 6993 case BO_PtrMemI: 6994 return IntRange::forValueOfType(C, GetExprType(E)); 6995 6996 // Bitwise-and uses the *infinum* of the two source ranges. 6997 case BO_And: 6998 case BO_AndAssign: 6999 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 7000 GetExprRange(C, BO->getRHS(), MaxWidth)); 7001 7002 // Left shift gets black-listed based on a judgement call. 7003 case BO_Shl: 7004 // ...except that we want to treat '1 << (blah)' as logically 7005 // positive. It's an important idiom. 7006 if (IntegerLiteral *I 7007 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 7008 if (I->getValue() == 1) { 7009 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 7010 return IntRange(R.Width, /*NonNegative*/ true); 7011 } 7012 } 7013 // fallthrough 7014 7015 case BO_ShlAssign: 7016 return IntRange::forValueOfType(C, GetExprType(E)); 7017 7018 // Right shift by a constant can narrow its left argument. 7019 case BO_Shr: 7020 case BO_ShrAssign: { 7021 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7022 7023 // If the shift amount is a positive constant, drop the width by 7024 // that much. 7025 llvm::APSInt shift; 7026 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 7027 shift.isNonNegative()) { 7028 unsigned zext = shift.getZExtValue(); 7029 if (zext >= L.Width) 7030 L.Width = (L.NonNegative ? 0 : 1); 7031 else 7032 L.Width -= zext; 7033 } 7034 7035 return L; 7036 } 7037 7038 // Comma acts as its right operand. 7039 case BO_Comma: 7040 return GetExprRange(C, BO->getRHS(), MaxWidth); 7041 7042 // Black-list pointer subtractions. 7043 case BO_Sub: 7044 if (BO->getLHS()->getType()->isPointerType()) 7045 return IntRange::forValueOfType(C, GetExprType(E)); 7046 break; 7047 7048 // The width of a division result is mostly determined by the size 7049 // of the LHS. 7050 case BO_Div: { 7051 // Don't 'pre-truncate' the operands. 7052 unsigned opWidth = C.getIntWidth(GetExprType(E)); 7053 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 7054 7055 // If the divisor is constant, use that. 7056 llvm::APSInt divisor; 7057 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 7058 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 7059 if (log2 >= L.Width) 7060 L.Width = (L.NonNegative ? 0 : 1); 7061 else 7062 L.Width = std::min(L.Width - log2, MaxWidth); 7063 return L; 7064 } 7065 7066 // Otherwise, just use the LHS's width. 7067 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 7068 return IntRange(L.Width, L.NonNegative && R.NonNegative); 7069 } 7070 7071 // The result of a remainder can't be larger than the result of 7072 // either side. 7073 case BO_Rem: { 7074 // Don't 'pre-truncate' the operands. 7075 unsigned opWidth = C.getIntWidth(GetExprType(E)); 7076 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 7077 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 7078 7079 IntRange meet = IntRange::meet(L, R); 7080 meet.Width = std::min(meet.Width, MaxWidth); 7081 return meet; 7082 } 7083 7084 // The default behavior is okay for these. 7085 case BO_Mul: 7086 case BO_Add: 7087 case BO_Xor: 7088 case BO_Or: 7089 break; 7090 } 7091 7092 // The default case is to treat the operation as if it were closed 7093 // on the narrowest type that encompasses both operands. 7094 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 7095 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 7096 return IntRange::join(L, R); 7097 } 7098 7099 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 7100 switch (UO->getOpcode()) { 7101 // Boolean-valued operations are white-listed. 7102 case UO_LNot: 7103 return IntRange::forBoolType(); 7104 7105 // Operations with opaque sources are black-listed. 7106 case UO_Deref: 7107 case UO_AddrOf: // should be impossible 7108 return IntRange::forValueOfType(C, GetExprType(E)); 7109 7110 default: 7111 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 7112 } 7113 } 7114 7115 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 7116 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 7117 7118 if (const auto *BitField = E->getSourceBitField()) 7119 return IntRange(BitField->getBitWidthValue(C), 7120 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 7121 7122 return IntRange::forValueOfType(C, GetExprType(E)); 7123 } 7124 7125 IntRange GetExprRange(ASTContext &C, const Expr *E) { 7126 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 7127 } 7128 7129 /// Checks whether the given value, which currently has the given 7130 /// source semantics, has the same value when coerced through the 7131 /// target semantics. 7132 bool IsSameFloatAfterCast(const llvm::APFloat &value, 7133 const llvm::fltSemantics &Src, 7134 const llvm::fltSemantics &Tgt) { 7135 llvm::APFloat truncated = value; 7136 7137 bool ignored; 7138 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 7139 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 7140 7141 return truncated.bitwiseIsEqual(value); 7142 } 7143 7144 /// Checks whether the given value, which currently has the given 7145 /// source semantics, has the same value when coerced through the 7146 /// target semantics. 7147 /// 7148 /// The value might be a vector of floats (or a complex number). 7149 bool IsSameFloatAfterCast(const APValue &value, 7150 const llvm::fltSemantics &Src, 7151 const llvm::fltSemantics &Tgt) { 7152 if (value.isFloat()) 7153 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 7154 7155 if (value.isVector()) { 7156 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 7157 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 7158 return false; 7159 return true; 7160 } 7161 7162 assert(value.isComplexFloat()); 7163 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 7164 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 7165 } 7166 7167 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 7168 7169 bool IsZero(Sema &S, Expr *E) { 7170 // Suppress cases where we are comparing against an enum constant. 7171 if (const DeclRefExpr *DR = 7172 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 7173 if (isa<EnumConstantDecl>(DR->getDecl())) 7174 return false; 7175 7176 // Suppress cases where the '0' value is expanded from a macro. 7177 if (E->getLocStart().isMacroID()) 7178 return false; 7179 7180 llvm::APSInt Value; 7181 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0; 7182 } 7183 7184 bool HasEnumType(Expr *E) { 7185 // Strip off implicit integral promotions. 7186 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7187 if (ICE->getCastKind() != CK_IntegralCast && 7188 ICE->getCastKind() != CK_NoOp) 7189 break; 7190 E = ICE->getSubExpr(); 7191 } 7192 7193 return E->getType()->isEnumeralType(); 7194 } 7195 7196 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) { 7197 // Disable warning in template instantiations. 7198 if (!S.ActiveTemplateInstantiations.empty()) 7199 return; 7200 7201 BinaryOperatorKind op = E->getOpcode(); 7202 if (E->isValueDependent()) 7203 return; 7204 7205 if (op == BO_LT && IsZero(S, E->getRHS())) { 7206 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 7207 << "< 0" << "false" << HasEnumType(E->getLHS()) 7208 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7209 } else if (op == BO_GE && IsZero(S, E->getRHS())) { 7210 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison) 7211 << ">= 0" << "true" << HasEnumType(E->getLHS()) 7212 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7213 } else if (op == BO_GT && IsZero(S, E->getLHS())) { 7214 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 7215 << "0 >" << "false" << HasEnumType(E->getRHS()) 7216 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7217 } else if (op == BO_LE && IsZero(S, E->getLHS())) { 7218 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison) 7219 << "0 <=" << "true" << HasEnumType(E->getRHS()) 7220 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 7221 } 7222 } 7223 7224 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant, 7225 Expr *Other, const llvm::APSInt &Value, 7226 bool RhsConstant) { 7227 // Disable warning in template instantiations. 7228 if (!S.ActiveTemplateInstantiations.empty()) 7229 return; 7230 7231 // TODO: Investigate using GetExprRange() to get tighter bounds 7232 // on the bit ranges. 7233 QualType OtherT = Other->getType(); 7234 if (const auto *AT = OtherT->getAs<AtomicType>()) 7235 OtherT = AT->getValueType(); 7236 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 7237 unsigned OtherWidth = OtherRange.Width; 7238 7239 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue(); 7240 7241 // 0 values are handled later by CheckTrivialUnsignedComparison(). 7242 if ((Value == 0) && (!OtherIsBooleanType)) 7243 return; 7244 7245 BinaryOperatorKind op = E->getOpcode(); 7246 bool IsTrue = true; 7247 7248 // Used for diagnostic printout. 7249 enum { 7250 LiteralConstant = 0, 7251 CXXBoolLiteralTrue, 7252 CXXBoolLiteralFalse 7253 } LiteralOrBoolConstant = LiteralConstant; 7254 7255 if (!OtherIsBooleanType) { 7256 QualType ConstantT = Constant->getType(); 7257 QualType CommonT = E->getLHS()->getType(); 7258 7259 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT)) 7260 return; 7261 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) && 7262 "comparison with non-integer type"); 7263 7264 bool ConstantSigned = ConstantT->isSignedIntegerType(); 7265 bool CommonSigned = CommonT->isSignedIntegerType(); 7266 7267 bool EqualityOnly = false; 7268 7269 if (CommonSigned) { 7270 // The common type is signed, therefore no signed to unsigned conversion. 7271 if (!OtherRange.NonNegative) { 7272 // Check that the constant is representable in type OtherT. 7273 if (ConstantSigned) { 7274 if (OtherWidth >= Value.getMinSignedBits()) 7275 return; 7276 } else { // !ConstantSigned 7277 if (OtherWidth >= Value.getActiveBits() + 1) 7278 return; 7279 } 7280 } else { // !OtherSigned 7281 // Check that the constant is representable in type OtherT. 7282 // Negative values are out of range. 7283 if (ConstantSigned) { 7284 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits()) 7285 return; 7286 } else { // !ConstantSigned 7287 if (OtherWidth >= Value.getActiveBits()) 7288 return; 7289 } 7290 } 7291 } else { // !CommonSigned 7292 if (OtherRange.NonNegative) { 7293 if (OtherWidth >= Value.getActiveBits()) 7294 return; 7295 } else { // OtherSigned 7296 assert(!ConstantSigned && 7297 "Two signed types converted to unsigned types."); 7298 // Check to see if the constant is representable in OtherT. 7299 if (OtherWidth > Value.getActiveBits()) 7300 return; 7301 // Check to see if the constant is equivalent to a negative value 7302 // cast to CommonT. 7303 if (S.Context.getIntWidth(ConstantT) == 7304 S.Context.getIntWidth(CommonT) && 7305 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth) 7306 return; 7307 // The constant value rests between values that OtherT can represent 7308 // after conversion. Relational comparison still works, but equality 7309 // comparisons will be tautological. 7310 EqualityOnly = true; 7311 } 7312 } 7313 7314 bool PositiveConstant = !ConstantSigned || Value.isNonNegative(); 7315 7316 if (op == BO_EQ || op == BO_NE) { 7317 IsTrue = op == BO_NE; 7318 } else if (EqualityOnly) { 7319 return; 7320 } else if (RhsConstant) { 7321 if (op == BO_GT || op == BO_GE) 7322 IsTrue = !PositiveConstant; 7323 else // op == BO_LT || op == BO_LE 7324 IsTrue = PositiveConstant; 7325 } else { 7326 if (op == BO_LT || op == BO_LE) 7327 IsTrue = !PositiveConstant; 7328 else // op == BO_GT || op == BO_GE 7329 IsTrue = PositiveConstant; 7330 } 7331 } else { 7332 // Other isKnownToHaveBooleanValue 7333 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn }; 7334 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal }; 7335 enum ConstantSide { Lhs, Rhs, SizeOfConstSides }; 7336 7337 static const struct LinkedConditions { 7338 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal]; 7339 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal]; 7340 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal]; 7341 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal]; 7342 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal]; 7343 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal]; 7344 7345 } TruthTable = { 7346 // Constant on LHS. | Constant on RHS. | 7347 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One| 7348 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } }, 7349 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } }, 7350 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } }, 7351 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } }, 7352 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } }, 7353 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } } 7354 }; 7355 7356 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant); 7357 7358 enum ConstantValue ConstVal = Zero; 7359 if (Value.isUnsigned() || Value.isNonNegative()) { 7360 if (Value == 0) { 7361 LiteralOrBoolConstant = 7362 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant; 7363 ConstVal = Zero; 7364 } else if (Value == 1) { 7365 LiteralOrBoolConstant = 7366 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant; 7367 ConstVal = One; 7368 } else { 7369 LiteralOrBoolConstant = LiteralConstant; 7370 ConstVal = GT_One; 7371 } 7372 } else { 7373 ConstVal = LT_Zero; 7374 } 7375 7376 CompareBoolWithConstantResult CmpRes; 7377 7378 switch (op) { 7379 case BO_LT: 7380 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal]; 7381 break; 7382 case BO_GT: 7383 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal]; 7384 break; 7385 case BO_LE: 7386 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal]; 7387 break; 7388 case BO_GE: 7389 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal]; 7390 break; 7391 case BO_EQ: 7392 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal]; 7393 break; 7394 case BO_NE: 7395 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal]; 7396 break; 7397 default: 7398 CmpRes = Unkwn; 7399 break; 7400 } 7401 7402 if (CmpRes == AFals) { 7403 IsTrue = false; 7404 } else if (CmpRes == ATrue) { 7405 IsTrue = true; 7406 } else { 7407 return; 7408 } 7409 } 7410 7411 // If this is a comparison to an enum constant, include that 7412 // constant in the diagnostic. 7413 const EnumConstantDecl *ED = nullptr; 7414 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 7415 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 7416 7417 SmallString<64> PrettySourceValue; 7418 llvm::raw_svector_ostream OS(PrettySourceValue); 7419 if (ED) 7420 OS << '\'' << *ED << "' (" << Value << ")"; 7421 else 7422 OS << Value; 7423 7424 S.DiagRuntimeBehavior( 7425 E->getOperatorLoc(), E, 7426 S.PDiag(diag::warn_out_of_range_compare) 7427 << OS.str() << LiteralOrBoolConstant 7428 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue 7429 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 7430 } 7431 7432 /// Analyze the operands of the given comparison. Implements the 7433 /// fallback case from AnalyzeComparison. 7434 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 7435 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 7436 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 7437 } 7438 7439 /// \brief Implements -Wsign-compare. 7440 /// 7441 /// \param E the binary operator to check for warnings 7442 void AnalyzeComparison(Sema &S, BinaryOperator *E) { 7443 // The type the comparison is being performed in. 7444 QualType T = E->getLHS()->getType(); 7445 7446 // Only analyze comparison operators where both sides have been converted to 7447 // the same type. 7448 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 7449 return AnalyzeImpConvsInComparison(S, E); 7450 7451 // Don't analyze value-dependent comparisons directly. 7452 if (E->isValueDependent()) 7453 return AnalyzeImpConvsInComparison(S, E); 7454 7455 Expr *LHS = E->getLHS()->IgnoreParenImpCasts(); 7456 Expr *RHS = E->getRHS()->IgnoreParenImpCasts(); 7457 7458 bool IsComparisonConstant = false; 7459 7460 // Check whether an integer constant comparison results in a value 7461 // of 'true' or 'false'. 7462 if (T->isIntegralType(S.Context)) { 7463 llvm::APSInt RHSValue; 7464 bool IsRHSIntegralLiteral = 7465 RHS->isIntegerConstantExpr(RHSValue, S.Context); 7466 llvm::APSInt LHSValue; 7467 bool IsLHSIntegralLiteral = 7468 LHS->isIntegerConstantExpr(LHSValue, S.Context); 7469 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral) 7470 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true); 7471 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral) 7472 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false); 7473 else 7474 IsComparisonConstant = 7475 (IsRHSIntegralLiteral && IsLHSIntegralLiteral); 7476 } else if (!T->hasUnsignedIntegerRepresentation()) 7477 IsComparisonConstant = E->isIntegerConstantExpr(S.Context); 7478 7479 // We don't do anything special if this isn't an unsigned integral 7480 // comparison: we're only interested in integral comparisons, and 7481 // signed comparisons only happen in cases we don't care to warn about. 7482 // 7483 // We also don't care about value-dependent expressions or expressions 7484 // whose result is a constant. 7485 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant) 7486 return AnalyzeImpConvsInComparison(S, E); 7487 7488 // Check to see if one of the (unmodified) operands is of different 7489 // signedness. 7490 Expr *signedOperand, *unsignedOperand; 7491 if (LHS->getType()->hasSignedIntegerRepresentation()) { 7492 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 7493 "unsigned comparison between two signed integer expressions?"); 7494 signedOperand = LHS; 7495 unsignedOperand = RHS; 7496 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 7497 signedOperand = RHS; 7498 unsignedOperand = LHS; 7499 } else { 7500 CheckTrivialUnsignedComparison(S, E); 7501 return AnalyzeImpConvsInComparison(S, E); 7502 } 7503 7504 // Otherwise, calculate the effective range of the signed operand. 7505 IntRange signedRange = GetExprRange(S.Context, signedOperand); 7506 7507 // Go ahead and analyze implicit conversions in the operands. Note 7508 // that we skip the implicit conversions on both sides. 7509 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 7510 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 7511 7512 // If the signed range is non-negative, -Wsign-compare won't fire, 7513 // but we should still check for comparisons which are always true 7514 // or false. 7515 if (signedRange.NonNegative) 7516 return CheckTrivialUnsignedComparison(S, E); 7517 7518 // For (in)equality comparisons, if the unsigned operand is a 7519 // constant which cannot collide with a overflowed signed operand, 7520 // then reinterpreting the signed operand as unsigned will not 7521 // change the result of the comparison. 7522 if (E->isEqualityOp()) { 7523 unsigned comparisonWidth = S.Context.getIntWidth(T); 7524 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 7525 7526 // We should never be unable to prove that the unsigned operand is 7527 // non-negative. 7528 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 7529 7530 if (unsignedRange.Width < comparisonWidth) 7531 return; 7532 } 7533 7534 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 7535 S.PDiag(diag::warn_mixed_sign_comparison) 7536 << LHS->getType() << RHS->getType() 7537 << LHS->getSourceRange() << RHS->getSourceRange()); 7538 } 7539 7540 /// Analyzes an attempt to assign the given value to a bitfield. 7541 /// 7542 /// Returns true if there was something fishy about the attempt. 7543 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 7544 SourceLocation InitLoc) { 7545 assert(Bitfield->isBitField()); 7546 if (Bitfield->isInvalidDecl()) 7547 return false; 7548 7549 // White-list bool bitfields. 7550 if (Bitfield->getType()->isBooleanType()) 7551 return false; 7552 7553 // Ignore value- or type-dependent expressions. 7554 if (Bitfield->getBitWidth()->isValueDependent() || 7555 Bitfield->getBitWidth()->isTypeDependent() || 7556 Init->isValueDependent() || 7557 Init->isTypeDependent()) 7558 return false; 7559 7560 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 7561 7562 llvm::APSInt Value; 7563 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) 7564 return false; 7565 7566 unsigned OriginalWidth = Value.getBitWidth(); 7567 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 7568 7569 if (OriginalWidth <= FieldWidth) 7570 return false; 7571 7572 // Compute the value which the bitfield will contain. 7573 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 7574 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType()); 7575 7576 // Check whether the stored value is equal to the original value. 7577 TruncatedValue = TruncatedValue.extend(OriginalWidth); 7578 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 7579 return false; 7580 7581 // Special-case bitfields of width 1: booleans are naturally 0/1, and 7582 // therefore don't strictly fit into a signed bitfield of width 1. 7583 if (FieldWidth == 1 && Value == 1) 7584 return false; 7585 7586 std::string PrettyValue = Value.toString(10); 7587 std::string PrettyTrunc = TruncatedValue.toString(10); 7588 7589 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 7590 << PrettyValue << PrettyTrunc << OriginalInit->getType() 7591 << Init->getSourceRange(); 7592 7593 return true; 7594 } 7595 7596 /// Analyze the given simple or compound assignment for warning-worthy 7597 /// operations. 7598 void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 7599 // Just recurse on the LHS. 7600 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 7601 7602 // We want to recurse on the RHS as normal unless we're assigning to 7603 // a bitfield. 7604 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 7605 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 7606 E->getOperatorLoc())) { 7607 // Recurse, ignoring any implicit conversions on the RHS. 7608 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 7609 E->getOperatorLoc()); 7610 } 7611 } 7612 7613 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 7614 } 7615 7616 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 7617 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 7618 SourceLocation CContext, unsigned diag, 7619 bool pruneControlFlow = false) { 7620 if (pruneControlFlow) { 7621 S.DiagRuntimeBehavior(E->getExprLoc(), E, 7622 S.PDiag(diag) 7623 << SourceType << T << E->getSourceRange() 7624 << SourceRange(CContext)); 7625 return; 7626 } 7627 S.Diag(E->getExprLoc(), diag) 7628 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 7629 } 7630 7631 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 7632 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext, 7633 unsigned diag, bool pruneControlFlow = false) { 7634 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 7635 } 7636 7637 7638 /// Diagnose an implicit cast from a floating point value to an integer value. 7639 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 7640 7641 SourceLocation CContext) { 7642 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 7643 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty(); 7644 7645 Expr *InnerE = E->IgnoreParenImpCasts(); 7646 // We also want to warn on, e.g., "int i = -1.234" 7647 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 7648 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 7649 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 7650 7651 const bool IsLiteral = 7652 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 7653 7654 llvm::APFloat Value(0.0); 7655 bool IsConstant = 7656 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 7657 if (!IsConstant) { 7658 return DiagnoseImpCast(S, E, T, CContext, 7659 diag::warn_impcast_float_integer, PruneWarnings); 7660 } 7661 7662 bool isExact = false; 7663 7664 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 7665 T->hasUnsignedIntegerRepresentation()); 7666 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero, 7667 &isExact) == llvm::APFloat::opOK && 7668 isExact) { 7669 if (IsLiteral) return; 7670 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 7671 PruneWarnings); 7672 } 7673 7674 unsigned DiagID = 0; 7675 if (IsLiteral) { 7676 // Warn on floating point literal to integer. 7677 DiagID = diag::warn_impcast_literal_float_to_integer; 7678 } else if (IntegerValue == 0) { 7679 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 7680 return DiagnoseImpCast(S, E, T, CContext, 7681 diag::warn_impcast_float_integer, PruneWarnings); 7682 } 7683 // Warn on non-zero to zero conversion. 7684 DiagID = diag::warn_impcast_float_to_integer_zero; 7685 } else { 7686 if (IntegerValue.isUnsigned()) { 7687 if (!IntegerValue.isMaxValue()) { 7688 return DiagnoseImpCast(S, E, T, CContext, 7689 diag::warn_impcast_float_integer, PruneWarnings); 7690 } 7691 } else { // IntegerValue.isSigned() 7692 if (!IntegerValue.isMaxSignedValue() && 7693 !IntegerValue.isMinSignedValue()) { 7694 return DiagnoseImpCast(S, E, T, CContext, 7695 diag::warn_impcast_float_integer, PruneWarnings); 7696 } 7697 } 7698 // Warn on evaluatable floating point expression to integer conversion. 7699 DiagID = diag::warn_impcast_float_to_integer; 7700 } 7701 7702 // FIXME: Force the precision of the source value down so we don't print 7703 // digits which are usually useless (we don't really care here if we 7704 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 7705 // would automatically print the shortest representation, but it's a bit 7706 // tricky to implement. 7707 SmallString<16> PrettySourceValue; 7708 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 7709 precision = (precision * 59 + 195) / 196; 7710 Value.toString(PrettySourceValue, precision); 7711 7712 SmallString<16> PrettyTargetValue; 7713 if (IsBool) 7714 PrettyTargetValue = Value.isZero() ? "false" : "true"; 7715 else 7716 IntegerValue.toString(PrettyTargetValue); 7717 7718 if (PruneWarnings) { 7719 S.DiagRuntimeBehavior(E->getExprLoc(), E, 7720 S.PDiag(DiagID) 7721 << E->getType() << T.getUnqualifiedType() 7722 << PrettySourceValue << PrettyTargetValue 7723 << E->getSourceRange() << SourceRange(CContext)); 7724 } else { 7725 S.Diag(E->getExprLoc(), DiagID) 7726 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 7727 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 7728 } 7729 } 7730 7731 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) { 7732 if (!Range.Width) return "0"; 7733 7734 llvm::APSInt ValueInRange = Value; 7735 ValueInRange.setIsSigned(!Range.NonNegative); 7736 ValueInRange = ValueInRange.trunc(Range.Width); 7737 return ValueInRange.toString(10); 7738 } 7739 7740 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 7741 if (!isa<ImplicitCastExpr>(Ex)) 7742 return false; 7743 7744 Expr *InnerE = Ex->IgnoreParenImpCasts(); 7745 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 7746 const Type *Source = 7747 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 7748 if (Target->isDependentType()) 7749 return false; 7750 7751 const BuiltinType *FloatCandidateBT = 7752 dyn_cast<BuiltinType>(ToBool ? Source : Target); 7753 const Type *BoolCandidateType = ToBool ? Target : Source; 7754 7755 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 7756 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 7757 } 7758 7759 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 7760 SourceLocation CC) { 7761 unsigned NumArgs = TheCall->getNumArgs(); 7762 for (unsigned i = 0; i < NumArgs; ++i) { 7763 Expr *CurrA = TheCall->getArg(i); 7764 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 7765 continue; 7766 7767 bool IsSwapped = ((i > 0) && 7768 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 7769 IsSwapped |= ((i < (NumArgs - 1)) && 7770 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 7771 if (IsSwapped) { 7772 // Warn on this floating-point to bool conversion. 7773 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 7774 CurrA->getType(), CC, 7775 diag::warn_impcast_floating_point_to_bool); 7776 } 7777 } 7778 } 7779 7780 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) { 7781 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 7782 E->getExprLoc())) 7783 return; 7784 7785 // Don't warn on functions which have return type nullptr_t. 7786 if (isa<CallExpr>(E)) 7787 return; 7788 7789 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 7790 const Expr::NullPointerConstantKind NullKind = 7791 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 7792 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 7793 return; 7794 7795 // Return if target type is a safe conversion. 7796 if (T->isAnyPointerType() || T->isBlockPointerType() || 7797 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 7798 return; 7799 7800 SourceLocation Loc = E->getSourceRange().getBegin(); 7801 7802 // Venture through the macro stacks to get to the source of macro arguments. 7803 // The new location is a better location than the complete location that was 7804 // passed in. 7805 while (S.SourceMgr.isMacroArgExpansion(Loc)) 7806 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc); 7807 7808 while (S.SourceMgr.isMacroArgExpansion(CC)) 7809 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC); 7810 7811 // __null is usually wrapped in a macro. Go up a macro if that is the case. 7812 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 7813 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 7814 Loc, S.SourceMgr, S.getLangOpts()); 7815 if (MacroName == "NULL") 7816 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first; 7817 } 7818 7819 // Only warn if the null and context location are in the same macro expansion. 7820 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 7821 return; 7822 7823 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 7824 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC) 7825 << FixItHint::CreateReplacement(Loc, 7826 S.getFixItZeroLiteralForType(T, Loc)); 7827 } 7828 7829 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 7830 ObjCArrayLiteral *ArrayLiteral); 7831 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 7832 ObjCDictionaryLiteral *DictionaryLiteral); 7833 7834 /// Check a single element within a collection literal against the 7835 /// target element type. 7836 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType, 7837 Expr *Element, unsigned ElementKind) { 7838 // Skip a bitcast to 'id' or qualified 'id'. 7839 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 7840 if (ICE->getCastKind() == CK_BitCast && 7841 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 7842 Element = ICE->getSubExpr(); 7843 } 7844 7845 QualType ElementType = Element->getType(); 7846 ExprResult ElementResult(Element); 7847 if (ElementType->getAs<ObjCObjectPointerType>() && 7848 S.CheckSingleAssignmentConstraints(TargetElementType, 7849 ElementResult, 7850 false, false) 7851 != Sema::Compatible) { 7852 S.Diag(Element->getLocStart(), 7853 diag::warn_objc_collection_literal_element) 7854 << ElementType << ElementKind << TargetElementType 7855 << Element->getSourceRange(); 7856 } 7857 7858 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 7859 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 7860 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 7861 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 7862 } 7863 7864 /// Check an Objective-C array literal being converted to the given 7865 /// target type. 7866 void checkObjCArrayLiteral(Sema &S, QualType TargetType, 7867 ObjCArrayLiteral *ArrayLiteral) { 7868 if (!S.NSArrayDecl) 7869 return; 7870 7871 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 7872 if (!TargetObjCPtr) 7873 return; 7874 7875 if (TargetObjCPtr->isUnspecialized() || 7876 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 7877 != S.NSArrayDecl->getCanonicalDecl()) 7878 return; 7879 7880 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 7881 if (TypeArgs.size() != 1) 7882 return; 7883 7884 QualType TargetElementType = TypeArgs[0]; 7885 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 7886 checkObjCCollectionLiteralElement(S, TargetElementType, 7887 ArrayLiteral->getElement(I), 7888 0); 7889 } 7890 } 7891 7892 /// Check an Objective-C dictionary literal being converted to the given 7893 /// target type. 7894 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 7895 ObjCDictionaryLiteral *DictionaryLiteral) { 7896 if (!S.NSDictionaryDecl) 7897 return; 7898 7899 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 7900 if (!TargetObjCPtr) 7901 return; 7902 7903 if (TargetObjCPtr->isUnspecialized() || 7904 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 7905 != S.NSDictionaryDecl->getCanonicalDecl()) 7906 return; 7907 7908 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 7909 if (TypeArgs.size() != 2) 7910 return; 7911 7912 QualType TargetKeyType = TypeArgs[0]; 7913 QualType TargetObjectType = TypeArgs[1]; 7914 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 7915 auto Element = DictionaryLiteral->getKeyValueElement(I); 7916 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 7917 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 7918 } 7919 } 7920 7921 // Helper function to filter out cases for constant width constant conversion. 7922 // Don't warn on char array initialization or for non-decimal values. 7923 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 7924 SourceLocation CC) { 7925 // If initializing from a constant, and the constant starts with '0', 7926 // then it is a binary, octal, or hexadecimal. Allow these constants 7927 // to fill all the bits, even if there is a sign change. 7928 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 7929 const char FirstLiteralCharacter = 7930 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 7931 if (FirstLiteralCharacter == '0') 7932 return false; 7933 } 7934 7935 // If the CC location points to a '{', and the type is char, then assume 7936 // assume it is an array initialization. 7937 if (CC.isValid() && T->isCharType()) { 7938 const char FirstContextCharacter = 7939 S.getSourceManager().getCharacterData(CC)[0]; 7940 if (FirstContextCharacter == '{') 7941 return false; 7942 } 7943 7944 return true; 7945 } 7946 7947 void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 7948 SourceLocation CC, bool *ICContext = nullptr) { 7949 if (E->isTypeDependent() || E->isValueDependent()) return; 7950 7951 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 7952 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 7953 if (Source == Target) return; 7954 if (Target->isDependentType()) return; 7955 7956 // If the conversion context location is invalid don't complain. We also 7957 // don't want to emit a warning if the issue occurs from the expansion of 7958 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 7959 // delay this check as long as possible. Once we detect we are in that 7960 // scenario, we just return. 7961 if (CC.isInvalid()) 7962 return; 7963 7964 // Diagnose implicit casts to bool. 7965 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 7966 if (isa<StringLiteral>(E)) 7967 // Warn on string literal to bool. Checks for string literals in logical 7968 // and expressions, for instance, assert(0 && "error here"), are 7969 // prevented by a check in AnalyzeImplicitConversions(). 7970 return DiagnoseImpCast(S, E, T, CC, 7971 diag::warn_impcast_string_literal_to_bool); 7972 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 7973 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 7974 // This covers the literal expressions that evaluate to Objective-C 7975 // objects. 7976 return DiagnoseImpCast(S, E, T, CC, 7977 diag::warn_impcast_objective_c_literal_to_bool); 7978 } 7979 if (Source->isPointerType() || Source->canDecayToPointerType()) { 7980 // Warn on pointer to bool conversion that is always true. 7981 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 7982 SourceRange(CC)); 7983 } 7984 } 7985 7986 // Check implicit casts from Objective-C collection literals to specialized 7987 // collection types, e.g., NSArray<NSString *> *. 7988 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 7989 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 7990 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 7991 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 7992 7993 // Strip vector types. 7994 if (isa<VectorType>(Source)) { 7995 if (!isa<VectorType>(Target)) { 7996 if (S.SourceMgr.isInSystemMacro(CC)) 7997 return; 7998 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 7999 } 8000 8001 // If the vector cast is cast between two vectors of the same size, it is 8002 // a bitcast, not a conversion. 8003 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 8004 return; 8005 8006 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 8007 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 8008 } 8009 if (auto VecTy = dyn_cast<VectorType>(Target)) 8010 Target = VecTy->getElementType().getTypePtr(); 8011 8012 // Strip complex types. 8013 if (isa<ComplexType>(Source)) { 8014 if (!isa<ComplexType>(Target)) { 8015 if (S.SourceMgr.isInSystemMacro(CC)) 8016 return; 8017 8018 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar); 8019 } 8020 8021 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 8022 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 8023 } 8024 8025 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 8026 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 8027 8028 // If the source is floating point... 8029 if (SourceBT && SourceBT->isFloatingPoint()) { 8030 // ...and the target is floating point... 8031 if (TargetBT && TargetBT->isFloatingPoint()) { 8032 // ...then warn if we're dropping FP rank. 8033 8034 // Builtin FP kinds are ordered by increasing FP rank. 8035 if (SourceBT->getKind() > TargetBT->getKind()) { 8036 // Don't warn about float constants that are precisely 8037 // representable in the target type. 8038 Expr::EvalResult result; 8039 if (E->EvaluateAsRValue(result, S.Context)) { 8040 // Value might be a float, a float vector, or a float complex. 8041 if (IsSameFloatAfterCast(result.Val, 8042 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 8043 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 8044 return; 8045 } 8046 8047 if (S.SourceMgr.isInSystemMacro(CC)) 8048 return; 8049 8050 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 8051 } 8052 // ... or possibly if we're increasing rank, too 8053 else if (TargetBT->getKind() > SourceBT->getKind()) { 8054 if (S.SourceMgr.isInSystemMacro(CC)) 8055 return; 8056 8057 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 8058 } 8059 return; 8060 } 8061 8062 // If the target is integral, always warn. 8063 if (TargetBT && TargetBT->isInteger()) { 8064 if (S.SourceMgr.isInSystemMacro(CC)) 8065 return; 8066 8067 DiagnoseFloatingImpCast(S, E, T, CC); 8068 } 8069 8070 // Detect the case where a call result is converted from floating-point to 8071 // to bool, and the final argument to the call is converted from bool, to 8072 // discover this typo: 8073 // 8074 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 8075 // 8076 // FIXME: This is an incredibly special case; is there some more general 8077 // way to detect this class of misplaced-parentheses bug? 8078 if (Target->isBooleanType() && isa<CallExpr>(E)) { 8079 // Check last argument of function call to see if it is an 8080 // implicit cast from a type matching the type the result 8081 // is being cast to. 8082 CallExpr *CEx = cast<CallExpr>(E); 8083 if (unsigned NumArgs = CEx->getNumArgs()) { 8084 Expr *LastA = CEx->getArg(NumArgs - 1); 8085 Expr *InnerE = LastA->IgnoreParenImpCasts(); 8086 if (isa<ImplicitCastExpr>(LastA) && 8087 InnerE->getType()->isBooleanType()) { 8088 // Warn on this floating-point to bool conversion 8089 DiagnoseImpCast(S, E, T, CC, 8090 diag::warn_impcast_floating_point_to_bool); 8091 } 8092 } 8093 } 8094 return; 8095 } 8096 8097 DiagnoseNullConversion(S, E, T, CC); 8098 8099 if (!Source->isIntegerType() || !Target->isIntegerType()) 8100 return; 8101 8102 // TODO: remove this early return once the false positives for constant->bool 8103 // in templates, macros, etc, are reduced or removed. 8104 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 8105 return; 8106 8107 IntRange SourceRange = GetExprRange(S.Context, E); 8108 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 8109 8110 if (SourceRange.Width > TargetRange.Width) { 8111 // If the source is a constant, use a default-on diagnostic. 8112 // TODO: this should happen for bitfield stores, too. 8113 llvm::APSInt Value(32); 8114 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 8115 if (S.SourceMgr.isInSystemMacro(CC)) 8116 return; 8117 8118 std::string PrettySourceValue = Value.toString(10); 8119 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 8120 8121 S.DiagRuntimeBehavior(E->getExprLoc(), E, 8122 S.PDiag(diag::warn_impcast_integer_precision_constant) 8123 << PrettySourceValue << PrettyTargetValue 8124 << E->getType() << T << E->getSourceRange() 8125 << clang::SourceRange(CC)); 8126 return; 8127 } 8128 8129 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 8130 if (S.SourceMgr.isInSystemMacro(CC)) 8131 return; 8132 8133 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 8134 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 8135 /* pruneControlFlow */ true); 8136 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 8137 } 8138 8139 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 8140 SourceRange.NonNegative && Source->isSignedIntegerType()) { 8141 // Warn when doing a signed to signed conversion, warn if the positive 8142 // source value is exactly the width of the target type, which will 8143 // cause a negative value to be stored. 8144 8145 llvm::APSInt Value; 8146 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 8147 !S.SourceMgr.isInSystemMacro(CC)) { 8148 if (isSameWidthConstantConversion(S, E, T, CC)) { 8149 std::string PrettySourceValue = Value.toString(10); 8150 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 8151 8152 S.DiagRuntimeBehavior( 8153 E->getExprLoc(), E, 8154 S.PDiag(diag::warn_impcast_integer_precision_constant) 8155 << PrettySourceValue << PrettyTargetValue << E->getType() << T 8156 << E->getSourceRange() << clang::SourceRange(CC)); 8157 return; 8158 } 8159 } 8160 8161 // Fall through for non-constants to give a sign conversion warning. 8162 } 8163 8164 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 8165 (!TargetRange.NonNegative && SourceRange.NonNegative && 8166 SourceRange.Width == TargetRange.Width)) { 8167 if (S.SourceMgr.isInSystemMacro(CC)) 8168 return; 8169 8170 unsigned DiagID = diag::warn_impcast_integer_sign; 8171 8172 // Traditionally, gcc has warned about this under -Wsign-compare. 8173 // We also want to warn about it in -Wconversion. 8174 // So if -Wconversion is off, use a completely identical diagnostic 8175 // in the sign-compare group. 8176 // The conditional-checking code will 8177 if (ICContext) { 8178 DiagID = diag::warn_impcast_integer_sign_conditional; 8179 *ICContext = true; 8180 } 8181 8182 return DiagnoseImpCast(S, E, T, CC, DiagID); 8183 } 8184 8185 // Diagnose conversions between different enumeration types. 8186 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 8187 // type, to give us better diagnostics. 8188 QualType SourceType = E->getType(); 8189 if (!S.getLangOpts().CPlusPlus) { 8190 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8191 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 8192 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 8193 SourceType = S.Context.getTypeDeclType(Enum); 8194 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 8195 } 8196 } 8197 8198 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 8199 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 8200 if (SourceEnum->getDecl()->hasNameForLinkage() && 8201 TargetEnum->getDecl()->hasNameForLinkage() && 8202 SourceEnum != TargetEnum) { 8203 if (S.SourceMgr.isInSystemMacro(CC)) 8204 return; 8205 8206 return DiagnoseImpCast(S, E, SourceType, T, CC, 8207 diag::warn_impcast_different_enum_types); 8208 } 8209 } 8210 8211 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 8212 SourceLocation CC, QualType T); 8213 8214 void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 8215 SourceLocation CC, bool &ICContext) { 8216 E = E->IgnoreParenImpCasts(); 8217 8218 if (isa<ConditionalOperator>(E)) 8219 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 8220 8221 AnalyzeImplicitConversions(S, E, CC); 8222 if (E->getType() != T) 8223 return CheckImplicitConversion(S, E, T, CC, &ICContext); 8224 } 8225 8226 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 8227 SourceLocation CC, QualType T) { 8228 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 8229 8230 bool Suspicious = false; 8231 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 8232 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 8233 8234 // If -Wconversion would have warned about either of the candidates 8235 // for a signedness conversion to the context type... 8236 if (!Suspicious) return; 8237 8238 // ...but it's currently ignored... 8239 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 8240 return; 8241 8242 // ...then check whether it would have warned about either of the 8243 // candidates for a signedness conversion to the condition type. 8244 if (E->getType() == T) return; 8245 8246 Suspicious = false; 8247 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 8248 E->getType(), CC, &Suspicious); 8249 if (!Suspicious) 8250 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 8251 E->getType(), CC, &Suspicious); 8252 } 8253 8254 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 8255 /// Input argument E is a logical expression. 8256 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 8257 if (S.getLangOpts().Bool) 8258 return; 8259 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 8260 } 8261 8262 /// AnalyzeImplicitConversions - Find and report any interesting 8263 /// implicit conversions in the given expression. There are a couple 8264 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 8265 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) { 8266 QualType T = OrigE->getType(); 8267 Expr *E = OrigE->IgnoreParenImpCasts(); 8268 8269 if (E->isTypeDependent() || E->isValueDependent()) 8270 return; 8271 8272 // For conditional operators, we analyze the arguments as if they 8273 // were being fed directly into the output. 8274 if (isa<ConditionalOperator>(E)) { 8275 ConditionalOperator *CO = cast<ConditionalOperator>(E); 8276 CheckConditionalOperator(S, CO, CC, T); 8277 return; 8278 } 8279 8280 // Check implicit argument conversions for function calls. 8281 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 8282 CheckImplicitArgumentConversions(S, Call, CC); 8283 8284 // Go ahead and check any implicit conversions we might have skipped. 8285 // The non-canonical typecheck is just an optimization; 8286 // CheckImplicitConversion will filter out dead implicit conversions. 8287 if (E->getType() != T) 8288 CheckImplicitConversion(S, E, T, CC); 8289 8290 // Now continue drilling into this expression. 8291 8292 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 8293 // The bound subexpressions in a PseudoObjectExpr are not reachable 8294 // as transitive children. 8295 // FIXME: Use a more uniform representation for this. 8296 for (auto *SE : POE->semantics()) 8297 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 8298 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 8299 } 8300 8301 // Skip past explicit casts. 8302 if (isa<ExplicitCastExpr>(E)) { 8303 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 8304 return AnalyzeImplicitConversions(S, E, CC); 8305 } 8306 8307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8308 // Do a somewhat different check with comparison operators. 8309 if (BO->isComparisonOp()) 8310 return AnalyzeComparison(S, BO); 8311 8312 // And with simple assignments. 8313 if (BO->getOpcode() == BO_Assign) 8314 return AnalyzeAssignment(S, BO); 8315 } 8316 8317 // These break the otherwise-useful invariant below. Fortunately, 8318 // we don't really need to recurse into them, because any internal 8319 // expressions should have been analyzed already when they were 8320 // built into statements. 8321 if (isa<StmtExpr>(E)) return; 8322 8323 // Don't descend into unevaluated contexts. 8324 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 8325 8326 // Now just recurse over the expression's children. 8327 CC = E->getExprLoc(); 8328 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 8329 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 8330 for (Stmt *SubStmt : E->children()) { 8331 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 8332 if (!ChildExpr) 8333 continue; 8334 8335 if (IsLogicalAndOperator && 8336 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 8337 // Ignore checking string literals that are in logical and operators. 8338 // This is a common pattern for asserts. 8339 continue; 8340 AnalyzeImplicitConversions(S, ChildExpr, CC); 8341 } 8342 8343 if (BO && BO->isLogicalOp()) { 8344 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 8345 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 8346 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 8347 8348 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 8349 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 8350 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 8351 } 8352 8353 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 8354 if (U->getOpcode() == UO_LNot) 8355 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 8356 } 8357 8358 } // end anonymous namespace 8359 8360 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 8361 // Returns true when emitting a warning about taking the address of a reference. 8362 static bool CheckForReference(Sema &SemaRef, const Expr *E, 8363 const PartialDiagnostic &PD) { 8364 E = E->IgnoreParenImpCasts(); 8365 8366 const FunctionDecl *FD = nullptr; 8367 8368 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8369 if (!DRE->getDecl()->getType()->isReferenceType()) 8370 return false; 8371 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 8372 if (!M->getMemberDecl()->getType()->isReferenceType()) 8373 return false; 8374 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 8375 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 8376 return false; 8377 FD = Call->getDirectCallee(); 8378 } else { 8379 return false; 8380 } 8381 8382 SemaRef.Diag(E->getExprLoc(), PD); 8383 8384 // If possible, point to location of function. 8385 if (FD) { 8386 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 8387 } 8388 8389 return true; 8390 } 8391 8392 // Returns true if the SourceLocation is expanded from any macro body. 8393 // Returns false if the SourceLocation is invalid, is from not in a macro 8394 // expansion, or is from expanded from a top-level macro argument. 8395 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 8396 if (Loc.isInvalid()) 8397 return false; 8398 8399 while (Loc.isMacroID()) { 8400 if (SM.isMacroBodyExpansion(Loc)) 8401 return true; 8402 Loc = SM.getImmediateMacroCallerLoc(Loc); 8403 } 8404 8405 return false; 8406 } 8407 8408 /// \brief Diagnose pointers that are always non-null. 8409 /// \param E the expression containing the pointer 8410 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 8411 /// compared to a null pointer 8412 /// \param IsEqual True when the comparison is equal to a null pointer 8413 /// \param Range Extra SourceRange to highlight in the diagnostic 8414 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 8415 Expr::NullPointerConstantKind NullKind, 8416 bool IsEqual, SourceRange Range) { 8417 if (!E) 8418 return; 8419 8420 // Don't warn inside macros. 8421 if (E->getExprLoc().isMacroID()) { 8422 const SourceManager &SM = getSourceManager(); 8423 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 8424 IsInAnyMacroBody(SM, Range.getBegin())) 8425 return; 8426 } 8427 E = E->IgnoreImpCasts(); 8428 8429 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 8430 8431 if (isa<CXXThisExpr>(E)) { 8432 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 8433 : diag::warn_this_bool_conversion; 8434 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 8435 return; 8436 } 8437 8438 bool IsAddressOf = false; 8439 8440 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 8441 if (UO->getOpcode() != UO_AddrOf) 8442 return; 8443 IsAddressOf = true; 8444 E = UO->getSubExpr(); 8445 } 8446 8447 if (IsAddressOf) { 8448 unsigned DiagID = IsCompare 8449 ? diag::warn_address_of_reference_null_compare 8450 : diag::warn_address_of_reference_bool_conversion; 8451 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 8452 << IsEqual; 8453 if (CheckForReference(*this, E, PD)) { 8454 return; 8455 } 8456 } 8457 8458 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 8459 bool IsParam = isa<NonNullAttr>(NonnullAttr); 8460 std::string Str; 8461 llvm::raw_string_ostream S(Str); 8462 E->printPretty(S, nullptr, getPrintingPolicy()); 8463 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 8464 : diag::warn_cast_nonnull_to_bool; 8465 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 8466 << E->getSourceRange() << Range << IsEqual; 8467 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 8468 }; 8469 8470 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 8471 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 8472 if (auto *Callee = Call->getDirectCallee()) { 8473 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 8474 ComplainAboutNonnullParamOrCall(A); 8475 return; 8476 } 8477 } 8478 } 8479 8480 // Expect to find a single Decl. Skip anything more complicated. 8481 ValueDecl *D = nullptr; 8482 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 8483 D = R->getDecl(); 8484 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 8485 D = M->getMemberDecl(); 8486 } 8487 8488 // Weak Decls can be null. 8489 if (!D || D->isWeak()) 8490 return; 8491 8492 // Check for parameter decl with nonnull attribute 8493 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 8494 if (getCurFunction() && 8495 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 8496 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 8497 ComplainAboutNonnullParamOrCall(A); 8498 return; 8499 } 8500 8501 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 8502 auto ParamIter = llvm::find(FD->parameters(), PV); 8503 assert(ParamIter != FD->param_end()); 8504 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 8505 8506 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 8507 if (!NonNull->args_size()) { 8508 ComplainAboutNonnullParamOrCall(NonNull); 8509 return; 8510 } 8511 8512 for (unsigned ArgNo : NonNull->args()) { 8513 if (ArgNo == ParamNo) { 8514 ComplainAboutNonnullParamOrCall(NonNull); 8515 return; 8516 } 8517 } 8518 } 8519 } 8520 } 8521 } 8522 8523 QualType T = D->getType(); 8524 const bool IsArray = T->isArrayType(); 8525 const bool IsFunction = T->isFunctionType(); 8526 8527 // Address of function is used to silence the function warning. 8528 if (IsAddressOf && IsFunction) { 8529 return; 8530 } 8531 8532 // Found nothing. 8533 if (!IsAddressOf && !IsFunction && !IsArray) 8534 return; 8535 8536 // Pretty print the expression for the diagnostic. 8537 std::string Str; 8538 llvm::raw_string_ostream S(Str); 8539 E->printPretty(S, nullptr, getPrintingPolicy()); 8540 8541 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 8542 : diag::warn_impcast_pointer_to_bool; 8543 enum { 8544 AddressOf, 8545 FunctionPointer, 8546 ArrayPointer 8547 } DiagType; 8548 if (IsAddressOf) 8549 DiagType = AddressOf; 8550 else if (IsFunction) 8551 DiagType = FunctionPointer; 8552 else if (IsArray) 8553 DiagType = ArrayPointer; 8554 else 8555 llvm_unreachable("Could not determine diagnostic."); 8556 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 8557 << Range << IsEqual; 8558 8559 if (!IsFunction) 8560 return; 8561 8562 // Suggest '&' to silence the function warning. 8563 Diag(E->getExprLoc(), diag::note_function_warning_silence) 8564 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 8565 8566 // Check to see if '()' fixit should be emitted. 8567 QualType ReturnType; 8568 UnresolvedSet<4> NonTemplateOverloads; 8569 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 8570 if (ReturnType.isNull()) 8571 return; 8572 8573 if (IsCompare) { 8574 // There are two cases here. If there is null constant, the only suggest 8575 // for a pointer return type. If the null is 0, then suggest if the return 8576 // type is a pointer or an integer type. 8577 if (!ReturnType->isPointerType()) { 8578 if (NullKind == Expr::NPCK_ZeroExpression || 8579 NullKind == Expr::NPCK_ZeroLiteral) { 8580 if (!ReturnType->isIntegerType()) 8581 return; 8582 } else { 8583 return; 8584 } 8585 } 8586 } else { // !IsCompare 8587 // For function to bool, only suggest if the function pointer has bool 8588 // return type. 8589 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 8590 return; 8591 } 8592 Diag(E->getExprLoc(), diag::note_function_to_function_call) 8593 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 8594 } 8595 8596 /// Diagnoses "dangerous" implicit conversions within the given 8597 /// expression (which is a full expression). Implements -Wconversion 8598 /// and -Wsign-compare. 8599 /// 8600 /// \param CC the "context" location of the implicit conversion, i.e. 8601 /// the most location of the syntactic entity requiring the implicit 8602 /// conversion 8603 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 8604 // Don't diagnose in unevaluated contexts. 8605 if (isUnevaluatedContext()) 8606 return; 8607 8608 // Don't diagnose for value- or type-dependent expressions. 8609 if (E->isTypeDependent() || E->isValueDependent()) 8610 return; 8611 8612 // Check for array bounds violations in cases where the check isn't triggered 8613 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 8614 // ArraySubscriptExpr is on the RHS of a variable initialization. 8615 CheckArrayAccess(E); 8616 8617 // This is not the right CC for (e.g.) a variable initialization. 8618 AnalyzeImplicitConversions(*this, E, CC); 8619 } 8620 8621 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 8622 /// Input argument E is a logical expression. 8623 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 8624 ::CheckBoolLikeConversion(*this, E, CC); 8625 } 8626 8627 /// Diagnose when expression is an integer constant expression and its evaluation 8628 /// results in integer overflow 8629 void Sema::CheckForIntOverflow (Expr *E) { 8630 // Use a work list to deal with nested struct initializers. 8631 SmallVector<Expr *, 2> Exprs(1, E); 8632 8633 do { 8634 Expr *E = Exprs.pop_back_val(); 8635 8636 if (isa<BinaryOperator>(E->IgnoreParenCasts())) { 8637 E->IgnoreParenCasts()->EvaluateForOverflow(Context); 8638 continue; 8639 } 8640 8641 if (auto InitList = dyn_cast<InitListExpr>(E)) 8642 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 8643 } while (!Exprs.empty()); 8644 } 8645 8646 namespace { 8647 /// \brief Visitor for expressions which looks for unsequenced operations on the 8648 /// same object. 8649 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 8650 typedef EvaluatedExprVisitor<SequenceChecker> Base; 8651 8652 /// \brief A tree of sequenced regions within an expression. Two regions are 8653 /// unsequenced if one is an ancestor or a descendent of the other. When we 8654 /// finish processing an expression with sequencing, such as a comma 8655 /// expression, we fold its tree nodes into its parent, since they are 8656 /// unsequenced with respect to nodes we will visit later. 8657 class SequenceTree { 8658 struct Value { 8659 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 8660 unsigned Parent : 31; 8661 bool Merged : 1; 8662 }; 8663 SmallVector<Value, 8> Values; 8664 8665 public: 8666 /// \brief A region within an expression which may be sequenced with respect 8667 /// to some other region. 8668 class Seq { 8669 explicit Seq(unsigned N) : Index(N) {} 8670 unsigned Index; 8671 friend class SequenceTree; 8672 public: 8673 Seq() : Index(0) {} 8674 }; 8675 8676 SequenceTree() { Values.push_back(Value(0)); } 8677 Seq root() const { return Seq(0); } 8678 8679 /// \brief Create a new sequence of operations, which is an unsequenced 8680 /// subset of \p Parent. This sequence of operations is sequenced with 8681 /// respect to other children of \p Parent. 8682 Seq allocate(Seq Parent) { 8683 Values.push_back(Value(Parent.Index)); 8684 return Seq(Values.size() - 1); 8685 } 8686 8687 /// \brief Merge a sequence of operations into its parent. 8688 void merge(Seq S) { 8689 Values[S.Index].Merged = true; 8690 } 8691 8692 /// \brief Determine whether two operations are unsequenced. This operation 8693 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 8694 /// should have been merged into its parent as appropriate. 8695 bool isUnsequenced(Seq Cur, Seq Old) { 8696 unsigned C = representative(Cur.Index); 8697 unsigned Target = representative(Old.Index); 8698 while (C >= Target) { 8699 if (C == Target) 8700 return true; 8701 C = Values[C].Parent; 8702 } 8703 return false; 8704 } 8705 8706 private: 8707 /// \brief Pick a representative for a sequence. 8708 unsigned representative(unsigned K) { 8709 if (Values[K].Merged) 8710 // Perform path compression as we go. 8711 return Values[K].Parent = representative(Values[K].Parent); 8712 return K; 8713 } 8714 }; 8715 8716 /// An object for which we can track unsequenced uses. 8717 typedef NamedDecl *Object; 8718 8719 /// Different flavors of object usage which we track. We only track the 8720 /// least-sequenced usage of each kind. 8721 enum UsageKind { 8722 /// A read of an object. Multiple unsequenced reads are OK. 8723 UK_Use, 8724 /// A modification of an object which is sequenced before the value 8725 /// computation of the expression, such as ++n in C++. 8726 UK_ModAsValue, 8727 /// A modification of an object which is not sequenced before the value 8728 /// computation of the expression, such as n++. 8729 UK_ModAsSideEffect, 8730 8731 UK_Count = UK_ModAsSideEffect + 1 8732 }; 8733 8734 struct Usage { 8735 Usage() : Use(nullptr), Seq() {} 8736 Expr *Use; 8737 SequenceTree::Seq Seq; 8738 }; 8739 8740 struct UsageInfo { 8741 UsageInfo() : Diagnosed(false) {} 8742 Usage Uses[UK_Count]; 8743 /// Have we issued a diagnostic for this variable already? 8744 bool Diagnosed; 8745 }; 8746 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap; 8747 8748 Sema &SemaRef; 8749 /// Sequenced regions within the expression. 8750 SequenceTree Tree; 8751 /// Declaration modifications and references which we have seen. 8752 UsageInfoMap UsageMap; 8753 /// The region we are currently within. 8754 SequenceTree::Seq Region; 8755 /// Filled in with declarations which were modified as a side-effect 8756 /// (that is, post-increment operations). 8757 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect; 8758 /// Expressions to check later. We defer checking these to reduce 8759 /// stack usage. 8760 SmallVectorImpl<Expr *> &WorkList; 8761 8762 /// RAII object wrapping the visitation of a sequenced subexpression of an 8763 /// expression. At the end of this process, the side-effects of the evaluation 8764 /// become sequenced with respect to the value computation of the result, so 8765 /// we downgrade any UK_ModAsSideEffect within the evaluation to 8766 /// UK_ModAsValue. 8767 struct SequencedSubexpression { 8768 SequencedSubexpression(SequenceChecker &Self) 8769 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 8770 Self.ModAsSideEffect = &ModAsSideEffect; 8771 } 8772 ~SequencedSubexpression() { 8773 for (auto &M : llvm::reverse(ModAsSideEffect)) { 8774 UsageInfo &U = Self.UsageMap[M.first]; 8775 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 8776 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 8777 SideEffectUsage = M.second; 8778 } 8779 Self.ModAsSideEffect = OldModAsSideEffect; 8780 } 8781 8782 SequenceChecker &Self; 8783 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 8784 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect; 8785 }; 8786 8787 /// RAII object wrapping the visitation of a subexpression which we might 8788 /// choose to evaluate as a constant. If any subexpression is evaluated and 8789 /// found to be non-constant, this allows us to suppress the evaluation of 8790 /// the outer expression. 8791 class EvaluationTracker { 8792 public: 8793 EvaluationTracker(SequenceChecker &Self) 8794 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) { 8795 Self.EvalTracker = this; 8796 } 8797 ~EvaluationTracker() { 8798 Self.EvalTracker = Prev; 8799 if (Prev) 8800 Prev->EvalOK &= EvalOK; 8801 } 8802 8803 bool evaluate(const Expr *E, bool &Result) { 8804 if (!EvalOK || E->isValueDependent()) 8805 return false; 8806 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 8807 return EvalOK; 8808 } 8809 8810 private: 8811 SequenceChecker &Self; 8812 EvaluationTracker *Prev; 8813 bool EvalOK; 8814 } *EvalTracker; 8815 8816 /// \brief Find the object which is produced by the specified expression, 8817 /// if any. 8818 Object getObject(Expr *E, bool Mod) const { 8819 E = E->IgnoreParenCasts(); 8820 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 8821 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 8822 return getObject(UO->getSubExpr(), Mod); 8823 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8824 if (BO->getOpcode() == BO_Comma) 8825 return getObject(BO->getRHS(), Mod); 8826 if (Mod && BO->isAssignmentOp()) 8827 return getObject(BO->getLHS(), Mod); 8828 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 8829 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 8830 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 8831 return ME->getMemberDecl(); 8832 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 8833 // FIXME: If this is a reference, map through to its value. 8834 return DRE->getDecl(); 8835 return nullptr; 8836 } 8837 8838 /// \brief Note that an object was modified or used by an expression. 8839 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 8840 Usage &U = UI.Uses[UK]; 8841 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 8842 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 8843 ModAsSideEffect->push_back(std::make_pair(O, U)); 8844 U.Use = Ref; 8845 U.Seq = Region; 8846 } 8847 } 8848 /// \brief Check whether a modification or use conflicts with a prior usage. 8849 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 8850 bool IsModMod) { 8851 if (UI.Diagnosed) 8852 return; 8853 8854 const Usage &U = UI.Uses[OtherKind]; 8855 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 8856 return; 8857 8858 Expr *Mod = U.Use; 8859 Expr *ModOrUse = Ref; 8860 if (OtherKind == UK_Use) 8861 std::swap(Mod, ModOrUse); 8862 8863 SemaRef.Diag(Mod->getExprLoc(), 8864 IsModMod ? diag::warn_unsequenced_mod_mod 8865 : diag::warn_unsequenced_mod_use) 8866 << O << SourceRange(ModOrUse->getExprLoc()); 8867 UI.Diagnosed = true; 8868 } 8869 8870 void notePreUse(Object O, Expr *Use) { 8871 UsageInfo &U = UsageMap[O]; 8872 // Uses conflict with other modifications. 8873 checkUsage(O, U, Use, UK_ModAsValue, false); 8874 } 8875 void notePostUse(Object O, Expr *Use) { 8876 UsageInfo &U = UsageMap[O]; 8877 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 8878 addUsage(U, O, Use, UK_Use); 8879 } 8880 8881 void notePreMod(Object O, Expr *Mod) { 8882 UsageInfo &U = UsageMap[O]; 8883 // Modifications conflict with other modifications and with uses. 8884 checkUsage(O, U, Mod, UK_ModAsValue, true); 8885 checkUsage(O, U, Mod, UK_Use, false); 8886 } 8887 void notePostMod(Object O, Expr *Use, UsageKind UK) { 8888 UsageInfo &U = UsageMap[O]; 8889 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 8890 addUsage(U, O, Use, UK); 8891 } 8892 8893 public: 8894 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 8895 : Base(S.Context), SemaRef(S), Region(Tree.root()), 8896 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) { 8897 Visit(E); 8898 } 8899 8900 void VisitStmt(Stmt *S) { 8901 // Skip all statements which aren't expressions for now. 8902 } 8903 8904 void VisitExpr(Expr *E) { 8905 // By default, just recurse to evaluated subexpressions. 8906 Base::VisitStmt(E); 8907 } 8908 8909 void VisitCastExpr(CastExpr *E) { 8910 Object O = Object(); 8911 if (E->getCastKind() == CK_LValueToRValue) 8912 O = getObject(E->getSubExpr(), false); 8913 8914 if (O) 8915 notePreUse(O, E); 8916 VisitExpr(E); 8917 if (O) 8918 notePostUse(O, E); 8919 } 8920 8921 void VisitBinComma(BinaryOperator *BO) { 8922 // C++11 [expr.comma]p1: 8923 // Every value computation and side effect associated with the left 8924 // expression is sequenced before every value computation and side 8925 // effect associated with the right expression. 8926 SequenceTree::Seq LHS = Tree.allocate(Region); 8927 SequenceTree::Seq RHS = Tree.allocate(Region); 8928 SequenceTree::Seq OldRegion = Region; 8929 8930 { 8931 SequencedSubexpression SeqLHS(*this); 8932 Region = LHS; 8933 Visit(BO->getLHS()); 8934 } 8935 8936 Region = RHS; 8937 Visit(BO->getRHS()); 8938 8939 Region = OldRegion; 8940 8941 // Forget that LHS and RHS are sequenced. They are both unsequenced 8942 // with respect to other stuff. 8943 Tree.merge(LHS); 8944 Tree.merge(RHS); 8945 } 8946 8947 void VisitBinAssign(BinaryOperator *BO) { 8948 // The modification is sequenced after the value computation of the LHS 8949 // and RHS, so check it before inspecting the operands and update the 8950 // map afterwards. 8951 Object O = getObject(BO->getLHS(), true); 8952 if (!O) 8953 return VisitExpr(BO); 8954 8955 notePreMod(O, BO); 8956 8957 // C++11 [expr.ass]p7: 8958 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 8959 // only once. 8960 // 8961 // Therefore, for a compound assignment operator, O is considered used 8962 // everywhere except within the evaluation of E1 itself. 8963 if (isa<CompoundAssignOperator>(BO)) 8964 notePreUse(O, BO); 8965 8966 Visit(BO->getLHS()); 8967 8968 if (isa<CompoundAssignOperator>(BO)) 8969 notePostUse(O, BO); 8970 8971 Visit(BO->getRHS()); 8972 8973 // C++11 [expr.ass]p1: 8974 // the assignment is sequenced [...] before the value computation of the 8975 // assignment expression. 8976 // C11 6.5.16/3 has no such rule. 8977 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 8978 : UK_ModAsSideEffect); 8979 } 8980 8981 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 8982 VisitBinAssign(CAO); 8983 } 8984 8985 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 8986 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 8987 void VisitUnaryPreIncDec(UnaryOperator *UO) { 8988 Object O = getObject(UO->getSubExpr(), true); 8989 if (!O) 8990 return VisitExpr(UO); 8991 8992 notePreMod(O, UO); 8993 Visit(UO->getSubExpr()); 8994 // C++11 [expr.pre.incr]p1: 8995 // the expression ++x is equivalent to x+=1 8996 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 8997 : UK_ModAsSideEffect); 8998 } 8999 9000 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9001 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 9002 void VisitUnaryPostIncDec(UnaryOperator *UO) { 9003 Object O = getObject(UO->getSubExpr(), true); 9004 if (!O) 9005 return VisitExpr(UO); 9006 9007 notePreMod(O, UO); 9008 Visit(UO->getSubExpr()); 9009 notePostMod(O, UO, UK_ModAsSideEffect); 9010 } 9011 9012 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 9013 void VisitBinLOr(BinaryOperator *BO) { 9014 // The side-effects of the LHS of an '&&' are sequenced before the 9015 // value computation of the RHS, and hence before the value computation 9016 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 9017 // as if they were unconditionally sequenced. 9018 EvaluationTracker Eval(*this); 9019 { 9020 SequencedSubexpression Sequenced(*this); 9021 Visit(BO->getLHS()); 9022 } 9023 9024 bool Result; 9025 if (Eval.evaluate(BO->getLHS(), Result)) { 9026 if (!Result) 9027 Visit(BO->getRHS()); 9028 } else { 9029 // Check for unsequenced operations in the RHS, treating it as an 9030 // entirely separate evaluation. 9031 // 9032 // FIXME: If there are operations in the RHS which are unsequenced 9033 // with respect to operations outside the RHS, and those operations 9034 // are unconditionally evaluated, diagnose them. 9035 WorkList.push_back(BO->getRHS()); 9036 } 9037 } 9038 void VisitBinLAnd(BinaryOperator *BO) { 9039 EvaluationTracker Eval(*this); 9040 { 9041 SequencedSubexpression Sequenced(*this); 9042 Visit(BO->getLHS()); 9043 } 9044 9045 bool Result; 9046 if (Eval.evaluate(BO->getLHS(), Result)) { 9047 if (Result) 9048 Visit(BO->getRHS()); 9049 } else { 9050 WorkList.push_back(BO->getRHS()); 9051 } 9052 } 9053 9054 // Only visit the condition, unless we can be sure which subexpression will 9055 // be chosen. 9056 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 9057 EvaluationTracker Eval(*this); 9058 { 9059 SequencedSubexpression Sequenced(*this); 9060 Visit(CO->getCond()); 9061 } 9062 9063 bool Result; 9064 if (Eval.evaluate(CO->getCond(), Result)) 9065 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 9066 else { 9067 WorkList.push_back(CO->getTrueExpr()); 9068 WorkList.push_back(CO->getFalseExpr()); 9069 } 9070 } 9071 9072 void VisitCallExpr(CallExpr *CE) { 9073 // C++11 [intro.execution]p15: 9074 // When calling a function [...], every value computation and side effect 9075 // associated with any argument expression, or with the postfix expression 9076 // designating the called function, is sequenced before execution of every 9077 // expression or statement in the body of the function [and thus before 9078 // the value computation of its result]. 9079 SequencedSubexpression Sequenced(*this); 9080 Base::VisitCallExpr(CE); 9081 9082 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 9083 } 9084 9085 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 9086 // This is a call, so all subexpressions are sequenced before the result. 9087 SequencedSubexpression Sequenced(*this); 9088 9089 if (!CCE->isListInitialization()) 9090 return VisitExpr(CCE); 9091 9092 // In C++11, list initializations are sequenced. 9093 SmallVector<SequenceTree::Seq, 32> Elts; 9094 SequenceTree::Seq Parent = Region; 9095 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 9096 E = CCE->arg_end(); 9097 I != E; ++I) { 9098 Region = Tree.allocate(Parent); 9099 Elts.push_back(Region); 9100 Visit(*I); 9101 } 9102 9103 // Forget that the initializers are sequenced. 9104 Region = Parent; 9105 for (unsigned I = 0; I < Elts.size(); ++I) 9106 Tree.merge(Elts[I]); 9107 } 9108 9109 void VisitInitListExpr(InitListExpr *ILE) { 9110 if (!SemaRef.getLangOpts().CPlusPlus11) 9111 return VisitExpr(ILE); 9112 9113 // In C++11, list initializations are sequenced. 9114 SmallVector<SequenceTree::Seq, 32> Elts; 9115 SequenceTree::Seq Parent = Region; 9116 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 9117 Expr *E = ILE->getInit(I); 9118 if (!E) continue; 9119 Region = Tree.allocate(Parent); 9120 Elts.push_back(Region); 9121 Visit(E); 9122 } 9123 9124 // Forget that the initializers are sequenced. 9125 Region = Parent; 9126 for (unsigned I = 0; I < Elts.size(); ++I) 9127 Tree.merge(Elts[I]); 9128 } 9129 }; 9130 } // end anonymous namespace 9131 9132 void Sema::CheckUnsequencedOperations(Expr *E) { 9133 SmallVector<Expr *, 8> WorkList; 9134 WorkList.push_back(E); 9135 while (!WorkList.empty()) { 9136 Expr *Item = WorkList.pop_back_val(); 9137 SequenceChecker(*this, Item, WorkList); 9138 } 9139 } 9140 9141 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 9142 bool IsConstexpr) { 9143 CheckImplicitConversions(E, CheckLoc); 9144 CheckUnsequencedOperations(E); 9145 if (!IsConstexpr && !E->isValueDependent()) 9146 CheckForIntOverflow(E); 9147 } 9148 9149 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 9150 FieldDecl *BitField, 9151 Expr *Init) { 9152 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 9153 } 9154 9155 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 9156 SourceLocation Loc) { 9157 if (!PType->isVariablyModifiedType()) 9158 return; 9159 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 9160 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 9161 return; 9162 } 9163 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 9164 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 9165 return; 9166 } 9167 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 9168 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 9169 return; 9170 } 9171 9172 const ArrayType *AT = S.Context.getAsArrayType(PType); 9173 if (!AT) 9174 return; 9175 9176 if (AT->getSizeModifier() != ArrayType::Star) { 9177 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 9178 return; 9179 } 9180 9181 S.Diag(Loc, diag::err_array_star_in_function_definition); 9182 } 9183 9184 /// CheckParmsForFunctionDef - Check that the parameters of the given 9185 /// function are appropriate for the definition of a function. This 9186 /// takes care of any checks that cannot be performed on the 9187 /// declaration itself, e.g., that the types of each of the function 9188 /// parameters are complete. 9189 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 9190 bool CheckParameterNames) { 9191 bool HasInvalidParm = false; 9192 for (ParmVarDecl *Param : Parameters) { 9193 // C99 6.7.5.3p4: the parameters in a parameter type list in a 9194 // function declarator that is part of a function definition of 9195 // that function shall not have incomplete type. 9196 // 9197 // This is also C++ [dcl.fct]p6. 9198 if (!Param->isInvalidDecl() && 9199 RequireCompleteType(Param->getLocation(), Param->getType(), 9200 diag::err_typecheck_decl_incomplete_type)) { 9201 Param->setInvalidDecl(); 9202 HasInvalidParm = true; 9203 } 9204 9205 // C99 6.9.1p5: If the declarator includes a parameter type list, the 9206 // declaration of each parameter shall include an identifier. 9207 if (CheckParameterNames && 9208 Param->getIdentifier() == nullptr && 9209 !Param->isImplicit() && 9210 !getLangOpts().CPlusPlus) 9211 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9212 9213 // C99 6.7.5.3p12: 9214 // If the function declarator is not part of a definition of that 9215 // function, parameters may have incomplete type and may use the [*] 9216 // notation in their sequences of declarator specifiers to specify 9217 // variable length array types. 9218 QualType PType = Param->getOriginalType(); 9219 // FIXME: This diagnostic should point the '[*]' if source-location 9220 // information is added for it. 9221 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 9222 9223 // MSVC destroys objects passed by value in the callee. Therefore a 9224 // function definition which takes such a parameter must be able to call the 9225 // object's destructor. However, we don't perform any direct access check 9226 // on the dtor. 9227 if (getLangOpts().CPlusPlus && Context.getTargetInfo() 9228 .getCXXABI() 9229 .areArgsDestroyedLeftToRightInCallee()) { 9230 if (!Param->isInvalidDecl()) { 9231 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) { 9232 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 9233 if (!ClassDecl->isInvalidDecl() && 9234 !ClassDecl->hasIrrelevantDestructor() && 9235 !ClassDecl->isDependentContext()) { 9236 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9237 MarkFunctionReferenced(Param->getLocation(), Destructor); 9238 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 9239 } 9240 } 9241 } 9242 } 9243 9244 // Parameters with the pass_object_size attribute only need to be marked 9245 // constant at function definitions. Because we lack information about 9246 // whether we're on a declaration or definition when we're instantiating the 9247 // attribute, we need to check for constness here. 9248 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 9249 if (!Param->getType().isConstQualified()) 9250 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 9251 << Attr->getSpelling() << 1; 9252 } 9253 9254 return HasInvalidParm; 9255 } 9256 9257 /// CheckCastAlign - Implements -Wcast-align, which warns when a 9258 /// pointer cast increases the alignment requirements. 9259 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 9260 // This is actually a lot of work to potentially be doing on every 9261 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 9262 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 9263 return; 9264 9265 // Ignore dependent types. 9266 if (T->isDependentType() || Op->getType()->isDependentType()) 9267 return; 9268 9269 // Require that the destination be a pointer type. 9270 const PointerType *DestPtr = T->getAs<PointerType>(); 9271 if (!DestPtr) return; 9272 9273 // If the destination has alignment 1, we're done. 9274 QualType DestPointee = DestPtr->getPointeeType(); 9275 if (DestPointee->isIncompleteType()) return; 9276 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 9277 if (DestAlign.isOne()) return; 9278 9279 // Require that the source be a pointer type. 9280 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 9281 if (!SrcPtr) return; 9282 QualType SrcPointee = SrcPtr->getPointeeType(); 9283 9284 // Whitelist casts from cv void*. We already implicitly 9285 // whitelisted casts to cv void*, since they have alignment 1. 9286 // Also whitelist casts involving incomplete types, which implicitly 9287 // includes 'void'. 9288 if (SrcPointee->isIncompleteType()) return; 9289 9290 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 9291 if (SrcAlign >= DestAlign) return; 9292 9293 Diag(TRange.getBegin(), diag::warn_cast_align) 9294 << Op->getType() << T 9295 << static_cast<unsigned>(SrcAlign.getQuantity()) 9296 << static_cast<unsigned>(DestAlign.getQuantity()) 9297 << TRange << Op->getSourceRange(); 9298 } 9299 9300 static const Type* getElementType(const Expr *BaseExpr) { 9301 const Type* EltType = BaseExpr->getType().getTypePtr(); 9302 if (EltType->isAnyPointerType()) 9303 return EltType->getPointeeType().getTypePtr(); 9304 else if (EltType->isArrayType()) 9305 return EltType->getBaseElementTypeUnsafe(); 9306 return EltType; 9307 } 9308 9309 /// \brief Check whether this array fits the idiom of a size-one tail padded 9310 /// array member of a struct. 9311 /// 9312 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 9313 /// commonly used to emulate flexible arrays in C89 code. 9314 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 9315 const NamedDecl *ND) { 9316 if (Size != 1 || !ND) return false; 9317 9318 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 9319 if (!FD) return false; 9320 9321 // Don't consider sizes resulting from macro expansions or template argument 9322 // substitution to form C89 tail-padded arrays. 9323 9324 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 9325 while (TInfo) { 9326 TypeLoc TL = TInfo->getTypeLoc(); 9327 // Look through typedefs. 9328 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 9329 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 9330 TInfo = TDL->getTypeSourceInfo(); 9331 continue; 9332 } 9333 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 9334 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 9335 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 9336 return false; 9337 } 9338 break; 9339 } 9340 9341 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 9342 if (!RD) return false; 9343 if (RD->isUnion()) return false; 9344 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9345 if (!CRD->isStandardLayout()) return false; 9346 } 9347 9348 // See if this is the last field decl in the record. 9349 const Decl *D = FD; 9350 while ((D = D->getNextDeclInContext())) 9351 if (isa<FieldDecl>(D)) 9352 return false; 9353 return true; 9354 } 9355 9356 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 9357 const ArraySubscriptExpr *ASE, 9358 bool AllowOnePastEnd, bool IndexNegated) { 9359 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 9360 if (IndexExpr->isValueDependent()) 9361 return; 9362 9363 const Type *EffectiveType = getElementType(BaseExpr); 9364 BaseExpr = BaseExpr->IgnoreParenCasts(); 9365 const ConstantArrayType *ArrayTy = 9366 Context.getAsConstantArrayType(BaseExpr->getType()); 9367 if (!ArrayTy) 9368 return; 9369 9370 llvm::APSInt index; 9371 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 9372 return; 9373 if (IndexNegated) 9374 index = -index; 9375 9376 const NamedDecl *ND = nullptr; 9377 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 9378 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 9379 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 9380 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 9381 9382 if (index.isUnsigned() || !index.isNegative()) { 9383 llvm::APInt size = ArrayTy->getSize(); 9384 if (!size.isStrictlyPositive()) 9385 return; 9386 9387 const Type* BaseType = getElementType(BaseExpr); 9388 if (BaseType != EffectiveType) { 9389 // Make sure we're comparing apples to apples when comparing index to size 9390 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 9391 uint64_t array_typesize = Context.getTypeSize(BaseType); 9392 // Handle ptrarith_typesize being zero, such as when casting to void* 9393 if (!ptrarith_typesize) ptrarith_typesize = 1; 9394 if (ptrarith_typesize != array_typesize) { 9395 // There's a cast to a different size type involved 9396 uint64_t ratio = array_typesize / ptrarith_typesize; 9397 // TODO: Be smarter about handling cases where array_typesize is not a 9398 // multiple of ptrarith_typesize 9399 if (ptrarith_typesize * ratio == array_typesize) 9400 size *= llvm::APInt(size.getBitWidth(), ratio); 9401 } 9402 } 9403 9404 if (size.getBitWidth() > index.getBitWidth()) 9405 index = index.zext(size.getBitWidth()); 9406 else if (size.getBitWidth() < index.getBitWidth()) 9407 size = size.zext(index.getBitWidth()); 9408 9409 // For array subscripting the index must be less than size, but for pointer 9410 // arithmetic also allow the index (offset) to be equal to size since 9411 // computing the next address after the end of the array is legal and 9412 // commonly done e.g. in C++ iterators and range-based for loops. 9413 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 9414 return; 9415 9416 // Also don't warn for arrays of size 1 which are members of some 9417 // structure. These are often used to approximate flexible arrays in C89 9418 // code. 9419 if (IsTailPaddedMemberArray(*this, size, ND)) 9420 return; 9421 9422 // Suppress the warning if the subscript expression (as identified by the 9423 // ']' location) and the index expression are both from macro expansions 9424 // within a system header. 9425 if (ASE) { 9426 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 9427 ASE->getRBracketLoc()); 9428 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 9429 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 9430 IndexExpr->getLocStart()); 9431 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 9432 return; 9433 } 9434 } 9435 9436 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 9437 if (ASE) 9438 DiagID = diag::warn_array_index_exceeds_bounds; 9439 9440 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 9441 PDiag(DiagID) << index.toString(10, true) 9442 << size.toString(10, true) 9443 << (unsigned)size.getLimitedValue(~0U) 9444 << IndexExpr->getSourceRange()); 9445 } else { 9446 unsigned DiagID = diag::warn_array_index_precedes_bounds; 9447 if (!ASE) { 9448 DiagID = diag::warn_ptr_arith_precedes_bounds; 9449 if (index.isNegative()) index = -index; 9450 } 9451 9452 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 9453 PDiag(DiagID) << index.toString(10, true) 9454 << IndexExpr->getSourceRange()); 9455 } 9456 9457 if (!ND) { 9458 // Try harder to find a NamedDecl to point at in the note. 9459 while (const ArraySubscriptExpr *ASE = 9460 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 9461 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 9462 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 9463 ND = dyn_cast<NamedDecl>(DRE->getDecl()); 9464 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 9465 ND = dyn_cast<NamedDecl>(ME->getMemberDecl()); 9466 } 9467 9468 if (ND) 9469 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 9470 PDiag(diag::note_array_index_out_of_bounds) 9471 << ND->getDeclName()); 9472 } 9473 9474 void Sema::CheckArrayAccess(const Expr *expr) { 9475 int AllowOnePastEnd = 0; 9476 while (expr) { 9477 expr = expr->IgnoreParenImpCasts(); 9478 switch (expr->getStmtClass()) { 9479 case Stmt::ArraySubscriptExprClass: { 9480 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 9481 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 9482 AllowOnePastEnd > 0); 9483 return; 9484 } 9485 case Stmt::OMPArraySectionExprClass: { 9486 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 9487 if (ASE->getLowerBound()) 9488 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 9489 /*ASE=*/nullptr, AllowOnePastEnd > 0); 9490 return; 9491 } 9492 case Stmt::UnaryOperatorClass: { 9493 // Only unwrap the * and & unary operators 9494 const UnaryOperator *UO = cast<UnaryOperator>(expr); 9495 expr = UO->getSubExpr(); 9496 switch (UO->getOpcode()) { 9497 case UO_AddrOf: 9498 AllowOnePastEnd++; 9499 break; 9500 case UO_Deref: 9501 AllowOnePastEnd--; 9502 break; 9503 default: 9504 return; 9505 } 9506 break; 9507 } 9508 case Stmt::ConditionalOperatorClass: { 9509 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 9510 if (const Expr *lhs = cond->getLHS()) 9511 CheckArrayAccess(lhs); 9512 if (const Expr *rhs = cond->getRHS()) 9513 CheckArrayAccess(rhs); 9514 return; 9515 } 9516 default: 9517 return; 9518 } 9519 } 9520 } 9521 9522 //===--- CHECK: Objective-C retain cycles ----------------------------------// 9523 9524 namespace { 9525 struct RetainCycleOwner { 9526 RetainCycleOwner() : Variable(nullptr), Indirect(false) {} 9527 VarDecl *Variable; 9528 SourceRange Range; 9529 SourceLocation Loc; 9530 bool Indirect; 9531 9532 void setLocsFrom(Expr *e) { 9533 Loc = e->getExprLoc(); 9534 Range = e->getSourceRange(); 9535 } 9536 }; 9537 } // end anonymous namespace 9538 9539 /// Consider whether capturing the given variable can possibly lead to 9540 /// a retain cycle. 9541 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 9542 // In ARC, it's captured strongly iff the variable has __strong 9543 // lifetime. In MRR, it's captured strongly if the variable is 9544 // __block and has an appropriate type. 9545 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 9546 return false; 9547 9548 owner.Variable = var; 9549 if (ref) 9550 owner.setLocsFrom(ref); 9551 return true; 9552 } 9553 9554 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 9555 while (true) { 9556 e = e->IgnoreParens(); 9557 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 9558 switch (cast->getCastKind()) { 9559 case CK_BitCast: 9560 case CK_LValueBitCast: 9561 case CK_LValueToRValue: 9562 case CK_ARCReclaimReturnedObject: 9563 e = cast->getSubExpr(); 9564 continue; 9565 9566 default: 9567 return false; 9568 } 9569 } 9570 9571 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 9572 ObjCIvarDecl *ivar = ref->getDecl(); 9573 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 9574 return false; 9575 9576 // Try to find a retain cycle in the base. 9577 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 9578 return false; 9579 9580 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 9581 owner.Indirect = true; 9582 return true; 9583 } 9584 9585 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 9586 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 9587 if (!var) return false; 9588 return considerVariable(var, ref, owner); 9589 } 9590 9591 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 9592 if (member->isArrow()) return false; 9593 9594 // Don't count this as an indirect ownership. 9595 e = member->getBase(); 9596 continue; 9597 } 9598 9599 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 9600 // Only pay attention to pseudo-objects on property references. 9601 ObjCPropertyRefExpr *pre 9602 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 9603 ->IgnoreParens()); 9604 if (!pre) return false; 9605 if (pre->isImplicitProperty()) return false; 9606 ObjCPropertyDecl *property = pre->getExplicitProperty(); 9607 if (!property->isRetaining() && 9608 !(property->getPropertyIvarDecl() && 9609 property->getPropertyIvarDecl()->getType() 9610 .getObjCLifetime() == Qualifiers::OCL_Strong)) 9611 return false; 9612 9613 owner.Indirect = true; 9614 if (pre->isSuperReceiver()) { 9615 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 9616 if (!owner.Variable) 9617 return false; 9618 owner.Loc = pre->getLocation(); 9619 owner.Range = pre->getSourceRange(); 9620 return true; 9621 } 9622 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 9623 ->getSourceExpr()); 9624 continue; 9625 } 9626 9627 // Array ivars? 9628 9629 return false; 9630 } 9631 } 9632 9633 namespace { 9634 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 9635 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 9636 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 9637 Context(Context), Variable(variable), Capturer(nullptr), 9638 VarWillBeReased(false) {} 9639 ASTContext &Context; 9640 VarDecl *Variable; 9641 Expr *Capturer; 9642 bool VarWillBeReased; 9643 9644 void VisitDeclRefExpr(DeclRefExpr *ref) { 9645 if (ref->getDecl() == Variable && !Capturer) 9646 Capturer = ref; 9647 } 9648 9649 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 9650 if (Capturer) return; 9651 Visit(ref->getBase()); 9652 if (Capturer && ref->isFreeIvar()) 9653 Capturer = ref; 9654 } 9655 9656 void VisitBlockExpr(BlockExpr *block) { 9657 // Look inside nested blocks 9658 if (block->getBlockDecl()->capturesVariable(Variable)) 9659 Visit(block->getBlockDecl()->getBody()); 9660 } 9661 9662 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 9663 if (Capturer) return; 9664 if (OVE->getSourceExpr()) 9665 Visit(OVE->getSourceExpr()); 9666 } 9667 void VisitBinaryOperator(BinaryOperator *BinOp) { 9668 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 9669 return; 9670 Expr *LHS = BinOp->getLHS(); 9671 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 9672 if (DRE->getDecl() != Variable) 9673 return; 9674 if (Expr *RHS = BinOp->getRHS()) { 9675 RHS = RHS->IgnoreParenCasts(); 9676 llvm::APSInt Value; 9677 VarWillBeReased = 9678 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 9679 } 9680 } 9681 } 9682 }; 9683 } // end anonymous namespace 9684 9685 /// Check whether the given argument is a block which captures a 9686 /// variable. 9687 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 9688 assert(owner.Variable && owner.Loc.isValid()); 9689 9690 e = e->IgnoreParenCasts(); 9691 9692 // Look through [^{...} copy] and Block_copy(^{...}). 9693 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 9694 Selector Cmd = ME->getSelector(); 9695 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 9696 e = ME->getInstanceReceiver(); 9697 if (!e) 9698 return nullptr; 9699 e = e->IgnoreParenCasts(); 9700 } 9701 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 9702 if (CE->getNumArgs() == 1) { 9703 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 9704 if (Fn) { 9705 const IdentifierInfo *FnI = Fn->getIdentifier(); 9706 if (FnI && FnI->isStr("_Block_copy")) { 9707 e = CE->getArg(0)->IgnoreParenCasts(); 9708 } 9709 } 9710 } 9711 } 9712 9713 BlockExpr *block = dyn_cast<BlockExpr>(e); 9714 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 9715 return nullptr; 9716 9717 FindCaptureVisitor visitor(S.Context, owner.Variable); 9718 visitor.Visit(block->getBlockDecl()->getBody()); 9719 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 9720 } 9721 9722 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 9723 RetainCycleOwner &owner) { 9724 assert(capturer); 9725 assert(owner.Variable && owner.Loc.isValid()); 9726 9727 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 9728 << owner.Variable << capturer->getSourceRange(); 9729 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 9730 << owner.Indirect << owner.Range; 9731 } 9732 9733 /// Check for a keyword selector that starts with the word 'add' or 9734 /// 'set'. 9735 static bool isSetterLikeSelector(Selector sel) { 9736 if (sel.isUnarySelector()) return false; 9737 9738 StringRef str = sel.getNameForSlot(0); 9739 while (!str.empty() && str.front() == '_') str = str.substr(1); 9740 if (str.startswith("set")) 9741 str = str.substr(3); 9742 else if (str.startswith("add")) { 9743 // Specially whitelist 'addOperationWithBlock:'. 9744 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 9745 return false; 9746 str = str.substr(3); 9747 } 9748 else 9749 return false; 9750 9751 if (str.empty()) return true; 9752 return !isLowercase(str.front()); 9753 } 9754 9755 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 9756 ObjCMessageExpr *Message) { 9757 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 9758 Message->getReceiverInterface(), 9759 NSAPI::ClassId_NSMutableArray); 9760 if (!IsMutableArray) { 9761 return None; 9762 } 9763 9764 Selector Sel = Message->getSelector(); 9765 9766 Optional<NSAPI::NSArrayMethodKind> MKOpt = 9767 S.NSAPIObj->getNSArrayMethodKind(Sel); 9768 if (!MKOpt) { 9769 return None; 9770 } 9771 9772 NSAPI::NSArrayMethodKind MK = *MKOpt; 9773 9774 switch (MK) { 9775 case NSAPI::NSMutableArr_addObject: 9776 case NSAPI::NSMutableArr_insertObjectAtIndex: 9777 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 9778 return 0; 9779 case NSAPI::NSMutableArr_replaceObjectAtIndex: 9780 return 1; 9781 9782 default: 9783 return None; 9784 } 9785 9786 return None; 9787 } 9788 9789 static 9790 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 9791 ObjCMessageExpr *Message) { 9792 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 9793 Message->getReceiverInterface(), 9794 NSAPI::ClassId_NSMutableDictionary); 9795 if (!IsMutableDictionary) { 9796 return None; 9797 } 9798 9799 Selector Sel = Message->getSelector(); 9800 9801 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 9802 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 9803 if (!MKOpt) { 9804 return None; 9805 } 9806 9807 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 9808 9809 switch (MK) { 9810 case NSAPI::NSMutableDict_setObjectForKey: 9811 case NSAPI::NSMutableDict_setValueForKey: 9812 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 9813 return 0; 9814 9815 default: 9816 return None; 9817 } 9818 9819 return None; 9820 } 9821 9822 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 9823 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 9824 Message->getReceiverInterface(), 9825 NSAPI::ClassId_NSMutableSet); 9826 9827 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 9828 Message->getReceiverInterface(), 9829 NSAPI::ClassId_NSMutableOrderedSet); 9830 if (!IsMutableSet && !IsMutableOrderedSet) { 9831 return None; 9832 } 9833 9834 Selector Sel = Message->getSelector(); 9835 9836 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 9837 if (!MKOpt) { 9838 return None; 9839 } 9840 9841 NSAPI::NSSetMethodKind MK = *MKOpt; 9842 9843 switch (MK) { 9844 case NSAPI::NSMutableSet_addObject: 9845 case NSAPI::NSOrderedSet_setObjectAtIndex: 9846 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 9847 case NSAPI::NSOrderedSet_insertObjectAtIndex: 9848 return 0; 9849 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 9850 return 1; 9851 } 9852 9853 return None; 9854 } 9855 9856 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 9857 if (!Message->isInstanceMessage()) { 9858 return; 9859 } 9860 9861 Optional<int> ArgOpt; 9862 9863 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 9864 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 9865 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 9866 return; 9867 } 9868 9869 int ArgIndex = *ArgOpt; 9870 9871 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 9872 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 9873 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 9874 } 9875 9876 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 9877 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 9878 if (ArgRE->isObjCSelfExpr()) { 9879 Diag(Message->getSourceRange().getBegin(), 9880 diag::warn_objc_circular_container) 9881 << ArgRE->getDecl()->getName() << StringRef("super"); 9882 } 9883 } 9884 } else { 9885 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 9886 9887 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 9888 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 9889 } 9890 9891 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 9892 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 9893 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 9894 ValueDecl *Decl = ReceiverRE->getDecl(); 9895 Diag(Message->getSourceRange().getBegin(), 9896 diag::warn_objc_circular_container) 9897 << Decl->getName() << Decl->getName(); 9898 if (!ArgRE->isObjCSelfExpr()) { 9899 Diag(Decl->getLocation(), 9900 diag::note_objc_circular_container_declared_here) 9901 << Decl->getName(); 9902 } 9903 } 9904 } 9905 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 9906 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 9907 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 9908 ObjCIvarDecl *Decl = IvarRE->getDecl(); 9909 Diag(Message->getSourceRange().getBegin(), 9910 diag::warn_objc_circular_container) 9911 << Decl->getName() << Decl->getName(); 9912 Diag(Decl->getLocation(), 9913 diag::note_objc_circular_container_declared_here) 9914 << Decl->getName(); 9915 } 9916 } 9917 } 9918 } 9919 } 9920 9921 /// Check a message send to see if it's likely to cause a retain cycle. 9922 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 9923 // Only check instance methods whose selector looks like a setter. 9924 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 9925 return; 9926 9927 // Try to find a variable that the receiver is strongly owned by. 9928 RetainCycleOwner owner; 9929 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 9930 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 9931 return; 9932 } else { 9933 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 9934 owner.Variable = getCurMethodDecl()->getSelfDecl(); 9935 owner.Loc = msg->getSuperLoc(); 9936 owner.Range = msg->getSuperLoc(); 9937 } 9938 9939 // Check whether the receiver is captured by any of the arguments. 9940 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) 9941 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) 9942 return diagnoseRetainCycle(*this, capturer, owner); 9943 } 9944 9945 /// Check a property assign to see if it's likely to cause a retain cycle. 9946 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 9947 RetainCycleOwner owner; 9948 if (!findRetainCycleOwner(*this, receiver, owner)) 9949 return; 9950 9951 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 9952 diagnoseRetainCycle(*this, capturer, owner); 9953 } 9954 9955 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 9956 RetainCycleOwner Owner; 9957 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 9958 return; 9959 9960 // Because we don't have an expression for the variable, we have to set the 9961 // location explicitly here. 9962 Owner.Loc = Var->getLocation(); 9963 Owner.Range = Var->getSourceRange(); 9964 9965 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 9966 diagnoseRetainCycle(*this, Capturer, Owner); 9967 } 9968 9969 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 9970 Expr *RHS, bool isProperty) { 9971 // Check if RHS is an Objective-C object literal, which also can get 9972 // immediately zapped in a weak reference. Note that we explicitly 9973 // allow ObjCStringLiterals, since those are designed to never really die. 9974 RHS = RHS->IgnoreParenImpCasts(); 9975 9976 // This enum needs to match with the 'select' in 9977 // warn_objc_arc_literal_assign (off-by-1). 9978 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 9979 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 9980 return false; 9981 9982 S.Diag(Loc, diag::warn_arc_literal_assign) 9983 << (unsigned) Kind 9984 << (isProperty ? 0 : 1) 9985 << RHS->getSourceRange(); 9986 9987 return true; 9988 } 9989 9990 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 9991 Qualifiers::ObjCLifetime LT, 9992 Expr *RHS, bool isProperty) { 9993 // Strip off any implicit cast added to get to the one ARC-specific. 9994 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 9995 if (cast->getCastKind() == CK_ARCConsumeObject) { 9996 S.Diag(Loc, diag::warn_arc_retained_assign) 9997 << (LT == Qualifiers::OCL_ExplicitNone) 9998 << (isProperty ? 0 : 1) 9999 << RHS->getSourceRange(); 10000 return true; 10001 } 10002 RHS = cast->getSubExpr(); 10003 } 10004 10005 if (LT == Qualifiers::OCL_Weak && 10006 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 10007 return true; 10008 10009 return false; 10010 } 10011 10012 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 10013 QualType LHS, Expr *RHS) { 10014 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 10015 10016 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 10017 return false; 10018 10019 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 10020 return true; 10021 10022 return false; 10023 } 10024 10025 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 10026 Expr *LHS, Expr *RHS) { 10027 QualType LHSType; 10028 // PropertyRef on LHS type need be directly obtained from 10029 // its declaration as it has a PseudoType. 10030 ObjCPropertyRefExpr *PRE 10031 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 10032 if (PRE && !PRE->isImplicitProperty()) { 10033 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 10034 if (PD) 10035 LHSType = PD->getType(); 10036 } 10037 10038 if (LHSType.isNull()) 10039 LHSType = LHS->getType(); 10040 10041 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 10042 10043 if (LT == Qualifiers::OCL_Weak) { 10044 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 10045 getCurFunction()->markSafeWeakUse(LHS); 10046 } 10047 10048 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 10049 return; 10050 10051 // FIXME. Check for other life times. 10052 if (LT != Qualifiers::OCL_None) 10053 return; 10054 10055 if (PRE) { 10056 if (PRE->isImplicitProperty()) 10057 return; 10058 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 10059 if (!PD) 10060 return; 10061 10062 unsigned Attributes = PD->getPropertyAttributes(); 10063 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 10064 // when 'assign' attribute was not explicitly specified 10065 // by user, ignore it and rely on property type itself 10066 // for lifetime info. 10067 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 10068 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 10069 LHSType->isObjCRetainableType()) 10070 return; 10071 10072 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 10073 if (cast->getCastKind() == CK_ARCConsumeObject) { 10074 Diag(Loc, diag::warn_arc_retained_property_assign) 10075 << RHS->getSourceRange(); 10076 return; 10077 } 10078 RHS = cast->getSubExpr(); 10079 } 10080 } 10081 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 10082 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 10083 return; 10084 } 10085 } 10086 } 10087 10088 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 10089 10090 namespace { 10091 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 10092 SourceLocation StmtLoc, 10093 const NullStmt *Body) { 10094 // Do not warn if the body is a macro that expands to nothing, e.g: 10095 // 10096 // #define CALL(x) 10097 // if (condition) 10098 // CALL(0); 10099 // 10100 if (Body->hasLeadingEmptyMacro()) 10101 return false; 10102 10103 // Get line numbers of statement and body. 10104 bool StmtLineInvalid; 10105 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 10106 &StmtLineInvalid); 10107 if (StmtLineInvalid) 10108 return false; 10109 10110 bool BodyLineInvalid; 10111 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 10112 &BodyLineInvalid); 10113 if (BodyLineInvalid) 10114 return false; 10115 10116 // Warn if null statement and body are on the same line. 10117 if (StmtLine != BodyLine) 10118 return false; 10119 10120 return true; 10121 } 10122 } // end anonymous namespace 10123 10124 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 10125 const Stmt *Body, 10126 unsigned DiagID) { 10127 // Since this is a syntactic check, don't emit diagnostic for template 10128 // instantiations, this just adds noise. 10129 if (CurrentInstantiationScope) 10130 return; 10131 10132 // The body should be a null statement. 10133 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 10134 if (!NBody) 10135 return; 10136 10137 // Do the usual checks. 10138 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 10139 return; 10140 10141 Diag(NBody->getSemiLoc(), DiagID); 10142 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 10143 } 10144 10145 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 10146 const Stmt *PossibleBody) { 10147 assert(!CurrentInstantiationScope); // Ensured by caller 10148 10149 SourceLocation StmtLoc; 10150 const Stmt *Body; 10151 unsigned DiagID; 10152 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 10153 StmtLoc = FS->getRParenLoc(); 10154 Body = FS->getBody(); 10155 DiagID = diag::warn_empty_for_body; 10156 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 10157 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 10158 Body = WS->getBody(); 10159 DiagID = diag::warn_empty_while_body; 10160 } else 10161 return; // Neither `for' nor `while'. 10162 10163 // The body should be a null statement. 10164 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 10165 if (!NBody) 10166 return; 10167 10168 // Skip expensive checks if diagnostic is disabled. 10169 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 10170 return; 10171 10172 // Do the usual checks. 10173 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 10174 return; 10175 10176 // `for(...);' and `while(...);' are popular idioms, so in order to keep 10177 // noise level low, emit diagnostics only if for/while is followed by a 10178 // CompoundStmt, e.g.: 10179 // for (int i = 0; i < n; i++); 10180 // { 10181 // a(i); 10182 // } 10183 // or if for/while is followed by a statement with more indentation 10184 // than for/while itself: 10185 // for (int i = 0; i < n; i++); 10186 // a(i); 10187 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 10188 if (!ProbableTypo) { 10189 bool BodyColInvalid; 10190 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 10191 PossibleBody->getLocStart(), 10192 &BodyColInvalid); 10193 if (BodyColInvalid) 10194 return; 10195 10196 bool StmtColInvalid; 10197 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 10198 S->getLocStart(), 10199 &StmtColInvalid); 10200 if (StmtColInvalid) 10201 return; 10202 10203 if (BodyCol > StmtCol) 10204 ProbableTypo = true; 10205 } 10206 10207 if (ProbableTypo) { 10208 Diag(NBody->getSemiLoc(), DiagID); 10209 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 10210 } 10211 } 10212 10213 //===--- CHECK: Warn on self move with std::move. -------------------------===// 10214 10215 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 10216 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 10217 SourceLocation OpLoc) { 10218 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 10219 return; 10220 10221 if (!ActiveTemplateInstantiations.empty()) 10222 return; 10223 10224 // Strip parens and casts away. 10225 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10226 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10227 10228 // Check for a call expression 10229 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 10230 if (!CE || CE->getNumArgs() != 1) 10231 return; 10232 10233 // Check for a call to std::move 10234 const FunctionDecl *FD = CE->getDirectCallee(); 10235 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() || 10236 !FD->getIdentifier()->isStr("move")) 10237 return; 10238 10239 // Get argument from std::move 10240 RHSExpr = CE->getArg(0); 10241 10242 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10243 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10244 10245 // Two DeclRefExpr's, check that the decls are the same. 10246 if (LHSDeclRef && RHSDeclRef) { 10247 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 10248 return; 10249 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 10250 RHSDeclRef->getDecl()->getCanonicalDecl()) 10251 return; 10252 10253 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10254 << LHSExpr->getSourceRange() 10255 << RHSExpr->getSourceRange(); 10256 return; 10257 } 10258 10259 // Member variables require a different approach to check for self moves. 10260 // MemberExpr's are the same if every nested MemberExpr refers to the same 10261 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 10262 // the base Expr's are CXXThisExpr's. 10263 const Expr *LHSBase = LHSExpr; 10264 const Expr *RHSBase = RHSExpr; 10265 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 10266 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 10267 if (!LHSME || !RHSME) 10268 return; 10269 10270 while (LHSME && RHSME) { 10271 if (LHSME->getMemberDecl()->getCanonicalDecl() != 10272 RHSME->getMemberDecl()->getCanonicalDecl()) 10273 return; 10274 10275 LHSBase = LHSME->getBase(); 10276 RHSBase = RHSME->getBase(); 10277 LHSME = dyn_cast<MemberExpr>(LHSBase); 10278 RHSME = dyn_cast<MemberExpr>(RHSBase); 10279 } 10280 10281 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 10282 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 10283 if (LHSDeclRef && RHSDeclRef) { 10284 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 10285 return; 10286 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 10287 RHSDeclRef->getDecl()->getCanonicalDecl()) 10288 return; 10289 10290 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10291 << LHSExpr->getSourceRange() 10292 << RHSExpr->getSourceRange(); 10293 return; 10294 } 10295 10296 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 10297 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 10298 << LHSExpr->getSourceRange() 10299 << RHSExpr->getSourceRange(); 10300 } 10301 10302 //===--- Layout compatibility ----------------------------------------------// 10303 10304 namespace { 10305 10306 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 10307 10308 /// \brief Check if two enumeration types are layout-compatible. 10309 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 10310 // C++11 [dcl.enum] p8: 10311 // Two enumeration types are layout-compatible if they have the same 10312 // underlying type. 10313 return ED1->isComplete() && ED2->isComplete() && 10314 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 10315 } 10316 10317 /// \brief Check if two fields are layout-compatible. 10318 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) { 10319 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 10320 return false; 10321 10322 if (Field1->isBitField() != Field2->isBitField()) 10323 return false; 10324 10325 if (Field1->isBitField()) { 10326 // Make sure that the bit-fields are the same length. 10327 unsigned Bits1 = Field1->getBitWidthValue(C); 10328 unsigned Bits2 = Field2->getBitWidthValue(C); 10329 10330 if (Bits1 != Bits2) 10331 return false; 10332 } 10333 10334 return true; 10335 } 10336 10337 /// \brief Check if two standard-layout structs are layout-compatible. 10338 /// (C++11 [class.mem] p17) 10339 bool isLayoutCompatibleStruct(ASTContext &C, 10340 RecordDecl *RD1, 10341 RecordDecl *RD2) { 10342 // If both records are C++ classes, check that base classes match. 10343 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 10344 // If one of records is a CXXRecordDecl we are in C++ mode, 10345 // thus the other one is a CXXRecordDecl, too. 10346 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 10347 // Check number of base classes. 10348 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 10349 return false; 10350 10351 // Check the base classes. 10352 for (CXXRecordDecl::base_class_const_iterator 10353 Base1 = D1CXX->bases_begin(), 10354 BaseEnd1 = D1CXX->bases_end(), 10355 Base2 = D2CXX->bases_begin(); 10356 Base1 != BaseEnd1; 10357 ++Base1, ++Base2) { 10358 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 10359 return false; 10360 } 10361 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 10362 // If only RD2 is a C++ class, it should have zero base classes. 10363 if (D2CXX->getNumBases() > 0) 10364 return false; 10365 } 10366 10367 // Check the fields. 10368 RecordDecl::field_iterator Field2 = RD2->field_begin(), 10369 Field2End = RD2->field_end(), 10370 Field1 = RD1->field_begin(), 10371 Field1End = RD1->field_end(); 10372 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 10373 if (!isLayoutCompatible(C, *Field1, *Field2)) 10374 return false; 10375 } 10376 if (Field1 != Field1End || Field2 != Field2End) 10377 return false; 10378 10379 return true; 10380 } 10381 10382 /// \brief Check if two standard-layout unions are layout-compatible. 10383 /// (C++11 [class.mem] p18) 10384 bool isLayoutCompatibleUnion(ASTContext &C, 10385 RecordDecl *RD1, 10386 RecordDecl *RD2) { 10387 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 10388 for (auto *Field2 : RD2->fields()) 10389 UnmatchedFields.insert(Field2); 10390 10391 for (auto *Field1 : RD1->fields()) { 10392 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 10393 I = UnmatchedFields.begin(), 10394 E = UnmatchedFields.end(); 10395 10396 for ( ; I != E; ++I) { 10397 if (isLayoutCompatible(C, Field1, *I)) { 10398 bool Result = UnmatchedFields.erase(*I); 10399 (void) Result; 10400 assert(Result); 10401 break; 10402 } 10403 } 10404 if (I == E) 10405 return false; 10406 } 10407 10408 return UnmatchedFields.empty(); 10409 } 10410 10411 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) { 10412 if (RD1->isUnion() != RD2->isUnion()) 10413 return false; 10414 10415 if (RD1->isUnion()) 10416 return isLayoutCompatibleUnion(C, RD1, RD2); 10417 else 10418 return isLayoutCompatibleStruct(C, RD1, RD2); 10419 } 10420 10421 /// \brief Check if two types are layout-compatible in C++11 sense. 10422 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 10423 if (T1.isNull() || T2.isNull()) 10424 return false; 10425 10426 // C++11 [basic.types] p11: 10427 // If two types T1 and T2 are the same type, then T1 and T2 are 10428 // layout-compatible types. 10429 if (C.hasSameType(T1, T2)) 10430 return true; 10431 10432 T1 = T1.getCanonicalType().getUnqualifiedType(); 10433 T2 = T2.getCanonicalType().getUnqualifiedType(); 10434 10435 const Type::TypeClass TC1 = T1->getTypeClass(); 10436 const Type::TypeClass TC2 = T2->getTypeClass(); 10437 10438 if (TC1 != TC2) 10439 return false; 10440 10441 if (TC1 == Type::Enum) { 10442 return isLayoutCompatible(C, 10443 cast<EnumType>(T1)->getDecl(), 10444 cast<EnumType>(T2)->getDecl()); 10445 } else if (TC1 == Type::Record) { 10446 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 10447 return false; 10448 10449 return isLayoutCompatible(C, 10450 cast<RecordType>(T1)->getDecl(), 10451 cast<RecordType>(T2)->getDecl()); 10452 } 10453 10454 return false; 10455 } 10456 } // end anonymous namespace 10457 10458 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 10459 10460 namespace { 10461 /// \brief Given a type tag expression find the type tag itself. 10462 /// 10463 /// \param TypeExpr Type tag expression, as it appears in user's code. 10464 /// 10465 /// \param VD Declaration of an identifier that appears in a type tag. 10466 /// 10467 /// \param MagicValue Type tag magic value. 10468 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 10469 const ValueDecl **VD, uint64_t *MagicValue) { 10470 while(true) { 10471 if (!TypeExpr) 10472 return false; 10473 10474 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 10475 10476 switch (TypeExpr->getStmtClass()) { 10477 case Stmt::UnaryOperatorClass: { 10478 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 10479 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 10480 TypeExpr = UO->getSubExpr(); 10481 continue; 10482 } 10483 return false; 10484 } 10485 10486 case Stmt::DeclRefExprClass: { 10487 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 10488 *VD = DRE->getDecl(); 10489 return true; 10490 } 10491 10492 case Stmt::IntegerLiteralClass: { 10493 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 10494 llvm::APInt MagicValueAPInt = IL->getValue(); 10495 if (MagicValueAPInt.getActiveBits() <= 64) { 10496 *MagicValue = MagicValueAPInt.getZExtValue(); 10497 return true; 10498 } else 10499 return false; 10500 } 10501 10502 case Stmt::BinaryConditionalOperatorClass: 10503 case Stmt::ConditionalOperatorClass: { 10504 const AbstractConditionalOperator *ACO = 10505 cast<AbstractConditionalOperator>(TypeExpr); 10506 bool Result; 10507 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 10508 if (Result) 10509 TypeExpr = ACO->getTrueExpr(); 10510 else 10511 TypeExpr = ACO->getFalseExpr(); 10512 continue; 10513 } 10514 return false; 10515 } 10516 10517 case Stmt::BinaryOperatorClass: { 10518 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 10519 if (BO->getOpcode() == BO_Comma) { 10520 TypeExpr = BO->getRHS(); 10521 continue; 10522 } 10523 return false; 10524 } 10525 10526 default: 10527 return false; 10528 } 10529 } 10530 } 10531 10532 /// \brief Retrieve the C type corresponding to type tag TypeExpr. 10533 /// 10534 /// \param TypeExpr Expression that specifies a type tag. 10535 /// 10536 /// \param MagicValues Registered magic values. 10537 /// 10538 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 10539 /// kind. 10540 /// 10541 /// \param TypeInfo Information about the corresponding C type. 10542 /// 10543 /// \returns true if the corresponding C type was found. 10544 bool GetMatchingCType( 10545 const IdentifierInfo *ArgumentKind, 10546 const Expr *TypeExpr, const ASTContext &Ctx, 10547 const llvm::DenseMap<Sema::TypeTagMagicValue, 10548 Sema::TypeTagData> *MagicValues, 10549 bool &FoundWrongKind, 10550 Sema::TypeTagData &TypeInfo) { 10551 FoundWrongKind = false; 10552 10553 // Variable declaration that has type_tag_for_datatype attribute. 10554 const ValueDecl *VD = nullptr; 10555 10556 uint64_t MagicValue; 10557 10558 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 10559 return false; 10560 10561 if (VD) { 10562 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 10563 if (I->getArgumentKind() != ArgumentKind) { 10564 FoundWrongKind = true; 10565 return false; 10566 } 10567 TypeInfo.Type = I->getMatchingCType(); 10568 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 10569 TypeInfo.MustBeNull = I->getMustBeNull(); 10570 return true; 10571 } 10572 return false; 10573 } 10574 10575 if (!MagicValues) 10576 return false; 10577 10578 llvm::DenseMap<Sema::TypeTagMagicValue, 10579 Sema::TypeTagData>::const_iterator I = 10580 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 10581 if (I == MagicValues->end()) 10582 return false; 10583 10584 TypeInfo = I->second; 10585 return true; 10586 } 10587 } // end anonymous namespace 10588 10589 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 10590 uint64_t MagicValue, QualType Type, 10591 bool LayoutCompatible, 10592 bool MustBeNull) { 10593 if (!TypeTagForDatatypeMagicValues) 10594 TypeTagForDatatypeMagicValues.reset( 10595 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 10596 10597 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 10598 (*TypeTagForDatatypeMagicValues)[Magic] = 10599 TypeTagData(Type, LayoutCompatible, MustBeNull); 10600 } 10601 10602 namespace { 10603 bool IsSameCharType(QualType T1, QualType T2) { 10604 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 10605 if (!BT1) 10606 return false; 10607 10608 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 10609 if (!BT2) 10610 return false; 10611 10612 BuiltinType::Kind T1Kind = BT1->getKind(); 10613 BuiltinType::Kind T2Kind = BT2->getKind(); 10614 10615 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 10616 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 10617 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 10618 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 10619 } 10620 } // end anonymous namespace 10621 10622 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 10623 const Expr * const *ExprArgs) { 10624 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 10625 bool IsPointerAttr = Attr->getIsPointer(); 10626 10627 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()]; 10628 bool FoundWrongKind; 10629 TypeTagData TypeInfo; 10630 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 10631 TypeTagForDatatypeMagicValues.get(), 10632 FoundWrongKind, TypeInfo)) { 10633 if (FoundWrongKind) 10634 Diag(TypeTagExpr->getExprLoc(), 10635 diag::warn_type_tag_for_datatype_wrong_kind) 10636 << TypeTagExpr->getSourceRange(); 10637 return; 10638 } 10639 10640 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()]; 10641 if (IsPointerAttr) { 10642 // Skip implicit cast of pointer to `void *' (as a function argument). 10643 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 10644 if (ICE->getType()->isVoidPointerType() && 10645 ICE->getCastKind() == CK_BitCast) 10646 ArgumentExpr = ICE->getSubExpr(); 10647 } 10648 QualType ArgumentType = ArgumentExpr->getType(); 10649 10650 // Passing a `void*' pointer shouldn't trigger a warning. 10651 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 10652 return; 10653 10654 if (TypeInfo.MustBeNull) { 10655 // Type tag with matching void type requires a null pointer. 10656 if (!ArgumentExpr->isNullPointerConstant(Context, 10657 Expr::NPC_ValueDependentIsNotNull)) { 10658 Diag(ArgumentExpr->getExprLoc(), 10659 diag::warn_type_safety_null_pointer_required) 10660 << ArgumentKind->getName() 10661 << ArgumentExpr->getSourceRange() 10662 << TypeTagExpr->getSourceRange(); 10663 } 10664 return; 10665 } 10666 10667 QualType RequiredType = TypeInfo.Type; 10668 if (IsPointerAttr) 10669 RequiredType = Context.getPointerType(RequiredType); 10670 10671 bool mismatch = false; 10672 if (!TypeInfo.LayoutCompatible) { 10673 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 10674 10675 // C++11 [basic.fundamental] p1: 10676 // Plain char, signed char, and unsigned char are three distinct types. 10677 // 10678 // But we treat plain `char' as equivalent to `signed char' or `unsigned 10679 // char' depending on the current char signedness mode. 10680 if (mismatch) 10681 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 10682 RequiredType->getPointeeType())) || 10683 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 10684 mismatch = false; 10685 } else 10686 if (IsPointerAttr) 10687 mismatch = !isLayoutCompatible(Context, 10688 ArgumentType->getPointeeType(), 10689 RequiredType->getPointeeType()); 10690 else 10691 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 10692 10693 if (mismatch) 10694 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 10695 << ArgumentType << ArgumentKind 10696 << TypeInfo.LayoutCompatible << RequiredType 10697 << ArgumentExpr->getSourceRange() 10698 << TypeTagExpr->getSourceRange(); 10699 } 10700