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