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/AST/APValue.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/ExprOpenMP.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Analysis/Analyses/FormatString.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getLocStart(), 121 call->getArg(argCount - 1)->getLocEnd()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 195 if (checkArgCount(S, TheCall, 3)) 196 return true; 197 198 // First two arguments should be integers. 199 for (unsigned I = 0; I < 2; ++I) { 200 ExprResult Arg = TheCall->getArg(I); 201 QualType Ty = Arg.get()->getType(); 202 if (!Ty->isIntegerType()) { 203 S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int) 204 << Ty << Arg.get()->getSourceRange(); 205 return true; 206 } 207 InitializedEntity Entity = InitializedEntity::InitializeParameter( 208 S.getASTContext(), Ty, /*consume*/ false); 209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 210 if (Arg.isInvalid()) 211 return true; 212 TheCall->setArg(I, Arg.get()); 213 } 214 215 // Third argument should be a pointer to a non-const integer. 216 // IRGen correctly handles volatile, restrict, and address spaces, and 217 // the other qualifiers aren't possible. 218 { 219 ExprResult Arg = TheCall->getArg(2); 220 QualType Ty = Arg.get()->getType(); 221 const auto *PtrTy = Ty->getAs<PointerType>(); 222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 223 !PtrTy->getPointeeType().isConstQualified())) { 224 S.Diag(Arg.get()->getLocStart(), 225 diag::err_overflow_builtin_must_be_ptr_int) 226 << Ty << Arg.get()->getSourceRange(); 227 return true; 228 } 229 InitializedEntity Entity = InitializedEntity::InitializeParameter( 230 S.getASTContext(), Ty, /*consume*/ false); 231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 232 if (Arg.isInvalid()) 233 return true; 234 TheCall->setArg(2, Arg.get()); 235 } 236 return false; 237 } 238 239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, 240 CallExpr *TheCall, unsigned SizeIdx, 241 unsigned DstSizeIdx) { 242 if (TheCall->getNumArgs() <= SizeIdx || 243 TheCall->getNumArgs() <= DstSizeIdx) 244 return; 245 246 const Expr *SizeArg = TheCall->getArg(SizeIdx); 247 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 248 249 llvm::APSInt Size, DstSize; 250 251 // find out if both sizes are known at compile time 252 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 253 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 254 return; 255 256 if (Size.ule(DstSize)) 257 return; 258 259 // confirmed overflow so generate the diagnostic. 260 IdentifierInfo *FnName = FDecl->getIdentifier(); 261 SourceLocation SL = TheCall->getLocStart(); 262 SourceRange SR = TheCall->getSourceRange(); 263 264 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName; 265 } 266 267 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 268 if (checkArgCount(S, BuiltinCall, 2)) 269 return true; 270 271 SourceLocation BuiltinLoc = BuiltinCall->getLocStart(); 272 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 273 Expr *Call = BuiltinCall->getArg(0); 274 Expr *Chain = BuiltinCall->getArg(1); 275 276 if (Call->getStmtClass() != Stmt::CallExprClass) { 277 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 278 << Call->getSourceRange(); 279 return true; 280 } 281 282 auto CE = cast<CallExpr>(Call); 283 if (CE->getCallee()->getType()->isBlockPointerType()) { 284 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 285 << Call->getSourceRange(); 286 return true; 287 } 288 289 const Decl *TargetDecl = CE->getCalleeDecl(); 290 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 291 if (FD->getBuiltinID()) { 292 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 293 << Call->getSourceRange(); 294 return true; 295 } 296 297 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 298 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 299 << Call->getSourceRange(); 300 return true; 301 } 302 303 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 304 if (ChainResult.isInvalid()) 305 return true; 306 if (!ChainResult.get()->getType()->isPointerType()) { 307 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 308 << Chain->getSourceRange(); 309 return true; 310 } 311 312 QualType ReturnTy = CE->getCallReturnType(S.Context); 313 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 314 QualType BuiltinTy = S.Context.getFunctionType( 315 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 316 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 317 318 Builtin = 319 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 320 321 BuiltinCall->setType(CE->getType()); 322 BuiltinCall->setValueKind(CE->getValueKind()); 323 BuiltinCall->setObjectKind(CE->getObjectKind()); 324 BuiltinCall->setCallee(Builtin); 325 BuiltinCall->setArg(1, ChainResult.get()); 326 327 return false; 328 } 329 330 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 331 Scope::ScopeFlags NeededScopeFlags, 332 unsigned DiagID) { 333 // Scopes aren't available during instantiation. Fortunately, builtin 334 // functions cannot be template args so they cannot be formed through template 335 // instantiation. Therefore checking once during the parse is sufficient. 336 if (SemaRef.inTemplateInstantiation()) 337 return false; 338 339 Scope *S = SemaRef.getCurScope(); 340 while (S && !S->isSEHExceptScope()) 341 S = S->getParent(); 342 if (!S || !(S->getFlags() & NeededScopeFlags)) { 343 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 344 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 345 << DRE->getDecl()->getIdentifier(); 346 return true; 347 } 348 349 return false; 350 } 351 352 static inline bool isBlockPointer(Expr *Arg) { 353 return Arg->getType()->isBlockPointerType(); 354 } 355 356 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 357 /// void*, which is a requirement of device side enqueue. 358 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 359 const BlockPointerType *BPT = 360 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 361 ArrayRef<QualType> Params = 362 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 363 unsigned ArgCounter = 0; 364 bool IllegalParams = false; 365 // Iterate through the block parameters until either one is found that is not 366 // a local void*, or the block is valid. 367 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 368 I != E; ++I, ++ArgCounter) { 369 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 370 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 371 LangAS::opencl_local) { 372 // Get the location of the error. If a block literal has been passed 373 // (BlockExpr) then we can point straight to the offending argument, 374 // else we just point to the variable reference. 375 SourceLocation ErrorLoc; 376 if (isa<BlockExpr>(BlockArg)) { 377 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 378 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart(); 379 } else if (isa<DeclRefExpr>(BlockArg)) { 380 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart(); 381 } 382 S.Diag(ErrorLoc, 383 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 384 IllegalParams = true; 385 } 386 } 387 388 return IllegalParams; 389 } 390 391 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 392 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 393 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension) 394 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 395 return true; 396 } 397 return false; 398 } 399 400 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 401 if (checkArgCount(S, TheCall, 2)) 402 return true; 403 404 if (checkOpenCLSubgroupExt(S, TheCall)) 405 return true; 406 407 // First argument is an ndrange_t type. 408 Expr *NDRangeArg = TheCall->getArg(0); 409 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 410 S.Diag(NDRangeArg->getLocStart(), 411 diag::err_opencl_builtin_expected_type) 412 << TheCall->getDirectCallee() << "'ndrange_t'"; 413 return true; 414 } 415 416 Expr *BlockArg = TheCall->getArg(1); 417 if (!isBlockPointer(BlockArg)) { 418 S.Diag(BlockArg->getLocStart(), 419 diag::err_opencl_builtin_expected_type) 420 << TheCall->getDirectCallee() << "block"; 421 return true; 422 } 423 return checkOpenCLBlockArgs(S, BlockArg); 424 } 425 426 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 427 /// get_kernel_work_group_size 428 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 429 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 430 if (checkArgCount(S, TheCall, 1)) 431 return true; 432 433 Expr *BlockArg = TheCall->getArg(0); 434 if (!isBlockPointer(BlockArg)) { 435 S.Diag(BlockArg->getLocStart(), 436 diag::err_opencl_builtin_expected_type) 437 << TheCall->getDirectCallee() << "block"; 438 return true; 439 } 440 return checkOpenCLBlockArgs(S, BlockArg); 441 } 442 443 /// Diagnose integer type and any valid implicit conversion to it. 444 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 445 const QualType &IntType); 446 447 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 448 unsigned Start, unsigned End) { 449 bool IllegalParams = false; 450 for (unsigned I = Start; I <= End; ++I) 451 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 452 S.Context.getSizeType()); 453 return IllegalParams; 454 } 455 456 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 457 /// 'local void*' parameter of passed block. 458 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 459 Expr *BlockArg, 460 unsigned NumNonVarArgs) { 461 const BlockPointerType *BPT = 462 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 463 unsigned NumBlockParams = 464 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 465 unsigned TotalNumArgs = TheCall->getNumArgs(); 466 467 // For each argument passed to the block, a corresponding uint needs to 468 // be passed to describe the size of the local memory. 469 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 470 S.Diag(TheCall->getLocStart(), 471 diag::err_opencl_enqueue_kernel_local_size_args); 472 return true; 473 } 474 475 // Check that the sizes of the local memory are specified by integers. 476 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 477 TotalNumArgs - 1); 478 } 479 480 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 481 /// overload formats specified in Table 6.13.17.1. 482 /// int enqueue_kernel(queue_t queue, 483 /// kernel_enqueue_flags_t flags, 484 /// const ndrange_t ndrange, 485 /// void (^block)(void)) 486 /// int enqueue_kernel(queue_t queue, 487 /// kernel_enqueue_flags_t flags, 488 /// const ndrange_t ndrange, 489 /// uint num_events_in_wait_list, 490 /// clk_event_t *event_wait_list, 491 /// clk_event_t *event_ret, 492 /// void (^block)(void)) 493 /// int enqueue_kernel(queue_t queue, 494 /// kernel_enqueue_flags_t flags, 495 /// const ndrange_t ndrange, 496 /// void (^block)(local void*, ...), 497 /// uint size0, ...) 498 /// int enqueue_kernel(queue_t queue, 499 /// kernel_enqueue_flags_t flags, 500 /// const ndrange_t ndrange, 501 /// uint num_events_in_wait_list, 502 /// clk_event_t *event_wait_list, 503 /// clk_event_t *event_ret, 504 /// void (^block)(local void*, ...), 505 /// uint size0, ...) 506 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 507 unsigned NumArgs = TheCall->getNumArgs(); 508 509 if (NumArgs < 4) { 510 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args); 511 return true; 512 } 513 514 Expr *Arg0 = TheCall->getArg(0); 515 Expr *Arg1 = TheCall->getArg(1); 516 Expr *Arg2 = TheCall->getArg(2); 517 Expr *Arg3 = TheCall->getArg(3); 518 519 // First argument always needs to be a queue_t type. 520 if (!Arg0->getType()->isQueueT()) { 521 S.Diag(TheCall->getArg(0)->getLocStart(), 522 diag::err_opencl_builtin_expected_type) 523 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 524 return true; 525 } 526 527 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 528 if (!Arg1->getType()->isIntegerType()) { 529 S.Diag(TheCall->getArg(1)->getLocStart(), 530 diag::err_opencl_builtin_expected_type) 531 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 532 return true; 533 } 534 535 // Third argument is always an ndrange_t type. 536 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 537 S.Diag(TheCall->getArg(2)->getLocStart(), 538 diag::err_opencl_builtin_expected_type) 539 << TheCall->getDirectCallee() << "'ndrange_t'"; 540 return true; 541 } 542 543 // With four arguments, there is only one form that the function could be 544 // called in: no events and no variable arguments. 545 if (NumArgs == 4) { 546 // check that the last argument is the right block type. 547 if (!isBlockPointer(Arg3)) { 548 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type) 549 << TheCall->getDirectCallee() << "block"; 550 return true; 551 } 552 // we have a block type, check the prototype 553 const BlockPointerType *BPT = 554 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 555 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 556 S.Diag(Arg3->getLocStart(), 557 diag::err_opencl_enqueue_kernel_blocks_no_args); 558 return true; 559 } 560 return false; 561 } 562 // we can have block + varargs. 563 if (isBlockPointer(Arg3)) 564 return (checkOpenCLBlockArgs(S, Arg3) || 565 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 566 // last two cases with either exactly 7 args or 7 args and varargs. 567 if (NumArgs >= 7) { 568 // check common block argument. 569 Expr *Arg6 = TheCall->getArg(6); 570 if (!isBlockPointer(Arg6)) { 571 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type) 572 << TheCall->getDirectCallee() << "block"; 573 return true; 574 } 575 if (checkOpenCLBlockArgs(S, Arg6)) 576 return true; 577 578 // Forth argument has to be any integer type. 579 if (!Arg3->getType()->isIntegerType()) { 580 S.Diag(TheCall->getArg(3)->getLocStart(), 581 diag::err_opencl_builtin_expected_type) 582 << TheCall->getDirectCallee() << "integer"; 583 return true; 584 } 585 // check remaining common arguments. 586 Expr *Arg4 = TheCall->getArg(4); 587 Expr *Arg5 = TheCall->getArg(5); 588 589 // Fifth argument is always passed as a pointer to clk_event_t. 590 if (!Arg4->isNullPointerConstant(S.Context, 591 Expr::NPC_ValueDependentIsNotNull) && 592 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 593 S.Diag(TheCall->getArg(4)->getLocStart(), 594 diag::err_opencl_builtin_expected_type) 595 << TheCall->getDirectCallee() 596 << S.Context.getPointerType(S.Context.OCLClkEventTy); 597 return true; 598 } 599 600 // Sixth argument is always passed as a pointer to clk_event_t. 601 if (!Arg5->isNullPointerConstant(S.Context, 602 Expr::NPC_ValueDependentIsNotNull) && 603 !(Arg5->getType()->isPointerType() && 604 Arg5->getType()->getPointeeType()->isClkEventT())) { 605 S.Diag(TheCall->getArg(5)->getLocStart(), 606 diag::err_opencl_builtin_expected_type) 607 << TheCall->getDirectCallee() 608 << S.Context.getPointerType(S.Context.OCLClkEventTy); 609 return true; 610 } 611 612 if (NumArgs == 7) 613 return false; 614 615 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 616 } 617 618 // None of the specific case has been detected, give generic error 619 S.Diag(TheCall->getLocStart(), 620 diag::err_opencl_enqueue_kernel_incorrect_args); 621 return true; 622 } 623 624 /// Returns OpenCL access qual. 625 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 626 return D->getAttr<OpenCLAccessAttr>(); 627 } 628 629 /// Returns true if pipe element type is different from the pointer. 630 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 631 const Expr *Arg0 = Call->getArg(0); 632 // First argument type should always be pipe. 633 if (!Arg0->getType()->isPipeType()) { 634 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 635 << Call->getDirectCallee() << Arg0->getSourceRange(); 636 return true; 637 } 638 OpenCLAccessAttr *AccessQual = 639 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 640 // Validates the access qualifier is compatible with the call. 641 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 642 // read_only and write_only, and assumed to be read_only if no qualifier is 643 // specified. 644 switch (Call->getDirectCallee()->getBuiltinID()) { 645 case Builtin::BIread_pipe: 646 case Builtin::BIreserve_read_pipe: 647 case Builtin::BIcommit_read_pipe: 648 case Builtin::BIwork_group_reserve_read_pipe: 649 case Builtin::BIsub_group_reserve_read_pipe: 650 case Builtin::BIwork_group_commit_read_pipe: 651 case Builtin::BIsub_group_commit_read_pipe: 652 if (!(!AccessQual || AccessQual->isReadOnly())) { 653 S.Diag(Arg0->getLocStart(), 654 diag::err_opencl_builtin_pipe_invalid_access_modifier) 655 << "read_only" << Arg0->getSourceRange(); 656 return true; 657 } 658 break; 659 case Builtin::BIwrite_pipe: 660 case Builtin::BIreserve_write_pipe: 661 case Builtin::BIcommit_write_pipe: 662 case Builtin::BIwork_group_reserve_write_pipe: 663 case Builtin::BIsub_group_reserve_write_pipe: 664 case Builtin::BIwork_group_commit_write_pipe: 665 case Builtin::BIsub_group_commit_write_pipe: 666 if (!(AccessQual && AccessQual->isWriteOnly())) { 667 S.Diag(Arg0->getLocStart(), 668 diag::err_opencl_builtin_pipe_invalid_access_modifier) 669 << "write_only" << Arg0->getSourceRange(); 670 return true; 671 } 672 break; 673 default: 674 break; 675 } 676 return false; 677 } 678 679 /// Returns true if pipe element type is different from the pointer. 680 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 681 const Expr *Arg0 = Call->getArg(0); 682 const Expr *ArgIdx = Call->getArg(Idx); 683 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 684 const QualType EltTy = PipeTy->getElementType(); 685 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 686 // The Idx argument should be a pointer and the type of the pointer and 687 // the type of pipe element should also be the same. 688 if (!ArgTy || 689 !S.Context.hasSameType( 690 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 691 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 692 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 693 << ArgIdx->getType() << ArgIdx->getSourceRange(); 694 return true; 695 } 696 return false; 697 } 698 699 // Performs semantic analysis for the read/write_pipe call. 700 // \param S Reference to the semantic analyzer. 701 // \param Call A pointer to the builtin call. 702 // \return True if a semantic error has been found, false otherwise. 703 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 704 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 705 // functions have two forms. 706 switch (Call->getNumArgs()) { 707 case 2: 708 if (checkOpenCLPipeArg(S, Call)) 709 return true; 710 // The call with 2 arguments should be 711 // read/write_pipe(pipe T, T*). 712 // Check packet type T. 713 if (checkOpenCLPipePacketType(S, Call, 1)) 714 return true; 715 break; 716 717 case 4: { 718 if (checkOpenCLPipeArg(S, Call)) 719 return true; 720 // The call with 4 arguments should be 721 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 722 // Check reserve_id_t. 723 if (!Call->getArg(1)->getType()->isReserveIDT()) { 724 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 725 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 726 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 727 return true; 728 } 729 730 // Check the index. 731 const Expr *Arg2 = Call->getArg(2); 732 if (!Arg2->getType()->isIntegerType() && 733 !Arg2->getType()->isUnsignedIntegerType()) { 734 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 735 << Call->getDirectCallee() << S.Context.UnsignedIntTy 736 << Arg2->getType() << Arg2->getSourceRange(); 737 return true; 738 } 739 740 // Check packet type T. 741 if (checkOpenCLPipePacketType(S, Call, 3)) 742 return true; 743 } break; 744 default: 745 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num) 746 << Call->getDirectCallee() << Call->getSourceRange(); 747 return true; 748 } 749 750 return false; 751 } 752 753 // Performs a semantic analysis on the {work_group_/sub_group_ 754 // /_}reserve_{read/write}_pipe 755 // \param S Reference to the semantic analyzer. 756 // \param Call The call to the builtin function to be analyzed. 757 // \return True if a semantic error was found, false otherwise. 758 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 759 if (checkArgCount(S, Call, 2)) 760 return true; 761 762 if (checkOpenCLPipeArg(S, Call)) 763 return true; 764 765 // Check the reserve size. 766 if (!Call->getArg(1)->getType()->isIntegerType() && 767 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 768 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 769 << Call->getDirectCallee() << S.Context.UnsignedIntTy 770 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 771 return true; 772 } 773 774 // Since return type of reserve_read/write_pipe built-in function is 775 // reserve_id_t, which is not defined in the builtin def file , we used int 776 // as return type and need to override the return type of these functions. 777 Call->setType(S.Context.OCLReserveIDTy); 778 779 return false; 780 } 781 782 // Performs a semantic analysis on {work_group_/sub_group_ 783 // /_}commit_{read/write}_pipe 784 // \param S Reference to the semantic analyzer. 785 // \param Call The call to the builtin function to be analyzed. 786 // \return True if a semantic error was found, false otherwise. 787 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 788 if (checkArgCount(S, Call, 2)) 789 return true; 790 791 if (checkOpenCLPipeArg(S, Call)) 792 return true; 793 794 // Check reserve_id_t. 795 if (!Call->getArg(1)->getType()->isReserveIDT()) { 796 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg) 797 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 798 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 799 return true; 800 } 801 802 return false; 803 } 804 805 // Performs a semantic analysis on the call to built-in Pipe 806 // Query Functions. 807 // \param S Reference to the semantic analyzer. 808 // \param Call The call to the builtin function to be analyzed. 809 // \return True if a semantic error was found, false otherwise. 810 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 811 if (checkArgCount(S, Call, 1)) 812 return true; 813 814 if (!Call->getArg(0)->getType()->isPipeType()) { 815 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg) 816 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 817 return true; 818 } 819 820 return false; 821 } 822 823 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 824 // Performs semantic analysis for the to_global/local/private call. 825 // \param S Reference to the semantic analyzer. 826 // \param BuiltinID ID of the builtin function. 827 // \param Call A pointer to the builtin call. 828 // \return True if a semantic error has been found, false otherwise. 829 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 830 CallExpr *Call) { 831 if (Call->getNumArgs() != 1) { 832 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num) 833 << Call->getDirectCallee() << Call->getSourceRange(); 834 return true; 835 } 836 837 auto RT = Call->getArg(0)->getType(); 838 if (!RT->isPointerType() || RT->getPointeeType() 839 .getAddressSpace() == LangAS::opencl_constant) { 840 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg) 841 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 842 return true; 843 } 844 845 RT = RT->getPointeeType(); 846 auto Qual = RT.getQualifiers(); 847 switch (BuiltinID) { 848 case Builtin::BIto_global: 849 Qual.setAddressSpace(LangAS::opencl_global); 850 break; 851 case Builtin::BIto_local: 852 Qual.setAddressSpace(LangAS::opencl_local); 853 break; 854 case Builtin::BIto_private: 855 Qual.setAddressSpace(LangAS::opencl_private); 856 break; 857 default: 858 llvm_unreachable("Invalid builtin function"); 859 } 860 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 861 RT.getUnqualifiedType(), Qual))); 862 863 return false; 864 } 865 866 // Emit an error and return true if the current architecture is not in the list 867 // of supported architectures. 868 static bool 869 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 870 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 871 llvm::Triple::ArchType CurArch = 872 S.getASTContext().getTargetInfo().getTriple().getArch(); 873 if (llvm::is_contained(SupportedArchs, CurArch)) 874 return false; 875 S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported) 876 << TheCall->getSourceRange(); 877 return true; 878 } 879 880 ExprResult 881 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 882 CallExpr *TheCall) { 883 ExprResult TheCallResult(TheCall); 884 885 // Find out if any arguments are required to be integer constant expressions. 886 unsigned ICEArguments = 0; 887 ASTContext::GetBuiltinTypeError Error; 888 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 889 if (Error != ASTContext::GE_None) 890 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 891 892 // If any arguments are required to be ICE's, check and diagnose. 893 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 894 // Skip arguments not required to be ICE's. 895 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 896 897 llvm::APSInt Result; 898 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 899 return true; 900 ICEArguments &= ~(1 << ArgNo); 901 } 902 903 switch (BuiltinID) { 904 case Builtin::BI__builtin___CFStringMakeConstantString: 905 assert(TheCall->getNumArgs() == 1 && 906 "Wrong # arguments to builtin CFStringMakeConstantString"); 907 if (CheckObjCString(TheCall->getArg(0))) 908 return ExprError(); 909 break; 910 case Builtin::BI__builtin_ms_va_start: 911 case Builtin::BI__builtin_stdarg_start: 912 case Builtin::BI__builtin_va_start: 913 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 914 return ExprError(); 915 break; 916 case Builtin::BI__va_start: { 917 switch (Context.getTargetInfo().getTriple().getArch()) { 918 case llvm::Triple::arm: 919 case llvm::Triple::thumb: 920 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 921 return ExprError(); 922 break; 923 default: 924 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 925 return ExprError(); 926 break; 927 } 928 break; 929 } 930 931 // The acquire, release, and no fence variants are ARM and AArch64 only. 932 case Builtin::BI_interlockedbittestandset_acq: 933 case Builtin::BI_interlockedbittestandset_rel: 934 case Builtin::BI_interlockedbittestandset_nf: 935 case Builtin::BI_interlockedbittestandreset_acq: 936 case Builtin::BI_interlockedbittestandreset_rel: 937 case Builtin::BI_interlockedbittestandreset_nf: 938 if (CheckBuiltinTargetSupport( 939 *this, BuiltinID, TheCall, 940 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 941 return ExprError(); 942 break; 943 944 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 945 case Builtin::BI_bittest64: 946 case Builtin::BI_bittestandcomplement64: 947 case Builtin::BI_bittestandreset64: 948 case Builtin::BI_bittestandset64: 949 case Builtin::BI_interlockedbittestandreset64: 950 case Builtin::BI_interlockedbittestandset64: 951 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 952 {llvm::Triple::x86_64, llvm::Triple::arm, 953 llvm::Triple::thumb, llvm::Triple::aarch64})) 954 return ExprError(); 955 break; 956 957 case Builtin::BI__builtin_isgreater: 958 case Builtin::BI__builtin_isgreaterequal: 959 case Builtin::BI__builtin_isless: 960 case Builtin::BI__builtin_islessequal: 961 case Builtin::BI__builtin_islessgreater: 962 case Builtin::BI__builtin_isunordered: 963 if (SemaBuiltinUnorderedCompare(TheCall)) 964 return ExprError(); 965 break; 966 case Builtin::BI__builtin_fpclassify: 967 if (SemaBuiltinFPClassification(TheCall, 6)) 968 return ExprError(); 969 break; 970 case Builtin::BI__builtin_isfinite: 971 case Builtin::BI__builtin_isinf: 972 case Builtin::BI__builtin_isinf_sign: 973 case Builtin::BI__builtin_isnan: 974 case Builtin::BI__builtin_isnormal: 975 if (SemaBuiltinFPClassification(TheCall, 1)) 976 return ExprError(); 977 break; 978 case Builtin::BI__builtin_shufflevector: 979 return SemaBuiltinShuffleVector(TheCall); 980 // TheCall will be freed by the smart pointer here, but that's fine, since 981 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 982 case Builtin::BI__builtin_prefetch: 983 if (SemaBuiltinPrefetch(TheCall)) 984 return ExprError(); 985 break; 986 case Builtin::BI__builtin_alloca_with_align: 987 if (SemaBuiltinAllocaWithAlign(TheCall)) 988 return ExprError(); 989 break; 990 case Builtin::BI__assume: 991 case Builtin::BI__builtin_assume: 992 if (SemaBuiltinAssume(TheCall)) 993 return ExprError(); 994 break; 995 case Builtin::BI__builtin_assume_aligned: 996 if (SemaBuiltinAssumeAligned(TheCall)) 997 return ExprError(); 998 break; 999 case Builtin::BI__builtin_object_size: 1000 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1001 return ExprError(); 1002 break; 1003 case Builtin::BI__builtin_longjmp: 1004 if (SemaBuiltinLongjmp(TheCall)) 1005 return ExprError(); 1006 break; 1007 case Builtin::BI__builtin_setjmp: 1008 if (SemaBuiltinSetjmp(TheCall)) 1009 return ExprError(); 1010 break; 1011 case Builtin::BI_setjmp: 1012 case Builtin::BI_setjmpex: 1013 if (checkArgCount(*this, TheCall, 1)) 1014 return true; 1015 break; 1016 case Builtin::BI__builtin_classify_type: 1017 if (checkArgCount(*this, TheCall, 1)) return true; 1018 TheCall->setType(Context.IntTy); 1019 break; 1020 case Builtin::BI__builtin_constant_p: 1021 if (checkArgCount(*this, TheCall, 1)) return true; 1022 TheCall->setType(Context.IntTy); 1023 break; 1024 case Builtin::BI__sync_fetch_and_add: 1025 case Builtin::BI__sync_fetch_and_add_1: 1026 case Builtin::BI__sync_fetch_and_add_2: 1027 case Builtin::BI__sync_fetch_and_add_4: 1028 case Builtin::BI__sync_fetch_and_add_8: 1029 case Builtin::BI__sync_fetch_and_add_16: 1030 case Builtin::BI__sync_fetch_and_sub: 1031 case Builtin::BI__sync_fetch_and_sub_1: 1032 case Builtin::BI__sync_fetch_and_sub_2: 1033 case Builtin::BI__sync_fetch_and_sub_4: 1034 case Builtin::BI__sync_fetch_and_sub_8: 1035 case Builtin::BI__sync_fetch_and_sub_16: 1036 case Builtin::BI__sync_fetch_and_or: 1037 case Builtin::BI__sync_fetch_and_or_1: 1038 case Builtin::BI__sync_fetch_and_or_2: 1039 case Builtin::BI__sync_fetch_and_or_4: 1040 case Builtin::BI__sync_fetch_and_or_8: 1041 case Builtin::BI__sync_fetch_and_or_16: 1042 case Builtin::BI__sync_fetch_and_and: 1043 case Builtin::BI__sync_fetch_and_and_1: 1044 case Builtin::BI__sync_fetch_and_and_2: 1045 case Builtin::BI__sync_fetch_and_and_4: 1046 case Builtin::BI__sync_fetch_and_and_8: 1047 case Builtin::BI__sync_fetch_and_and_16: 1048 case Builtin::BI__sync_fetch_and_xor: 1049 case Builtin::BI__sync_fetch_and_xor_1: 1050 case Builtin::BI__sync_fetch_and_xor_2: 1051 case Builtin::BI__sync_fetch_and_xor_4: 1052 case Builtin::BI__sync_fetch_and_xor_8: 1053 case Builtin::BI__sync_fetch_and_xor_16: 1054 case Builtin::BI__sync_fetch_and_nand: 1055 case Builtin::BI__sync_fetch_and_nand_1: 1056 case Builtin::BI__sync_fetch_and_nand_2: 1057 case Builtin::BI__sync_fetch_and_nand_4: 1058 case Builtin::BI__sync_fetch_and_nand_8: 1059 case Builtin::BI__sync_fetch_and_nand_16: 1060 case Builtin::BI__sync_add_and_fetch: 1061 case Builtin::BI__sync_add_and_fetch_1: 1062 case Builtin::BI__sync_add_and_fetch_2: 1063 case Builtin::BI__sync_add_and_fetch_4: 1064 case Builtin::BI__sync_add_and_fetch_8: 1065 case Builtin::BI__sync_add_and_fetch_16: 1066 case Builtin::BI__sync_sub_and_fetch: 1067 case Builtin::BI__sync_sub_and_fetch_1: 1068 case Builtin::BI__sync_sub_and_fetch_2: 1069 case Builtin::BI__sync_sub_and_fetch_4: 1070 case Builtin::BI__sync_sub_and_fetch_8: 1071 case Builtin::BI__sync_sub_and_fetch_16: 1072 case Builtin::BI__sync_and_and_fetch: 1073 case Builtin::BI__sync_and_and_fetch_1: 1074 case Builtin::BI__sync_and_and_fetch_2: 1075 case Builtin::BI__sync_and_and_fetch_4: 1076 case Builtin::BI__sync_and_and_fetch_8: 1077 case Builtin::BI__sync_and_and_fetch_16: 1078 case Builtin::BI__sync_or_and_fetch: 1079 case Builtin::BI__sync_or_and_fetch_1: 1080 case Builtin::BI__sync_or_and_fetch_2: 1081 case Builtin::BI__sync_or_and_fetch_4: 1082 case Builtin::BI__sync_or_and_fetch_8: 1083 case Builtin::BI__sync_or_and_fetch_16: 1084 case Builtin::BI__sync_xor_and_fetch: 1085 case Builtin::BI__sync_xor_and_fetch_1: 1086 case Builtin::BI__sync_xor_and_fetch_2: 1087 case Builtin::BI__sync_xor_and_fetch_4: 1088 case Builtin::BI__sync_xor_and_fetch_8: 1089 case Builtin::BI__sync_xor_and_fetch_16: 1090 case Builtin::BI__sync_nand_and_fetch: 1091 case Builtin::BI__sync_nand_and_fetch_1: 1092 case Builtin::BI__sync_nand_and_fetch_2: 1093 case Builtin::BI__sync_nand_and_fetch_4: 1094 case Builtin::BI__sync_nand_and_fetch_8: 1095 case Builtin::BI__sync_nand_and_fetch_16: 1096 case Builtin::BI__sync_val_compare_and_swap: 1097 case Builtin::BI__sync_val_compare_and_swap_1: 1098 case Builtin::BI__sync_val_compare_and_swap_2: 1099 case Builtin::BI__sync_val_compare_and_swap_4: 1100 case Builtin::BI__sync_val_compare_and_swap_8: 1101 case Builtin::BI__sync_val_compare_and_swap_16: 1102 case Builtin::BI__sync_bool_compare_and_swap: 1103 case Builtin::BI__sync_bool_compare_and_swap_1: 1104 case Builtin::BI__sync_bool_compare_and_swap_2: 1105 case Builtin::BI__sync_bool_compare_and_swap_4: 1106 case Builtin::BI__sync_bool_compare_and_swap_8: 1107 case Builtin::BI__sync_bool_compare_and_swap_16: 1108 case Builtin::BI__sync_lock_test_and_set: 1109 case Builtin::BI__sync_lock_test_and_set_1: 1110 case Builtin::BI__sync_lock_test_and_set_2: 1111 case Builtin::BI__sync_lock_test_and_set_4: 1112 case Builtin::BI__sync_lock_test_and_set_8: 1113 case Builtin::BI__sync_lock_test_and_set_16: 1114 case Builtin::BI__sync_lock_release: 1115 case Builtin::BI__sync_lock_release_1: 1116 case Builtin::BI__sync_lock_release_2: 1117 case Builtin::BI__sync_lock_release_4: 1118 case Builtin::BI__sync_lock_release_8: 1119 case Builtin::BI__sync_lock_release_16: 1120 case Builtin::BI__sync_swap: 1121 case Builtin::BI__sync_swap_1: 1122 case Builtin::BI__sync_swap_2: 1123 case Builtin::BI__sync_swap_4: 1124 case Builtin::BI__sync_swap_8: 1125 case Builtin::BI__sync_swap_16: 1126 return SemaBuiltinAtomicOverloaded(TheCallResult); 1127 case Builtin::BI__builtin_nontemporal_load: 1128 case Builtin::BI__builtin_nontemporal_store: 1129 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1130 #define BUILTIN(ID, TYPE, ATTRS) 1131 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1132 case Builtin::BI##ID: \ 1133 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1134 #include "clang/Basic/Builtins.def" 1135 case Builtin::BI__annotation: 1136 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1137 return ExprError(); 1138 break; 1139 case Builtin::BI__builtin_annotation: 1140 if (SemaBuiltinAnnotation(*this, TheCall)) 1141 return ExprError(); 1142 break; 1143 case Builtin::BI__builtin_addressof: 1144 if (SemaBuiltinAddressof(*this, TheCall)) 1145 return ExprError(); 1146 break; 1147 case Builtin::BI__builtin_add_overflow: 1148 case Builtin::BI__builtin_sub_overflow: 1149 case Builtin::BI__builtin_mul_overflow: 1150 if (SemaBuiltinOverflow(*this, TheCall)) 1151 return ExprError(); 1152 break; 1153 case Builtin::BI__builtin_operator_new: 1154 case Builtin::BI__builtin_operator_delete: { 1155 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1156 ExprResult Res = 1157 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1158 if (Res.isInvalid()) 1159 CorrectDelayedTyposInExpr(TheCallResult.get()); 1160 return Res; 1161 } 1162 case Builtin::BI__builtin_dump_struct: { 1163 // We first want to ensure we are called with 2 arguments 1164 if (checkArgCount(*this, TheCall, 2)) 1165 return ExprError(); 1166 // Ensure that the first argument is of type 'struct XX *' 1167 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1168 const QualType PtrArgType = PtrArg->getType(); 1169 if (!PtrArgType->isPointerType() || 1170 !PtrArgType->getPointeeType()->isRecordType()) { 1171 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1172 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1173 << "structure pointer"; 1174 return ExprError(); 1175 } 1176 1177 // Ensure that the second argument is of type 'FunctionType' 1178 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1179 const QualType FnPtrArgType = FnPtrArg->getType(); 1180 if (!FnPtrArgType->isPointerType()) { 1181 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1182 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1183 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1184 return ExprError(); 1185 } 1186 1187 const auto *FuncType = 1188 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1189 1190 if (!FuncType) { 1191 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1192 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1193 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1194 return ExprError(); 1195 } 1196 1197 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1198 if (!FT->getNumParams()) { 1199 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1200 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1201 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1202 return ExprError(); 1203 } 1204 QualType PT = FT->getParamType(0); 1205 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1206 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1207 !PT->getPointeeType().isConstQualified()) { 1208 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1209 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1210 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1211 return ExprError(); 1212 } 1213 } 1214 1215 TheCall->setType(Context.IntTy); 1216 break; 1217 } 1218 1219 // check secure string manipulation functions where overflows 1220 // are detectable at compile time 1221 case Builtin::BI__builtin___memcpy_chk: 1222 case Builtin::BI__builtin___memmove_chk: 1223 case Builtin::BI__builtin___memset_chk: 1224 case Builtin::BI__builtin___strlcat_chk: 1225 case Builtin::BI__builtin___strlcpy_chk: 1226 case Builtin::BI__builtin___strncat_chk: 1227 case Builtin::BI__builtin___strncpy_chk: 1228 case Builtin::BI__builtin___stpncpy_chk: 1229 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1230 break; 1231 case Builtin::BI__builtin___memccpy_chk: 1232 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1233 break; 1234 case Builtin::BI__builtin___snprintf_chk: 1235 case Builtin::BI__builtin___vsnprintf_chk: 1236 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1237 break; 1238 case Builtin::BI__builtin_call_with_static_chain: 1239 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1240 return ExprError(); 1241 break; 1242 case Builtin::BI__exception_code: 1243 case Builtin::BI_exception_code: 1244 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1245 diag::err_seh___except_block)) 1246 return ExprError(); 1247 break; 1248 case Builtin::BI__exception_info: 1249 case Builtin::BI_exception_info: 1250 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1251 diag::err_seh___except_filter)) 1252 return ExprError(); 1253 break; 1254 case Builtin::BI__GetExceptionInfo: 1255 if (checkArgCount(*this, TheCall, 1)) 1256 return ExprError(); 1257 1258 if (CheckCXXThrowOperand( 1259 TheCall->getLocStart(), 1260 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1261 TheCall)) 1262 return ExprError(); 1263 1264 TheCall->setType(Context.VoidPtrTy); 1265 break; 1266 // OpenCL v2.0, s6.13.16 - Pipe functions 1267 case Builtin::BIread_pipe: 1268 case Builtin::BIwrite_pipe: 1269 // Since those two functions are declared with var args, we need a semantic 1270 // check for the argument. 1271 if (SemaBuiltinRWPipe(*this, TheCall)) 1272 return ExprError(); 1273 TheCall->setType(Context.IntTy); 1274 break; 1275 case Builtin::BIreserve_read_pipe: 1276 case Builtin::BIreserve_write_pipe: 1277 case Builtin::BIwork_group_reserve_read_pipe: 1278 case Builtin::BIwork_group_reserve_write_pipe: 1279 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1280 return ExprError(); 1281 break; 1282 case Builtin::BIsub_group_reserve_read_pipe: 1283 case Builtin::BIsub_group_reserve_write_pipe: 1284 if (checkOpenCLSubgroupExt(*this, TheCall) || 1285 SemaBuiltinReserveRWPipe(*this, TheCall)) 1286 return ExprError(); 1287 break; 1288 case Builtin::BIcommit_read_pipe: 1289 case Builtin::BIcommit_write_pipe: 1290 case Builtin::BIwork_group_commit_read_pipe: 1291 case Builtin::BIwork_group_commit_write_pipe: 1292 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1293 return ExprError(); 1294 break; 1295 case Builtin::BIsub_group_commit_read_pipe: 1296 case Builtin::BIsub_group_commit_write_pipe: 1297 if (checkOpenCLSubgroupExt(*this, TheCall) || 1298 SemaBuiltinCommitRWPipe(*this, TheCall)) 1299 return ExprError(); 1300 break; 1301 case Builtin::BIget_pipe_num_packets: 1302 case Builtin::BIget_pipe_max_packets: 1303 if (SemaBuiltinPipePackets(*this, TheCall)) 1304 return ExprError(); 1305 TheCall->setType(Context.UnsignedIntTy); 1306 break; 1307 case Builtin::BIto_global: 1308 case Builtin::BIto_local: 1309 case Builtin::BIto_private: 1310 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1311 return ExprError(); 1312 break; 1313 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1314 case Builtin::BIenqueue_kernel: 1315 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1316 return ExprError(); 1317 break; 1318 case Builtin::BIget_kernel_work_group_size: 1319 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1320 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1321 return ExprError(); 1322 break; 1323 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1324 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1325 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1326 return ExprError(); 1327 break; 1328 case Builtin::BI__builtin_os_log_format: 1329 case Builtin::BI__builtin_os_log_format_buffer_size: 1330 if (SemaBuiltinOSLogFormat(TheCall)) 1331 return ExprError(); 1332 break; 1333 } 1334 1335 // Since the target specific builtins for each arch overlap, only check those 1336 // of the arch we are compiling for. 1337 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1338 switch (Context.getTargetInfo().getTriple().getArch()) { 1339 case llvm::Triple::arm: 1340 case llvm::Triple::armeb: 1341 case llvm::Triple::thumb: 1342 case llvm::Triple::thumbeb: 1343 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1344 return ExprError(); 1345 break; 1346 case llvm::Triple::aarch64: 1347 case llvm::Triple::aarch64_be: 1348 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1349 return ExprError(); 1350 break; 1351 case llvm::Triple::hexagon: 1352 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1353 return ExprError(); 1354 break; 1355 case llvm::Triple::mips: 1356 case llvm::Triple::mipsel: 1357 case llvm::Triple::mips64: 1358 case llvm::Triple::mips64el: 1359 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1360 return ExprError(); 1361 break; 1362 case llvm::Triple::systemz: 1363 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1364 return ExprError(); 1365 break; 1366 case llvm::Triple::x86: 1367 case llvm::Triple::x86_64: 1368 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1369 return ExprError(); 1370 break; 1371 case llvm::Triple::ppc: 1372 case llvm::Triple::ppc64: 1373 case llvm::Triple::ppc64le: 1374 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1375 return ExprError(); 1376 break; 1377 default: 1378 break; 1379 } 1380 } 1381 1382 return TheCallResult; 1383 } 1384 1385 // Get the valid immediate range for the specified NEON type code. 1386 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1387 NeonTypeFlags Type(t); 1388 int IsQuad = ForceQuad ? true : Type.isQuad(); 1389 switch (Type.getEltType()) { 1390 case NeonTypeFlags::Int8: 1391 case NeonTypeFlags::Poly8: 1392 return shift ? 7 : (8 << IsQuad) - 1; 1393 case NeonTypeFlags::Int16: 1394 case NeonTypeFlags::Poly16: 1395 return shift ? 15 : (4 << IsQuad) - 1; 1396 case NeonTypeFlags::Int32: 1397 return shift ? 31 : (2 << IsQuad) - 1; 1398 case NeonTypeFlags::Int64: 1399 case NeonTypeFlags::Poly64: 1400 return shift ? 63 : (1 << IsQuad) - 1; 1401 case NeonTypeFlags::Poly128: 1402 return shift ? 127 : (1 << IsQuad) - 1; 1403 case NeonTypeFlags::Float16: 1404 assert(!shift && "cannot shift float types!"); 1405 return (4 << IsQuad) - 1; 1406 case NeonTypeFlags::Float32: 1407 assert(!shift && "cannot shift float types!"); 1408 return (2 << IsQuad) - 1; 1409 case NeonTypeFlags::Float64: 1410 assert(!shift && "cannot shift float types!"); 1411 return (1 << IsQuad) - 1; 1412 } 1413 llvm_unreachable("Invalid NeonTypeFlag!"); 1414 } 1415 1416 /// getNeonEltType - Return the QualType corresponding to the elements of 1417 /// the vector type specified by the NeonTypeFlags. This is used to check 1418 /// the pointer arguments for Neon load/store intrinsics. 1419 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1420 bool IsPolyUnsigned, bool IsInt64Long) { 1421 switch (Flags.getEltType()) { 1422 case NeonTypeFlags::Int8: 1423 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1424 case NeonTypeFlags::Int16: 1425 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1426 case NeonTypeFlags::Int32: 1427 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1428 case NeonTypeFlags::Int64: 1429 if (IsInt64Long) 1430 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1431 else 1432 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1433 : Context.LongLongTy; 1434 case NeonTypeFlags::Poly8: 1435 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1436 case NeonTypeFlags::Poly16: 1437 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1438 case NeonTypeFlags::Poly64: 1439 if (IsInt64Long) 1440 return Context.UnsignedLongTy; 1441 else 1442 return Context.UnsignedLongLongTy; 1443 case NeonTypeFlags::Poly128: 1444 break; 1445 case NeonTypeFlags::Float16: 1446 return Context.HalfTy; 1447 case NeonTypeFlags::Float32: 1448 return Context.FloatTy; 1449 case NeonTypeFlags::Float64: 1450 return Context.DoubleTy; 1451 } 1452 llvm_unreachable("Invalid NeonTypeFlag!"); 1453 } 1454 1455 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1456 llvm::APSInt Result; 1457 uint64_t mask = 0; 1458 unsigned TV = 0; 1459 int PtrArgNum = -1; 1460 bool HasConstPtr = false; 1461 switch (BuiltinID) { 1462 #define GET_NEON_OVERLOAD_CHECK 1463 #include "clang/Basic/arm_neon.inc" 1464 #include "clang/Basic/arm_fp16.inc" 1465 #undef GET_NEON_OVERLOAD_CHECK 1466 } 1467 1468 // For NEON intrinsics which are overloaded on vector element type, validate 1469 // the immediate which specifies which variant to emit. 1470 unsigned ImmArg = TheCall->getNumArgs()-1; 1471 if (mask) { 1472 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1473 return true; 1474 1475 TV = Result.getLimitedValue(64); 1476 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1477 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1478 << TheCall->getArg(ImmArg)->getSourceRange(); 1479 } 1480 1481 if (PtrArgNum >= 0) { 1482 // Check that pointer arguments have the specified type. 1483 Expr *Arg = TheCall->getArg(PtrArgNum); 1484 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1485 Arg = ICE->getSubExpr(); 1486 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1487 QualType RHSTy = RHS.get()->getType(); 1488 1489 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1490 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1491 Arch == llvm::Triple::aarch64_be; 1492 bool IsInt64Long = 1493 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1494 QualType EltTy = 1495 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1496 if (HasConstPtr) 1497 EltTy = EltTy.withConst(); 1498 QualType LHSTy = Context.getPointerType(EltTy); 1499 AssignConvertType ConvTy; 1500 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1501 if (RHS.isInvalid()) 1502 return true; 1503 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1504 RHS.get(), AA_Assigning)) 1505 return true; 1506 } 1507 1508 // For NEON intrinsics which take an immediate value as part of the 1509 // instruction, range check them here. 1510 unsigned i = 0, l = 0, u = 0; 1511 switch (BuiltinID) { 1512 default: 1513 return false; 1514 #define GET_NEON_IMMEDIATE_CHECK 1515 #include "clang/Basic/arm_neon.inc" 1516 #include "clang/Basic/arm_fp16.inc" 1517 #undef GET_NEON_IMMEDIATE_CHECK 1518 } 1519 1520 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1521 } 1522 1523 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1524 unsigned MaxWidth) { 1525 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1526 BuiltinID == ARM::BI__builtin_arm_ldaex || 1527 BuiltinID == ARM::BI__builtin_arm_strex || 1528 BuiltinID == ARM::BI__builtin_arm_stlex || 1529 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1530 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1531 BuiltinID == AArch64::BI__builtin_arm_strex || 1532 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1533 "unexpected ARM builtin"); 1534 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1535 BuiltinID == ARM::BI__builtin_arm_ldaex || 1536 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1537 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1538 1539 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1540 1541 // Ensure that we have the proper number of arguments. 1542 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1543 return true; 1544 1545 // Inspect the pointer argument of the atomic builtin. This should always be 1546 // a pointer type, whose element is an integral scalar or pointer type. 1547 // Because it is a pointer type, we don't have to worry about any implicit 1548 // casts here. 1549 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1550 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1551 if (PointerArgRes.isInvalid()) 1552 return true; 1553 PointerArg = PointerArgRes.get(); 1554 1555 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1556 if (!pointerType) { 1557 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1558 << PointerArg->getType() << PointerArg->getSourceRange(); 1559 return true; 1560 } 1561 1562 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1563 // task is to insert the appropriate casts into the AST. First work out just 1564 // what the appropriate type is. 1565 QualType ValType = pointerType->getPointeeType(); 1566 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1567 if (IsLdrex) 1568 AddrType.addConst(); 1569 1570 // Issue a warning if the cast is dodgy. 1571 CastKind CastNeeded = CK_NoOp; 1572 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1573 CastNeeded = CK_BitCast; 1574 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1575 << PointerArg->getType() 1576 << Context.getPointerType(AddrType) 1577 << AA_Passing << PointerArg->getSourceRange(); 1578 } 1579 1580 // Finally, do the cast and replace the argument with the corrected version. 1581 AddrType = Context.getPointerType(AddrType); 1582 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1583 if (PointerArgRes.isInvalid()) 1584 return true; 1585 PointerArg = PointerArgRes.get(); 1586 1587 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1588 1589 // In general, we allow ints, floats and pointers to be loaded and stored. 1590 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1591 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1592 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1593 << PointerArg->getType() << PointerArg->getSourceRange(); 1594 return true; 1595 } 1596 1597 // But ARM doesn't have instructions to deal with 128-bit versions. 1598 if (Context.getTypeSize(ValType) > MaxWidth) { 1599 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1600 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1601 << PointerArg->getType() << PointerArg->getSourceRange(); 1602 return true; 1603 } 1604 1605 switch (ValType.getObjCLifetime()) { 1606 case Qualifiers::OCL_None: 1607 case Qualifiers::OCL_ExplicitNone: 1608 // okay 1609 break; 1610 1611 case Qualifiers::OCL_Weak: 1612 case Qualifiers::OCL_Strong: 1613 case Qualifiers::OCL_Autoreleasing: 1614 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1615 << ValType << PointerArg->getSourceRange(); 1616 return true; 1617 } 1618 1619 if (IsLdrex) { 1620 TheCall->setType(ValType); 1621 return false; 1622 } 1623 1624 // Initialize the argument to be stored. 1625 ExprResult ValArg = TheCall->getArg(0); 1626 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1627 Context, ValType, /*consume*/ false); 1628 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1629 if (ValArg.isInvalid()) 1630 return true; 1631 TheCall->setArg(0, ValArg.get()); 1632 1633 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1634 // but the custom checker bypasses all default analysis. 1635 TheCall->setType(Context.IntTy); 1636 return false; 1637 } 1638 1639 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1640 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1641 BuiltinID == ARM::BI__builtin_arm_ldaex || 1642 BuiltinID == ARM::BI__builtin_arm_strex || 1643 BuiltinID == ARM::BI__builtin_arm_stlex) { 1644 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1645 } 1646 1647 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1648 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1649 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1650 } 1651 1652 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1653 BuiltinID == ARM::BI__builtin_arm_wsr64) 1654 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1655 1656 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1657 BuiltinID == ARM::BI__builtin_arm_rsrp || 1658 BuiltinID == ARM::BI__builtin_arm_wsr || 1659 BuiltinID == ARM::BI__builtin_arm_wsrp) 1660 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1661 1662 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1663 return true; 1664 1665 // For intrinsics which take an immediate value as part of the instruction, 1666 // range check them here. 1667 // FIXME: VFP Intrinsics should error if VFP not present. 1668 switch (BuiltinID) { 1669 default: return false; 1670 case ARM::BI__builtin_arm_ssat: 1671 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1672 case ARM::BI__builtin_arm_usat: 1673 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1674 case ARM::BI__builtin_arm_ssat16: 1675 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1676 case ARM::BI__builtin_arm_usat16: 1677 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1678 case ARM::BI__builtin_arm_vcvtr_f: 1679 case ARM::BI__builtin_arm_vcvtr_d: 1680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1681 case ARM::BI__builtin_arm_dmb: 1682 case ARM::BI__builtin_arm_dsb: 1683 case ARM::BI__builtin_arm_isb: 1684 case ARM::BI__builtin_arm_dbg: 1685 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1686 } 1687 } 1688 1689 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1690 CallExpr *TheCall) { 1691 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1692 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1693 BuiltinID == AArch64::BI__builtin_arm_strex || 1694 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1695 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1696 } 1697 1698 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1699 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1700 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1701 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1702 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1703 } 1704 1705 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1706 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1707 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1708 1709 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1710 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1711 BuiltinID == AArch64::BI__builtin_arm_wsr || 1712 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1713 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1714 1715 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1716 return true; 1717 1718 // For intrinsics which take an immediate value as part of the instruction, 1719 // range check them here. 1720 unsigned i = 0, l = 0, u = 0; 1721 switch (BuiltinID) { 1722 default: return false; 1723 case AArch64::BI__builtin_arm_dmb: 1724 case AArch64::BI__builtin_arm_dsb: 1725 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1726 } 1727 1728 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1729 } 1730 1731 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 1732 CallExpr *TheCall) { 1733 struct ArgInfo { 1734 ArgInfo(unsigned O, bool S, unsigned W, unsigned A) 1735 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {} 1736 unsigned OpNum = 0; 1737 bool IsSigned = false; 1738 unsigned BitWidth = 0; 1739 unsigned Align = 0; 1740 }; 1741 1742 static const std::map<unsigned, std::vector<ArgInfo>> Infos = { 1743 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 1744 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 1745 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 1746 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 1747 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 1748 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 1749 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 1750 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 1751 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 1752 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 1753 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 1754 1755 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 1756 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 1757 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 1758 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 1759 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 1760 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 1761 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 1762 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 1763 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 1764 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 1765 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 1766 1767 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 1768 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 1769 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 1770 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 1771 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 1772 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 1773 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 1774 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 1775 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 1776 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 1777 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 1778 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 1779 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 1780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 1781 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 1782 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 1783 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 1784 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 1785 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 1786 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 1787 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 1788 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 1789 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 1790 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 1791 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 1792 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 1793 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 1794 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 1795 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 1796 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 1797 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 1798 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 1799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 1800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 1801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 1802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 1803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 1804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 1805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 1806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 1807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 1808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 1809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 1810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 1811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 1812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 1813 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 1814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 1815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 1819 {{ 1, false, 6, 0 }} }, 1820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 1821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 1822 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 1823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 1824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 1825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 1826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 1827 {{ 1, false, 5, 0 }} }, 1828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 1829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 1830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 1831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 1832 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 1833 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 1834 { 2, false, 5, 0 }} }, 1835 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 1836 { 2, false, 6, 0 }} }, 1837 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 1838 { 3, false, 5, 0 }} }, 1839 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 1840 { 3, false, 6, 0 }} }, 1841 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 1842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 1843 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 1844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 1845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 1846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 1847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 1848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 1849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 1850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 1851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 1852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 1853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 1854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 1855 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 1856 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 1857 {{ 2, false, 4, 0 }, 1858 { 3, false, 5, 0 }} }, 1859 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 1860 {{ 2, false, 4, 0 }, 1861 { 3, false, 5, 0 }} }, 1862 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 1863 {{ 2, false, 4, 0 }, 1864 { 3, false, 5, 0 }} }, 1865 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 1866 {{ 2, false, 4, 0 }, 1867 { 3, false, 5, 0 }} }, 1868 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 1869 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 1870 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 1871 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 1872 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 1873 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 1874 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 1875 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 1876 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 1877 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 1878 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 1879 { 2, false, 5, 0 }} }, 1880 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 1881 { 2, false, 6, 0 }} }, 1882 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 1883 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 1884 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 1885 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 1886 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 1887 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 1888 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 1889 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 1890 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 1891 {{ 1, false, 4, 0 }} }, 1892 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 1893 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 1894 {{ 1, false, 4, 0 }} }, 1895 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 1896 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 1897 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 1898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 1899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 1900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 1901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 1902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 1903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 1904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 1905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 1906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 1915 {{ 3, false, 1, 0 }} }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 1920 {{ 3, false, 1, 0 }} }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 1925 {{ 3, false, 1, 0 }} }, 1926 }; 1927 1928 auto F = Infos.find(BuiltinID); 1929 if (F == Infos.end()) 1930 return false; 1931 1932 bool Error = false; 1933 1934 for (const ArgInfo &A : F->second) { 1935 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0; 1936 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1; 1937 if (!A.Align) { 1938 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 1939 } else { 1940 unsigned M = 1 << A.Align; 1941 Min *= M; 1942 Max *= M; 1943 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 1944 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 1945 } 1946 } 1947 return Error; 1948 } 1949 1950 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1951 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1952 // ordering for DSP is unspecified. MSA is ordered by the data format used 1953 // by the underlying instruction i.e., df/m, df/n and then by size. 1954 // 1955 // FIXME: The size tests here should instead be tablegen'd along with the 1956 // definitions from include/clang/Basic/BuiltinsMips.def. 1957 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1958 // be too. 1959 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1960 unsigned i = 0, l = 0, u = 0, m = 0; 1961 switch (BuiltinID) { 1962 default: return false; 1963 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1964 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1965 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1966 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1967 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1968 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1969 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1970 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1971 // df/m field. 1972 // These intrinsics take an unsigned 3 bit immediate. 1973 case Mips::BI__builtin_msa_bclri_b: 1974 case Mips::BI__builtin_msa_bnegi_b: 1975 case Mips::BI__builtin_msa_bseti_b: 1976 case Mips::BI__builtin_msa_sat_s_b: 1977 case Mips::BI__builtin_msa_sat_u_b: 1978 case Mips::BI__builtin_msa_slli_b: 1979 case Mips::BI__builtin_msa_srai_b: 1980 case Mips::BI__builtin_msa_srari_b: 1981 case Mips::BI__builtin_msa_srli_b: 1982 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1983 case Mips::BI__builtin_msa_binsli_b: 1984 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1985 // These intrinsics take an unsigned 4 bit immediate. 1986 case Mips::BI__builtin_msa_bclri_h: 1987 case Mips::BI__builtin_msa_bnegi_h: 1988 case Mips::BI__builtin_msa_bseti_h: 1989 case Mips::BI__builtin_msa_sat_s_h: 1990 case Mips::BI__builtin_msa_sat_u_h: 1991 case Mips::BI__builtin_msa_slli_h: 1992 case Mips::BI__builtin_msa_srai_h: 1993 case Mips::BI__builtin_msa_srari_h: 1994 case Mips::BI__builtin_msa_srli_h: 1995 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1996 case Mips::BI__builtin_msa_binsli_h: 1997 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 1998 // These intrinsics take an unsigned 5 bit immediate. 1999 // The first block of intrinsics actually have an unsigned 5 bit field, 2000 // not a df/n field. 2001 case Mips::BI__builtin_msa_clei_u_b: 2002 case Mips::BI__builtin_msa_clei_u_h: 2003 case Mips::BI__builtin_msa_clei_u_w: 2004 case Mips::BI__builtin_msa_clei_u_d: 2005 case Mips::BI__builtin_msa_clti_u_b: 2006 case Mips::BI__builtin_msa_clti_u_h: 2007 case Mips::BI__builtin_msa_clti_u_w: 2008 case Mips::BI__builtin_msa_clti_u_d: 2009 case Mips::BI__builtin_msa_maxi_u_b: 2010 case Mips::BI__builtin_msa_maxi_u_h: 2011 case Mips::BI__builtin_msa_maxi_u_w: 2012 case Mips::BI__builtin_msa_maxi_u_d: 2013 case Mips::BI__builtin_msa_mini_u_b: 2014 case Mips::BI__builtin_msa_mini_u_h: 2015 case Mips::BI__builtin_msa_mini_u_w: 2016 case Mips::BI__builtin_msa_mini_u_d: 2017 case Mips::BI__builtin_msa_addvi_b: 2018 case Mips::BI__builtin_msa_addvi_h: 2019 case Mips::BI__builtin_msa_addvi_w: 2020 case Mips::BI__builtin_msa_addvi_d: 2021 case Mips::BI__builtin_msa_bclri_w: 2022 case Mips::BI__builtin_msa_bnegi_w: 2023 case Mips::BI__builtin_msa_bseti_w: 2024 case Mips::BI__builtin_msa_sat_s_w: 2025 case Mips::BI__builtin_msa_sat_u_w: 2026 case Mips::BI__builtin_msa_slli_w: 2027 case Mips::BI__builtin_msa_srai_w: 2028 case Mips::BI__builtin_msa_srari_w: 2029 case Mips::BI__builtin_msa_srli_w: 2030 case Mips::BI__builtin_msa_srlri_w: 2031 case Mips::BI__builtin_msa_subvi_b: 2032 case Mips::BI__builtin_msa_subvi_h: 2033 case Mips::BI__builtin_msa_subvi_w: 2034 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2035 case Mips::BI__builtin_msa_binsli_w: 2036 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2037 // These intrinsics take an unsigned 6 bit immediate. 2038 case Mips::BI__builtin_msa_bclri_d: 2039 case Mips::BI__builtin_msa_bnegi_d: 2040 case Mips::BI__builtin_msa_bseti_d: 2041 case Mips::BI__builtin_msa_sat_s_d: 2042 case Mips::BI__builtin_msa_sat_u_d: 2043 case Mips::BI__builtin_msa_slli_d: 2044 case Mips::BI__builtin_msa_srai_d: 2045 case Mips::BI__builtin_msa_srari_d: 2046 case Mips::BI__builtin_msa_srli_d: 2047 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2048 case Mips::BI__builtin_msa_binsli_d: 2049 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2050 // These intrinsics take a signed 5 bit immediate. 2051 case Mips::BI__builtin_msa_ceqi_b: 2052 case Mips::BI__builtin_msa_ceqi_h: 2053 case Mips::BI__builtin_msa_ceqi_w: 2054 case Mips::BI__builtin_msa_ceqi_d: 2055 case Mips::BI__builtin_msa_clti_s_b: 2056 case Mips::BI__builtin_msa_clti_s_h: 2057 case Mips::BI__builtin_msa_clti_s_w: 2058 case Mips::BI__builtin_msa_clti_s_d: 2059 case Mips::BI__builtin_msa_clei_s_b: 2060 case Mips::BI__builtin_msa_clei_s_h: 2061 case Mips::BI__builtin_msa_clei_s_w: 2062 case Mips::BI__builtin_msa_clei_s_d: 2063 case Mips::BI__builtin_msa_maxi_s_b: 2064 case Mips::BI__builtin_msa_maxi_s_h: 2065 case Mips::BI__builtin_msa_maxi_s_w: 2066 case Mips::BI__builtin_msa_maxi_s_d: 2067 case Mips::BI__builtin_msa_mini_s_b: 2068 case Mips::BI__builtin_msa_mini_s_h: 2069 case Mips::BI__builtin_msa_mini_s_w: 2070 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2071 // These intrinsics take an unsigned 8 bit immediate. 2072 case Mips::BI__builtin_msa_andi_b: 2073 case Mips::BI__builtin_msa_nori_b: 2074 case Mips::BI__builtin_msa_ori_b: 2075 case Mips::BI__builtin_msa_shf_b: 2076 case Mips::BI__builtin_msa_shf_h: 2077 case Mips::BI__builtin_msa_shf_w: 2078 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2079 case Mips::BI__builtin_msa_bseli_b: 2080 case Mips::BI__builtin_msa_bmnzi_b: 2081 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2082 // df/n format 2083 // These intrinsics take an unsigned 4 bit immediate. 2084 case Mips::BI__builtin_msa_copy_s_b: 2085 case Mips::BI__builtin_msa_copy_u_b: 2086 case Mips::BI__builtin_msa_insve_b: 2087 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2088 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2089 // These intrinsics take an unsigned 3 bit immediate. 2090 case Mips::BI__builtin_msa_copy_s_h: 2091 case Mips::BI__builtin_msa_copy_u_h: 2092 case Mips::BI__builtin_msa_insve_h: 2093 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2094 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2095 // These intrinsics take an unsigned 2 bit immediate. 2096 case Mips::BI__builtin_msa_copy_s_w: 2097 case Mips::BI__builtin_msa_copy_u_w: 2098 case Mips::BI__builtin_msa_insve_w: 2099 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2100 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2101 // These intrinsics take an unsigned 1 bit immediate. 2102 case Mips::BI__builtin_msa_copy_s_d: 2103 case Mips::BI__builtin_msa_copy_u_d: 2104 case Mips::BI__builtin_msa_insve_d: 2105 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2106 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2107 // Memory offsets and immediate loads. 2108 // These intrinsics take a signed 10 bit immediate. 2109 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2110 case Mips::BI__builtin_msa_ldi_h: 2111 case Mips::BI__builtin_msa_ldi_w: 2112 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2113 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 2114 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 2115 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 2116 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 2117 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 2118 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 2119 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 2120 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 2121 } 2122 2123 if (!m) 2124 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2125 2126 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2127 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2128 } 2129 2130 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2131 unsigned i = 0, l = 0, u = 0; 2132 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2133 BuiltinID == PPC::BI__builtin_divdeu || 2134 BuiltinID == PPC::BI__builtin_bpermd; 2135 bool IsTarget64Bit = Context.getTargetInfo() 2136 .getTypeWidth(Context 2137 .getTargetInfo() 2138 .getIntPtrType()) == 64; 2139 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2140 BuiltinID == PPC::BI__builtin_divweu || 2141 BuiltinID == PPC::BI__builtin_divde || 2142 BuiltinID == PPC::BI__builtin_divdeu; 2143 2144 if (Is64BitBltin && !IsTarget64Bit) 2145 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 2146 << TheCall->getSourceRange(); 2147 2148 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2149 (BuiltinID == PPC::BI__builtin_bpermd && 2150 !Context.getTargetInfo().hasFeature("bpermd"))) 2151 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 2152 << TheCall->getSourceRange(); 2153 2154 switch (BuiltinID) { 2155 default: return false; 2156 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2157 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2158 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2159 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2160 case PPC::BI__builtin_tbegin: 2161 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2162 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2163 case PPC::BI__builtin_tabortwc: 2164 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2165 case PPC::BI__builtin_tabortwci: 2166 case PPC::BI__builtin_tabortdci: 2167 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2168 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2169 case PPC::BI__builtin_vsx_xxpermdi: 2170 case PPC::BI__builtin_vsx_xxsldwi: 2171 return SemaBuiltinVSX(TheCall); 2172 } 2173 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2174 } 2175 2176 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2177 CallExpr *TheCall) { 2178 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2179 Expr *Arg = TheCall->getArg(0); 2180 llvm::APSInt AbortCode(32); 2181 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2182 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2183 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 2184 << Arg->getSourceRange(); 2185 } 2186 2187 // For intrinsics which take an immediate value as part of the instruction, 2188 // range check them here. 2189 unsigned i = 0, l = 0, u = 0; 2190 switch (BuiltinID) { 2191 default: return false; 2192 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2193 case SystemZ::BI__builtin_s390_verimb: 2194 case SystemZ::BI__builtin_s390_verimh: 2195 case SystemZ::BI__builtin_s390_verimf: 2196 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2197 case SystemZ::BI__builtin_s390_vfaeb: 2198 case SystemZ::BI__builtin_s390_vfaeh: 2199 case SystemZ::BI__builtin_s390_vfaef: 2200 case SystemZ::BI__builtin_s390_vfaebs: 2201 case SystemZ::BI__builtin_s390_vfaehs: 2202 case SystemZ::BI__builtin_s390_vfaefs: 2203 case SystemZ::BI__builtin_s390_vfaezb: 2204 case SystemZ::BI__builtin_s390_vfaezh: 2205 case SystemZ::BI__builtin_s390_vfaezf: 2206 case SystemZ::BI__builtin_s390_vfaezbs: 2207 case SystemZ::BI__builtin_s390_vfaezhs: 2208 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2209 case SystemZ::BI__builtin_s390_vfisb: 2210 case SystemZ::BI__builtin_s390_vfidb: 2211 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 2212 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2213 case SystemZ::BI__builtin_s390_vftcisb: 2214 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 2215 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 2216 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 2217 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 2218 case SystemZ::BI__builtin_s390_vstrcb: 2219 case SystemZ::BI__builtin_s390_vstrch: 2220 case SystemZ::BI__builtin_s390_vstrcf: 2221 case SystemZ::BI__builtin_s390_vstrczb: 2222 case SystemZ::BI__builtin_s390_vstrczh: 2223 case SystemZ::BI__builtin_s390_vstrczf: 2224 case SystemZ::BI__builtin_s390_vstrcbs: 2225 case SystemZ::BI__builtin_s390_vstrchs: 2226 case SystemZ::BI__builtin_s390_vstrcfs: 2227 case SystemZ::BI__builtin_s390_vstrczbs: 2228 case SystemZ::BI__builtin_s390_vstrczhs: 2229 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 2230 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 2231 case SystemZ::BI__builtin_s390_vfminsb: 2232 case SystemZ::BI__builtin_s390_vfmaxsb: 2233 case SystemZ::BI__builtin_s390_vfmindb: 2234 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 2235 } 2236 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2237 } 2238 2239 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 2240 /// This checks that the target supports __builtin_cpu_supports and 2241 /// that the string argument is constant and valid. 2242 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 2243 Expr *Arg = TheCall->getArg(0); 2244 2245 // Check if the argument is a string literal. 2246 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2247 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2248 << Arg->getSourceRange(); 2249 2250 // Check the contents of the string. 2251 StringRef Feature = 2252 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2253 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 2254 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 2255 << Arg->getSourceRange(); 2256 return false; 2257 } 2258 2259 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 2260 /// This checks that the target supports __builtin_cpu_is and 2261 /// that the string argument is constant and valid. 2262 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 2263 Expr *Arg = TheCall->getArg(0); 2264 2265 // Check if the argument is a string literal. 2266 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2267 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2268 << Arg->getSourceRange(); 2269 2270 // Check the contents of the string. 2271 StringRef Feature = 2272 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2273 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 2274 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 2275 << Arg->getSourceRange(); 2276 return false; 2277 } 2278 2279 // Check if the rounding mode is legal. 2280 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 2281 // Indicates if this instruction has rounding control or just SAE. 2282 bool HasRC = false; 2283 2284 unsigned ArgNum = 0; 2285 switch (BuiltinID) { 2286 default: 2287 return false; 2288 case X86::BI__builtin_ia32_vcvttsd2si32: 2289 case X86::BI__builtin_ia32_vcvttsd2si64: 2290 case X86::BI__builtin_ia32_vcvttsd2usi32: 2291 case X86::BI__builtin_ia32_vcvttsd2usi64: 2292 case X86::BI__builtin_ia32_vcvttss2si32: 2293 case X86::BI__builtin_ia32_vcvttss2si64: 2294 case X86::BI__builtin_ia32_vcvttss2usi32: 2295 case X86::BI__builtin_ia32_vcvttss2usi64: 2296 ArgNum = 1; 2297 break; 2298 case X86::BI__builtin_ia32_cvtps2pd512_mask: 2299 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 2300 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 2301 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 2302 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 2303 case X86::BI__builtin_ia32_cvttps2dq512_mask: 2304 case X86::BI__builtin_ia32_cvttps2qq512_mask: 2305 case X86::BI__builtin_ia32_cvttps2udq512_mask: 2306 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 2307 case X86::BI__builtin_ia32_exp2pd_mask: 2308 case X86::BI__builtin_ia32_exp2ps_mask: 2309 case X86::BI__builtin_ia32_getexppd512_mask: 2310 case X86::BI__builtin_ia32_getexpps512_mask: 2311 case X86::BI__builtin_ia32_rcp28pd_mask: 2312 case X86::BI__builtin_ia32_rcp28ps_mask: 2313 case X86::BI__builtin_ia32_rsqrt28pd_mask: 2314 case X86::BI__builtin_ia32_rsqrt28ps_mask: 2315 case X86::BI__builtin_ia32_vcomisd: 2316 case X86::BI__builtin_ia32_vcomiss: 2317 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 2318 ArgNum = 3; 2319 break; 2320 case X86::BI__builtin_ia32_cmppd512_mask: 2321 case X86::BI__builtin_ia32_cmpps512_mask: 2322 case X86::BI__builtin_ia32_cmpsd_mask: 2323 case X86::BI__builtin_ia32_cmpss_mask: 2324 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 2325 case X86::BI__builtin_ia32_getexpsd128_round_mask: 2326 case X86::BI__builtin_ia32_getexpss128_round_mask: 2327 case X86::BI__builtin_ia32_maxpd512_mask: 2328 case X86::BI__builtin_ia32_maxps512_mask: 2329 case X86::BI__builtin_ia32_maxsd_round_mask: 2330 case X86::BI__builtin_ia32_maxss_round_mask: 2331 case X86::BI__builtin_ia32_minpd512_mask: 2332 case X86::BI__builtin_ia32_minps512_mask: 2333 case X86::BI__builtin_ia32_minsd_round_mask: 2334 case X86::BI__builtin_ia32_minss_round_mask: 2335 case X86::BI__builtin_ia32_rcp28sd_round_mask: 2336 case X86::BI__builtin_ia32_rcp28ss_round_mask: 2337 case X86::BI__builtin_ia32_reducepd512_mask: 2338 case X86::BI__builtin_ia32_reduceps512_mask: 2339 case X86::BI__builtin_ia32_rndscalepd_mask: 2340 case X86::BI__builtin_ia32_rndscaleps_mask: 2341 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 2342 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 2343 ArgNum = 4; 2344 break; 2345 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2346 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2347 case X86::BI__builtin_ia32_fixupimmps512_mask: 2348 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2349 case X86::BI__builtin_ia32_fixupimmsd_mask: 2350 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2351 case X86::BI__builtin_ia32_fixupimmss_mask: 2352 case X86::BI__builtin_ia32_fixupimmss_maskz: 2353 case X86::BI__builtin_ia32_rangepd512_mask: 2354 case X86::BI__builtin_ia32_rangeps512_mask: 2355 case X86::BI__builtin_ia32_rangesd128_round_mask: 2356 case X86::BI__builtin_ia32_rangess128_round_mask: 2357 case X86::BI__builtin_ia32_reducesd_mask: 2358 case X86::BI__builtin_ia32_reducess_mask: 2359 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2360 case X86::BI__builtin_ia32_rndscaless_round_mask: 2361 ArgNum = 5; 2362 break; 2363 case X86::BI__builtin_ia32_vcvtsd2si64: 2364 case X86::BI__builtin_ia32_vcvtsd2si32: 2365 case X86::BI__builtin_ia32_vcvtsd2usi32: 2366 case X86::BI__builtin_ia32_vcvtsd2usi64: 2367 case X86::BI__builtin_ia32_vcvtss2si32: 2368 case X86::BI__builtin_ia32_vcvtss2si64: 2369 case X86::BI__builtin_ia32_vcvtss2usi32: 2370 case X86::BI__builtin_ia32_vcvtss2usi64: 2371 ArgNum = 1; 2372 HasRC = true; 2373 break; 2374 case X86::BI__builtin_ia32_addpd512: 2375 case X86::BI__builtin_ia32_addps512: 2376 case X86::BI__builtin_ia32_divpd512: 2377 case X86::BI__builtin_ia32_divps512: 2378 case X86::BI__builtin_ia32_mulpd512: 2379 case X86::BI__builtin_ia32_mulps512: 2380 case X86::BI__builtin_ia32_subpd512: 2381 case X86::BI__builtin_ia32_subps512: 2382 case X86::BI__builtin_ia32_cvtsi2sd64: 2383 case X86::BI__builtin_ia32_cvtsi2ss32: 2384 case X86::BI__builtin_ia32_cvtsi2ss64: 2385 case X86::BI__builtin_ia32_cvtusi2sd64: 2386 case X86::BI__builtin_ia32_cvtusi2ss32: 2387 case X86::BI__builtin_ia32_cvtusi2ss64: 2388 ArgNum = 2; 2389 HasRC = true; 2390 break; 2391 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 2392 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 2393 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 2394 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 2395 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 2396 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2397 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2398 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2399 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2400 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2401 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2402 case X86::BI__builtin_ia32_sqrtpd512_mask: 2403 case X86::BI__builtin_ia32_sqrtps512_mask: 2404 ArgNum = 3; 2405 HasRC = true; 2406 break; 2407 case X86::BI__builtin_ia32_addss_round_mask: 2408 case X86::BI__builtin_ia32_addsd_round_mask: 2409 case X86::BI__builtin_ia32_divss_round_mask: 2410 case X86::BI__builtin_ia32_divsd_round_mask: 2411 case X86::BI__builtin_ia32_mulss_round_mask: 2412 case X86::BI__builtin_ia32_mulsd_round_mask: 2413 case X86::BI__builtin_ia32_subss_round_mask: 2414 case X86::BI__builtin_ia32_subsd_round_mask: 2415 case X86::BI__builtin_ia32_scalefpd512_mask: 2416 case X86::BI__builtin_ia32_scalefps512_mask: 2417 case X86::BI__builtin_ia32_scalefsd_round_mask: 2418 case X86::BI__builtin_ia32_scalefss_round_mask: 2419 case X86::BI__builtin_ia32_getmantpd512_mask: 2420 case X86::BI__builtin_ia32_getmantps512_mask: 2421 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2422 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2423 case X86::BI__builtin_ia32_sqrtss_round_mask: 2424 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2425 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2426 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2427 case X86::BI__builtin_ia32_vfmaddss3_mask: 2428 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2429 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2430 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2431 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2432 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2433 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2434 case X86::BI__builtin_ia32_vfmaddps512_mask: 2435 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2436 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2437 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2438 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2439 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2440 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2441 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2442 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2443 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2444 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2445 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2446 ArgNum = 4; 2447 HasRC = true; 2448 break; 2449 case X86::BI__builtin_ia32_getmantsd_round_mask: 2450 case X86::BI__builtin_ia32_getmantss_round_mask: 2451 ArgNum = 5; 2452 HasRC = true; 2453 break; 2454 } 2455 2456 llvm::APSInt Result; 2457 2458 // We can't check the value of a dependent argument. 2459 Expr *Arg = TheCall->getArg(ArgNum); 2460 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2461 return false; 2462 2463 // Check constant-ness first. 2464 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2465 return true; 2466 2467 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2468 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2469 // combined with ROUND_NO_EXC. 2470 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2471 Result == 8/*ROUND_NO_EXC*/ || 2472 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2473 return false; 2474 2475 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2476 << Arg->getSourceRange(); 2477 } 2478 2479 // Check if the gather/scatter scale is legal. 2480 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2481 CallExpr *TheCall) { 2482 unsigned ArgNum = 0; 2483 switch (BuiltinID) { 2484 default: 2485 return false; 2486 case X86::BI__builtin_ia32_gatherpfdpd: 2487 case X86::BI__builtin_ia32_gatherpfdps: 2488 case X86::BI__builtin_ia32_gatherpfqpd: 2489 case X86::BI__builtin_ia32_gatherpfqps: 2490 case X86::BI__builtin_ia32_scatterpfdpd: 2491 case X86::BI__builtin_ia32_scatterpfdps: 2492 case X86::BI__builtin_ia32_scatterpfqpd: 2493 case X86::BI__builtin_ia32_scatterpfqps: 2494 ArgNum = 3; 2495 break; 2496 case X86::BI__builtin_ia32_gatherd_pd: 2497 case X86::BI__builtin_ia32_gatherd_pd256: 2498 case X86::BI__builtin_ia32_gatherq_pd: 2499 case X86::BI__builtin_ia32_gatherq_pd256: 2500 case X86::BI__builtin_ia32_gatherd_ps: 2501 case X86::BI__builtin_ia32_gatherd_ps256: 2502 case X86::BI__builtin_ia32_gatherq_ps: 2503 case X86::BI__builtin_ia32_gatherq_ps256: 2504 case X86::BI__builtin_ia32_gatherd_q: 2505 case X86::BI__builtin_ia32_gatherd_q256: 2506 case X86::BI__builtin_ia32_gatherq_q: 2507 case X86::BI__builtin_ia32_gatherq_q256: 2508 case X86::BI__builtin_ia32_gatherd_d: 2509 case X86::BI__builtin_ia32_gatherd_d256: 2510 case X86::BI__builtin_ia32_gatherq_d: 2511 case X86::BI__builtin_ia32_gatherq_d256: 2512 case X86::BI__builtin_ia32_gather3div2df: 2513 case X86::BI__builtin_ia32_gather3div2di: 2514 case X86::BI__builtin_ia32_gather3div4df: 2515 case X86::BI__builtin_ia32_gather3div4di: 2516 case X86::BI__builtin_ia32_gather3div4sf: 2517 case X86::BI__builtin_ia32_gather3div4si: 2518 case X86::BI__builtin_ia32_gather3div8sf: 2519 case X86::BI__builtin_ia32_gather3div8si: 2520 case X86::BI__builtin_ia32_gather3siv2df: 2521 case X86::BI__builtin_ia32_gather3siv2di: 2522 case X86::BI__builtin_ia32_gather3siv4df: 2523 case X86::BI__builtin_ia32_gather3siv4di: 2524 case X86::BI__builtin_ia32_gather3siv4sf: 2525 case X86::BI__builtin_ia32_gather3siv4si: 2526 case X86::BI__builtin_ia32_gather3siv8sf: 2527 case X86::BI__builtin_ia32_gather3siv8si: 2528 case X86::BI__builtin_ia32_gathersiv8df: 2529 case X86::BI__builtin_ia32_gathersiv16sf: 2530 case X86::BI__builtin_ia32_gatherdiv8df: 2531 case X86::BI__builtin_ia32_gatherdiv16sf: 2532 case X86::BI__builtin_ia32_gathersiv8di: 2533 case X86::BI__builtin_ia32_gathersiv16si: 2534 case X86::BI__builtin_ia32_gatherdiv8di: 2535 case X86::BI__builtin_ia32_gatherdiv16si: 2536 case X86::BI__builtin_ia32_scatterdiv2df: 2537 case X86::BI__builtin_ia32_scatterdiv2di: 2538 case X86::BI__builtin_ia32_scatterdiv4df: 2539 case X86::BI__builtin_ia32_scatterdiv4di: 2540 case X86::BI__builtin_ia32_scatterdiv4sf: 2541 case X86::BI__builtin_ia32_scatterdiv4si: 2542 case X86::BI__builtin_ia32_scatterdiv8sf: 2543 case X86::BI__builtin_ia32_scatterdiv8si: 2544 case X86::BI__builtin_ia32_scattersiv2df: 2545 case X86::BI__builtin_ia32_scattersiv2di: 2546 case X86::BI__builtin_ia32_scattersiv4df: 2547 case X86::BI__builtin_ia32_scattersiv4di: 2548 case X86::BI__builtin_ia32_scattersiv4sf: 2549 case X86::BI__builtin_ia32_scattersiv4si: 2550 case X86::BI__builtin_ia32_scattersiv8sf: 2551 case X86::BI__builtin_ia32_scattersiv8si: 2552 case X86::BI__builtin_ia32_scattersiv8df: 2553 case X86::BI__builtin_ia32_scattersiv16sf: 2554 case X86::BI__builtin_ia32_scatterdiv8df: 2555 case X86::BI__builtin_ia32_scatterdiv16sf: 2556 case X86::BI__builtin_ia32_scattersiv8di: 2557 case X86::BI__builtin_ia32_scattersiv16si: 2558 case X86::BI__builtin_ia32_scatterdiv8di: 2559 case X86::BI__builtin_ia32_scatterdiv16si: 2560 ArgNum = 4; 2561 break; 2562 } 2563 2564 llvm::APSInt Result; 2565 2566 // We can't check the value of a dependent argument. 2567 Expr *Arg = TheCall->getArg(ArgNum); 2568 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2569 return false; 2570 2571 // Check constant-ness first. 2572 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2573 return true; 2574 2575 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2576 return false; 2577 2578 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2579 << Arg->getSourceRange(); 2580 } 2581 2582 static bool isX86_32Builtin(unsigned BuiltinID) { 2583 // These builtins only work on x86-32 targets. 2584 switch (BuiltinID) { 2585 case X86::BI__builtin_ia32_readeflags_u32: 2586 case X86::BI__builtin_ia32_writeeflags_u32: 2587 return true; 2588 } 2589 2590 return false; 2591 } 2592 2593 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2594 if (BuiltinID == X86::BI__builtin_cpu_supports) 2595 return SemaBuiltinCpuSupports(*this, TheCall); 2596 2597 if (BuiltinID == X86::BI__builtin_cpu_is) 2598 return SemaBuiltinCpuIs(*this, TheCall); 2599 2600 // Check for 32-bit only builtins on a 64-bit target. 2601 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 2602 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 2603 return Diag(TheCall->getCallee()->getLocStart(), 2604 diag::err_32_bit_builtin_64_bit_tgt); 2605 2606 // If the intrinsic has rounding or SAE make sure its valid. 2607 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2608 return true; 2609 2610 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2611 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2612 return true; 2613 2614 // For intrinsics which take an immediate value as part of the instruction, 2615 // range check them here. 2616 int i = 0, l = 0, u = 0; 2617 switch (BuiltinID) { 2618 default: 2619 return false; 2620 case X86::BI__builtin_ia32_vec_ext_v2si: 2621 case X86::BI__builtin_ia32_vec_ext_v2di: 2622 case X86::BI__builtin_ia32_vextractf128_pd256: 2623 case X86::BI__builtin_ia32_vextractf128_ps256: 2624 case X86::BI__builtin_ia32_vextractf128_si256: 2625 case X86::BI__builtin_ia32_extract128i256: 2626 case X86::BI__builtin_ia32_extractf64x4_mask: 2627 case X86::BI__builtin_ia32_extracti64x4_mask: 2628 case X86::BI__builtin_ia32_extractf32x8_mask: 2629 case X86::BI__builtin_ia32_extracti32x8_mask: 2630 case X86::BI__builtin_ia32_extractf64x2_256_mask: 2631 case X86::BI__builtin_ia32_extracti64x2_256_mask: 2632 case X86::BI__builtin_ia32_extractf32x4_256_mask: 2633 case X86::BI__builtin_ia32_extracti32x4_256_mask: 2634 i = 1; l = 0; u = 1; 2635 break; 2636 case X86::BI__builtin_ia32_vec_set_v2di: 2637 case X86::BI__builtin_ia32_vinsertf128_pd256: 2638 case X86::BI__builtin_ia32_vinsertf128_ps256: 2639 case X86::BI__builtin_ia32_vinsertf128_si256: 2640 case X86::BI__builtin_ia32_insert128i256: 2641 case X86::BI__builtin_ia32_insertf32x8: 2642 case X86::BI__builtin_ia32_inserti32x8: 2643 case X86::BI__builtin_ia32_insertf64x4: 2644 case X86::BI__builtin_ia32_inserti64x4: 2645 case X86::BI__builtin_ia32_insertf64x2_256: 2646 case X86::BI__builtin_ia32_inserti64x2_256: 2647 case X86::BI__builtin_ia32_insertf32x4_256: 2648 case X86::BI__builtin_ia32_inserti32x4_256: 2649 i = 2; l = 0; u = 1; 2650 break; 2651 case X86::BI__builtin_ia32_vpermilpd: 2652 case X86::BI__builtin_ia32_vec_ext_v4hi: 2653 case X86::BI__builtin_ia32_vec_ext_v4si: 2654 case X86::BI__builtin_ia32_vec_ext_v4sf: 2655 case X86::BI__builtin_ia32_vec_ext_v4di: 2656 case X86::BI__builtin_ia32_extractf32x4_mask: 2657 case X86::BI__builtin_ia32_extracti32x4_mask: 2658 case X86::BI__builtin_ia32_extractf64x2_512_mask: 2659 case X86::BI__builtin_ia32_extracti64x2_512_mask: 2660 i = 1; l = 0; u = 3; 2661 break; 2662 case X86::BI_mm_prefetch: 2663 case X86::BI__builtin_ia32_vec_ext_v8hi: 2664 case X86::BI__builtin_ia32_vec_ext_v8si: 2665 i = 1; l = 0; u = 7; 2666 break; 2667 case X86::BI__builtin_ia32_sha1rnds4: 2668 case X86::BI__builtin_ia32_blendpd: 2669 case X86::BI__builtin_ia32_shufpd: 2670 case X86::BI__builtin_ia32_vec_set_v4hi: 2671 case X86::BI__builtin_ia32_vec_set_v4si: 2672 case X86::BI__builtin_ia32_vec_set_v4di: 2673 case X86::BI__builtin_ia32_shuf_f32x4_256: 2674 case X86::BI__builtin_ia32_shuf_f64x2_256: 2675 case X86::BI__builtin_ia32_shuf_i32x4_256: 2676 case X86::BI__builtin_ia32_shuf_i64x2_256: 2677 case X86::BI__builtin_ia32_insertf64x2_512: 2678 case X86::BI__builtin_ia32_inserti64x2_512: 2679 case X86::BI__builtin_ia32_insertf32x4: 2680 case X86::BI__builtin_ia32_inserti32x4: 2681 i = 2; l = 0; u = 3; 2682 break; 2683 case X86::BI__builtin_ia32_vpermil2pd: 2684 case X86::BI__builtin_ia32_vpermil2pd256: 2685 case X86::BI__builtin_ia32_vpermil2ps: 2686 case X86::BI__builtin_ia32_vpermil2ps256: 2687 i = 3; l = 0; u = 3; 2688 break; 2689 case X86::BI__builtin_ia32_cmpb128_mask: 2690 case X86::BI__builtin_ia32_cmpw128_mask: 2691 case X86::BI__builtin_ia32_cmpd128_mask: 2692 case X86::BI__builtin_ia32_cmpq128_mask: 2693 case X86::BI__builtin_ia32_cmpb256_mask: 2694 case X86::BI__builtin_ia32_cmpw256_mask: 2695 case X86::BI__builtin_ia32_cmpd256_mask: 2696 case X86::BI__builtin_ia32_cmpq256_mask: 2697 case X86::BI__builtin_ia32_cmpb512_mask: 2698 case X86::BI__builtin_ia32_cmpw512_mask: 2699 case X86::BI__builtin_ia32_cmpd512_mask: 2700 case X86::BI__builtin_ia32_cmpq512_mask: 2701 case X86::BI__builtin_ia32_ucmpb128_mask: 2702 case X86::BI__builtin_ia32_ucmpw128_mask: 2703 case X86::BI__builtin_ia32_ucmpd128_mask: 2704 case X86::BI__builtin_ia32_ucmpq128_mask: 2705 case X86::BI__builtin_ia32_ucmpb256_mask: 2706 case X86::BI__builtin_ia32_ucmpw256_mask: 2707 case X86::BI__builtin_ia32_ucmpd256_mask: 2708 case X86::BI__builtin_ia32_ucmpq256_mask: 2709 case X86::BI__builtin_ia32_ucmpb512_mask: 2710 case X86::BI__builtin_ia32_ucmpw512_mask: 2711 case X86::BI__builtin_ia32_ucmpd512_mask: 2712 case X86::BI__builtin_ia32_ucmpq512_mask: 2713 case X86::BI__builtin_ia32_vpcomub: 2714 case X86::BI__builtin_ia32_vpcomuw: 2715 case X86::BI__builtin_ia32_vpcomud: 2716 case X86::BI__builtin_ia32_vpcomuq: 2717 case X86::BI__builtin_ia32_vpcomb: 2718 case X86::BI__builtin_ia32_vpcomw: 2719 case X86::BI__builtin_ia32_vpcomd: 2720 case X86::BI__builtin_ia32_vpcomq: 2721 case X86::BI__builtin_ia32_vec_set_v8hi: 2722 case X86::BI__builtin_ia32_vec_set_v8si: 2723 i = 2; l = 0; u = 7; 2724 break; 2725 case X86::BI__builtin_ia32_vpermilpd256: 2726 case X86::BI__builtin_ia32_roundps: 2727 case X86::BI__builtin_ia32_roundpd: 2728 case X86::BI__builtin_ia32_roundps256: 2729 case X86::BI__builtin_ia32_roundpd256: 2730 case X86::BI__builtin_ia32_getmantpd128_mask: 2731 case X86::BI__builtin_ia32_getmantpd256_mask: 2732 case X86::BI__builtin_ia32_getmantps128_mask: 2733 case X86::BI__builtin_ia32_getmantps256_mask: 2734 case X86::BI__builtin_ia32_getmantpd512_mask: 2735 case X86::BI__builtin_ia32_getmantps512_mask: 2736 case X86::BI__builtin_ia32_vec_ext_v16qi: 2737 case X86::BI__builtin_ia32_vec_ext_v16hi: 2738 i = 1; l = 0; u = 15; 2739 break; 2740 case X86::BI__builtin_ia32_pblendd128: 2741 case X86::BI__builtin_ia32_blendps: 2742 case X86::BI__builtin_ia32_blendpd256: 2743 case X86::BI__builtin_ia32_shufpd256: 2744 case X86::BI__builtin_ia32_roundss: 2745 case X86::BI__builtin_ia32_roundsd: 2746 case X86::BI__builtin_ia32_rangepd128_mask: 2747 case X86::BI__builtin_ia32_rangepd256_mask: 2748 case X86::BI__builtin_ia32_rangepd512_mask: 2749 case X86::BI__builtin_ia32_rangeps128_mask: 2750 case X86::BI__builtin_ia32_rangeps256_mask: 2751 case X86::BI__builtin_ia32_rangeps512_mask: 2752 case X86::BI__builtin_ia32_getmantsd_round_mask: 2753 case X86::BI__builtin_ia32_getmantss_round_mask: 2754 case X86::BI__builtin_ia32_vec_set_v16qi: 2755 case X86::BI__builtin_ia32_vec_set_v16hi: 2756 i = 2; l = 0; u = 15; 2757 break; 2758 case X86::BI__builtin_ia32_vec_ext_v32qi: 2759 i = 1; l = 0; u = 31; 2760 break; 2761 case X86::BI__builtin_ia32_cmpps: 2762 case X86::BI__builtin_ia32_cmpss: 2763 case X86::BI__builtin_ia32_cmppd: 2764 case X86::BI__builtin_ia32_cmpsd: 2765 case X86::BI__builtin_ia32_cmpps256: 2766 case X86::BI__builtin_ia32_cmppd256: 2767 case X86::BI__builtin_ia32_cmpps128_mask: 2768 case X86::BI__builtin_ia32_cmppd128_mask: 2769 case X86::BI__builtin_ia32_cmpps256_mask: 2770 case X86::BI__builtin_ia32_cmppd256_mask: 2771 case X86::BI__builtin_ia32_cmpps512_mask: 2772 case X86::BI__builtin_ia32_cmppd512_mask: 2773 case X86::BI__builtin_ia32_cmpsd_mask: 2774 case X86::BI__builtin_ia32_cmpss_mask: 2775 case X86::BI__builtin_ia32_vec_set_v32qi: 2776 i = 2; l = 0; u = 31; 2777 break; 2778 case X86::BI__builtin_ia32_permdf256: 2779 case X86::BI__builtin_ia32_permdi256: 2780 case X86::BI__builtin_ia32_permdf512: 2781 case X86::BI__builtin_ia32_permdi512: 2782 case X86::BI__builtin_ia32_vpermilps: 2783 case X86::BI__builtin_ia32_vpermilps256: 2784 case X86::BI__builtin_ia32_vpermilpd512: 2785 case X86::BI__builtin_ia32_vpermilps512: 2786 case X86::BI__builtin_ia32_pshufd: 2787 case X86::BI__builtin_ia32_pshufd256: 2788 case X86::BI__builtin_ia32_pshufd512: 2789 case X86::BI__builtin_ia32_pshufhw: 2790 case X86::BI__builtin_ia32_pshufhw256: 2791 case X86::BI__builtin_ia32_pshufhw512: 2792 case X86::BI__builtin_ia32_pshuflw: 2793 case X86::BI__builtin_ia32_pshuflw256: 2794 case X86::BI__builtin_ia32_pshuflw512: 2795 case X86::BI__builtin_ia32_vcvtps2ph: 2796 case X86::BI__builtin_ia32_vcvtps2ph_mask: 2797 case X86::BI__builtin_ia32_vcvtps2ph256: 2798 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 2799 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 2800 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2801 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2802 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2803 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2804 case X86::BI__builtin_ia32_rndscaleps_mask: 2805 case X86::BI__builtin_ia32_rndscalepd_mask: 2806 case X86::BI__builtin_ia32_reducepd128_mask: 2807 case X86::BI__builtin_ia32_reducepd256_mask: 2808 case X86::BI__builtin_ia32_reducepd512_mask: 2809 case X86::BI__builtin_ia32_reduceps128_mask: 2810 case X86::BI__builtin_ia32_reduceps256_mask: 2811 case X86::BI__builtin_ia32_reduceps512_mask: 2812 case X86::BI__builtin_ia32_prold512_mask: 2813 case X86::BI__builtin_ia32_prolq512_mask: 2814 case X86::BI__builtin_ia32_prold128_mask: 2815 case X86::BI__builtin_ia32_prold256_mask: 2816 case X86::BI__builtin_ia32_prolq128_mask: 2817 case X86::BI__builtin_ia32_prolq256_mask: 2818 case X86::BI__builtin_ia32_prord512_mask: 2819 case X86::BI__builtin_ia32_prorq512_mask: 2820 case X86::BI__builtin_ia32_prord128_mask: 2821 case X86::BI__builtin_ia32_prord256_mask: 2822 case X86::BI__builtin_ia32_prorq128_mask: 2823 case X86::BI__builtin_ia32_prorq256_mask: 2824 case X86::BI__builtin_ia32_fpclasspd128_mask: 2825 case X86::BI__builtin_ia32_fpclasspd256_mask: 2826 case X86::BI__builtin_ia32_fpclassps128_mask: 2827 case X86::BI__builtin_ia32_fpclassps256_mask: 2828 case X86::BI__builtin_ia32_fpclassps512_mask: 2829 case X86::BI__builtin_ia32_fpclasspd512_mask: 2830 case X86::BI__builtin_ia32_fpclasssd_mask: 2831 case X86::BI__builtin_ia32_fpclassss_mask: 2832 case X86::BI__builtin_ia32_pslldqi128_byteshift: 2833 case X86::BI__builtin_ia32_pslldqi256_byteshift: 2834 case X86::BI__builtin_ia32_pslldqi512_byteshift: 2835 case X86::BI__builtin_ia32_psrldqi128_byteshift: 2836 case X86::BI__builtin_ia32_psrldqi256_byteshift: 2837 case X86::BI__builtin_ia32_psrldqi512_byteshift: 2838 i = 1; l = 0; u = 255; 2839 break; 2840 case X86::BI__builtin_ia32_vperm2f128_pd256: 2841 case X86::BI__builtin_ia32_vperm2f128_ps256: 2842 case X86::BI__builtin_ia32_vperm2f128_si256: 2843 case X86::BI__builtin_ia32_permti256: 2844 case X86::BI__builtin_ia32_pblendw128: 2845 case X86::BI__builtin_ia32_pblendw256: 2846 case X86::BI__builtin_ia32_blendps256: 2847 case X86::BI__builtin_ia32_pblendd256: 2848 case X86::BI__builtin_ia32_palignr128: 2849 case X86::BI__builtin_ia32_palignr256: 2850 case X86::BI__builtin_ia32_palignr512: 2851 case X86::BI__builtin_ia32_alignq512: 2852 case X86::BI__builtin_ia32_alignd512: 2853 case X86::BI__builtin_ia32_alignd128: 2854 case X86::BI__builtin_ia32_alignd256: 2855 case X86::BI__builtin_ia32_alignq128: 2856 case X86::BI__builtin_ia32_alignq256: 2857 case X86::BI__builtin_ia32_vcomisd: 2858 case X86::BI__builtin_ia32_vcomiss: 2859 case X86::BI__builtin_ia32_shuf_f32x4: 2860 case X86::BI__builtin_ia32_shuf_f64x2: 2861 case X86::BI__builtin_ia32_shuf_i32x4: 2862 case X86::BI__builtin_ia32_shuf_i64x2: 2863 case X86::BI__builtin_ia32_shufpd512: 2864 case X86::BI__builtin_ia32_shufps: 2865 case X86::BI__builtin_ia32_shufps256: 2866 case X86::BI__builtin_ia32_shufps512: 2867 case X86::BI__builtin_ia32_dbpsadbw128: 2868 case X86::BI__builtin_ia32_dbpsadbw256: 2869 case X86::BI__builtin_ia32_dbpsadbw512: 2870 case X86::BI__builtin_ia32_vpshldd128: 2871 case X86::BI__builtin_ia32_vpshldd256: 2872 case X86::BI__builtin_ia32_vpshldd512: 2873 case X86::BI__builtin_ia32_vpshldq128: 2874 case X86::BI__builtin_ia32_vpshldq256: 2875 case X86::BI__builtin_ia32_vpshldq512: 2876 case X86::BI__builtin_ia32_vpshldw128: 2877 case X86::BI__builtin_ia32_vpshldw256: 2878 case X86::BI__builtin_ia32_vpshldw512: 2879 case X86::BI__builtin_ia32_vpshrdd128: 2880 case X86::BI__builtin_ia32_vpshrdd256: 2881 case X86::BI__builtin_ia32_vpshrdd512: 2882 case X86::BI__builtin_ia32_vpshrdq128: 2883 case X86::BI__builtin_ia32_vpshrdq256: 2884 case X86::BI__builtin_ia32_vpshrdq512: 2885 case X86::BI__builtin_ia32_vpshrdw128: 2886 case X86::BI__builtin_ia32_vpshrdw256: 2887 case X86::BI__builtin_ia32_vpshrdw512: 2888 i = 2; l = 0; u = 255; 2889 break; 2890 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2891 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2892 case X86::BI__builtin_ia32_fixupimmps512_mask: 2893 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2894 case X86::BI__builtin_ia32_fixupimmsd_mask: 2895 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2896 case X86::BI__builtin_ia32_fixupimmss_mask: 2897 case X86::BI__builtin_ia32_fixupimmss_maskz: 2898 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2899 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2900 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2901 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2902 case X86::BI__builtin_ia32_fixupimmps128_mask: 2903 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2904 case X86::BI__builtin_ia32_fixupimmps256_mask: 2905 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2906 case X86::BI__builtin_ia32_pternlogd512_mask: 2907 case X86::BI__builtin_ia32_pternlogd512_maskz: 2908 case X86::BI__builtin_ia32_pternlogq512_mask: 2909 case X86::BI__builtin_ia32_pternlogq512_maskz: 2910 case X86::BI__builtin_ia32_pternlogd128_mask: 2911 case X86::BI__builtin_ia32_pternlogd128_maskz: 2912 case X86::BI__builtin_ia32_pternlogd256_mask: 2913 case X86::BI__builtin_ia32_pternlogd256_maskz: 2914 case X86::BI__builtin_ia32_pternlogq128_mask: 2915 case X86::BI__builtin_ia32_pternlogq128_maskz: 2916 case X86::BI__builtin_ia32_pternlogq256_mask: 2917 case X86::BI__builtin_ia32_pternlogq256_maskz: 2918 i = 3; l = 0; u = 255; 2919 break; 2920 case X86::BI__builtin_ia32_gatherpfdpd: 2921 case X86::BI__builtin_ia32_gatherpfdps: 2922 case X86::BI__builtin_ia32_gatherpfqpd: 2923 case X86::BI__builtin_ia32_gatherpfqps: 2924 case X86::BI__builtin_ia32_scatterpfdpd: 2925 case X86::BI__builtin_ia32_scatterpfdps: 2926 case X86::BI__builtin_ia32_scatterpfqpd: 2927 case X86::BI__builtin_ia32_scatterpfqps: 2928 i = 4; l = 2; u = 3; 2929 break; 2930 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2931 case X86::BI__builtin_ia32_rndscaless_round_mask: 2932 i = 4; l = 0; u = 255; 2933 break; 2934 } 2935 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2936 } 2937 2938 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2939 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2940 /// Returns true when the format fits the function and the FormatStringInfo has 2941 /// been populated. 2942 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2943 FormatStringInfo *FSI) { 2944 FSI->HasVAListArg = Format->getFirstArg() == 0; 2945 FSI->FormatIdx = Format->getFormatIdx() - 1; 2946 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2947 2948 // The way the format attribute works in GCC, the implicit this argument 2949 // of member functions is counted. However, it doesn't appear in our own 2950 // lists, so decrement format_idx in that case. 2951 if (IsCXXMember) { 2952 if(FSI->FormatIdx == 0) 2953 return false; 2954 --FSI->FormatIdx; 2955 if (FSI->FirstDataArg != 0) 2956 --FSI->FirstDataArg; 2957 } 2958 return true; 2959 } 2960 2961 /// Checks if a the given expression evaluates to null. 2962 /// 2963 /// Returns true if the value evaluates to null. 2964 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2965 // If the expression has non-null type, it doesn't evaluate to null. 2966 if (auto nullability 2967 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2968 if (*nullability == NullabilityKind::NonNull) 2969 return false; 2970 } 2971 2972 // As a special case, transparent unions initialized with zero are 2973 // considered null for the purposes of the nonnull attribute. 2974 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2975 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2976 if (const CompoundLiteralExpr *CLE = 2977 dyn_cast<CompoundLiteralExpr>(Expr)) 2978 if (const InitListExpr *ILE = 2979 dyn_cast<InitListExpr>(CLE->getInitializer())) 2980 Expr = ILE->getInit(0); 2981 } 2982 2983 bool Result; 2984 return (!Expr->isValueDependent() && 2985 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2986 !Result); 2987 } 2988 2989 static void CheckNonNullArgument(Sema &S, 2990 const Expr *ArgExpr, 2991 SourceLocation CallSiteLoc) { 2992 if (CheckNonNullExpr(S, ArgExpr)) 2993 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 2994 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 2995 } 2996 2997 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 2998 FormatStringInfo FSI; 2999 if ((GetFormatStringType(Format) == FST_NSString) && 3000 getFormatStringInfo(Format, false, &FSI)) { 3001 Idx = FSI.FormatIdx; 3002 return true; 3003 } 3004 return false; 3005 } 3006 3007 /// Diagnose use of %s directive in an NSString which is being passed 3008 /// as formatting string to formatting method. 3009 static void 3010 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3011 const NamedDecl *FDecl, 3012 Expr **Args, 3013 unsigned NumArgs) { 3014 unsigned Idx = 0; 3015 bool Format = false; 3016 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3017 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3018 Idx = 2; 3019 Format = true; 3020 } 3021 else 3022 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3023 if (S.GetFormatNSStringIdx(I, Idx)) { 3024 Format = true; 3025 break; 3026 } 3027 } 3028 if (!Format || NumArgs <= Idx) 3029 return; 3030 const Expr *FormatExpr = Args[Idx]; 3031 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3032 FormatExpr = CSCE->getSubExpr(); 3033 const StringLiteral *FormatString; 3034 if (const ObjCStringLiteral *OSL = 3035 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3036 FormatString = OSL->getString(); 3037 else 3038 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3039 if (!FormatString) 3040 return; 3041 if (S.FormatStringHasSArg(FormatString)) { 3042 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3043 << "%s" << 1 << 1; 3044 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3045 << FDecl->getDeclName(); 3046 } 3047 } 3048 3049 /// Determine whether the given type has a non-null nullability annotation. 3050 static bool isNonNullType(ASTContext &ctx, QualType type) { 3051 if (auto nullability = type->getNullability(ctx)) 3052 return *nullability == NullabilityKind::NonNull; 3053 3054 return false; 3055 } 3056 3057 static void CheckNonNullArguments(Sema &S, 3058 const NamedDecl *FDecl, 3059 const FunctionProtoType *Proto, 3060 ArrayRef<const Expr *> Args, 3061 SourceLocation CallSiteLoc) { 3062 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3063 3064 // Check the attributes attached to the method/function itself. 3065 llvm::SmallBitVector NonNullArgs; 3066 if (FDecl) { 3067 // Handle the nonnull attribute on the function/method declaration itself. 3068 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3069 if (!NonNull->args_size()) { 3070 // Easy case: all pointer arguments are nonnull. 3071 for (const auto *Arg : Args) 3072 if (S.isValidPointerAttrType(Arg->getType())) 3073 CheckNonNullArgument(S, Arg, CallSiteLoc); 3074 return; 3075 } 3076 3077 for (const ParamIdx &Idx : NonNull->args()) { 3078 unsigned IdxAST = Idx.getASTIndex(); 3079 if (IdxAST >= Args.size()) 3080 continue; 3081 if (NonNullArgs.empty()) 3082 NonNullArgs.resize(Args.size()); 3083 NonNullArgs.set(IdxAST); 3084 } 3085 } 3086 } 3087 3088 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3089 // Handle the nonnull attribute on the parameters of the 3090 // function/method. 3091 ArrayRef<ParmVarDecl*> parms; 3092 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3093 parms = FD->parameters(); 3094 else 3095 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3096 3097 unsigned ParamIndex = 0; 3098 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3099 I != E; ++I, ++ParamIndex) { 3100 const ParmVarDecl *PVD = *I; 3101 if (PVD->hasAttr<NonNullAttr>() || 3102 isNonNullType(S.Context, PVD->getType())) { 3103 if (NonNullArgs.empty()) 3104 NonNullArgs.resize(Args.size()); 3105 3106 NonNullArgs.set(ParamIndex); 3107 } 3108 } 3109 } else { 3110 // If we have a non-function, non-method declaration but no 3111 // function prototype, try to dig out the function prototype. 3112 if (!Proto) { 3113 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3114 QualType type = VD->getType().getNonReferenceType(); 3115 if (auto pointerType = type->getAs<PointerType>()) 3116 type = pointerType->getPointeeType(); 3117 else if (auto blockType = type->getAs<BlockPointerType>()) 3118 type = blockType->getPointeeType(); 3119 // FIXME: data member pointers? 3120 3121 // Dig out the function prototype, if there is one. 3122 Proto = type->getAs<FunctionProtoType>(); 3123 } 3124 } 3125 3126 // Fill in non-null argument information from the nullability 3127 // information on the parameter types (if we have them). 3128 if (Proto) { 3129 unsigned Index = 0; 3130 for (auto paramType : Proto->getParamTypes()) { 3131 if (isNonNullType(S.Context, paramType)) { 3132 if (NonNullArgs.empty()) 3133 NonNullArgs.resize(Args.size()); 3134 3135 NonNullArgs.set(Index); 3136 } 3137 3138 ++Index; 3139 } 3140 } 3141 } 3142 3143 // Check for non-null arguments. 3144 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3145 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3146 if (NonNullArgs[ArgIndex]) 3147 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3148 } 3149 } 3150 3151 /// Handles the checks for format strings, non-POD arguments to vararg 3152 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3153 /// attributes. 3154 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3155 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3156 bool IsMemberFunction, SourceLocation Loc, 3157 SourceRange Range, VariadicCallType CallType) { 3158 // FIXME: We should check as much as we can in the template definition. 3159 if (CurContext->isDependentContext()) 3160 return; 3161 3162 // Printf and scanf checking. 3163 llvm::SmallBitVector CheckedVarArgs; 3164 if (FDecl) { 3165 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3166 // Only create vector if there are format attributes. 3167 CheckedVarArgs.resize(Args.size()); 3168 3169 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3170 CheckedVarArgs); 3171 } 3172 } 3173 3174 // Refuse POD arguments that weren't caught by the format string 3175 // checks above. 3176 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3177 if (CallType != VariadicDoesNotApply && 3178 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3179 unsigned NumParams = Proto ? Proto->getNumParams() 3180 : FDecl && isa<FunctionDecl>(FDecl) 3181 ? cast<FunctionDecl>(FDecl)->getNumParams() 3182 : FDecl && isa<ObjCMethodDecl>(FDecl) 3183 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3184 : 0; 3185 3186 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3187 // Args[ArgIdx] can be null in malformed code. 3188 if (const Expr *Arg = Args[ArgIdx]) { 3189 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3190 checkVariadicArgument(Arg, CallType); 3191 } 3192 } 3193 } 3194 3195 if (FDecl || Proto) { 3196 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3197 3198 // Type safety checking. 3199 if (FDecl) { 3200 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3201 CheckArgumentWithTypeTag(I, Args, Loc); 3202 } 3203 } 3204 3205 if (FD) 3206 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3207 } 3208 3209 /// CheckConstructorCall - Check a constructor call for correctness and safety 3210 /// properties not enforced by the C type system. 3211 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 3212 ArrayRef<const Expr *> Args, 3213 const FunctionProtoType *Proto, 3214 SourceLocation Loc) { 3215 VariadicCallType CallType = 3216 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3217 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 3218 Loc, SourceRange(), CallType); 3219 } 3220 3221 /// CheckFunctionCall - Check a direct function call for various correctness 3222 /// and safety properties not strictly enforced by the C type system. 3223 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 3224 const FunctionProtoType *Proto) { 3225 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 3226 isa<CXXMethodDecl>(FDecl); 3227 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 3228 IsMemberOperatorCall; 3229 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 3230 TheCall->getCallee()); 3231 Expr** Args = TheCall->getArgs(); 3232 unsigned NumArgs = TheCall->getNumArgs(); 3233 3234 Expr *ImplicitThis = nullptr; 3235 if (IsMemberOperatorCall) { 3236 // If this is a call to a member operator, hide the first argument 3237 // from checkCall. 3238 // FIXME: Our choice of AST representation here is less than ideal. 3239 ImplicitThis = Args[0]; 3240 ++Args; 3241 --NumArgs; 3242 } else if (IsMemberFunction) 3243 ImplicitThis = 3244 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 3245 3246 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 3247 IsMemberFunction, TheCall->getRParenLoc(), 3248 TheCall->getCallee()->getSourceRange(), CallType); 3249 3250 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3251 // None of the checks below are needed for functions that don't have 3252 // simple names (e.g., C++ conversion functions). 3253 if (!FnInfo) 3254 return false; 3255 3256 CheckAbsoluteValueFunction(TheCall, FDecl); 3257 CheckMaxUnsignedZero(TheCall, FDecl); 3258 3259 if (getLangOpts().ObjC1) 3260 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 3261 3262 unsigned CMId = FDecl->getMemoryFunctionKind(); 3263 if (CMId == 0) 3264 return false; 3265 3266 // Handle memory setting and copying functions. 3267 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 3268 CheckStrlcpycatArguments(TheCall, FnInfo); 3269 else if (CMId == Builtin::BIstrncat) 3270 CheckStrncatArguments(TheCall, FnInfo); 3271 else 3272 CheckMemaccessArguments(TheCall, CMId, FnInfo); 3273 3274 return false; 3275 } 3276 3277 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 3278 ArrayRef<const Expr *> Args) { 3279 VariadicCallType CallType = 3280 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 3281 3282 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 3283 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 3284 CallType); 3285 3286 return false; 3287 } 3288 3289 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 3290 const FunctionProtoType *Proto) { 3291 QualType Ty; 3292 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 3293 Ty = V->getType().getNonReferenceType(); 3294 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 3295 Ty = F->getType().getNonReferenceType(); 3296 else 3297 return false; 3298 3299 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 3300 !Ty->isFunctionProtoType()) 3301 return false; 3302 3303 VariadicCallType CallType; 3304 if (!Proto || !Proto->isVariadic()) { 3305 CallType = VariadicDoesNotApply; 3306 } else if (Ty->isBlockPointerType()) { 3307 CallType = VariadicBlock; 3308 } else { // Ty->isFunctionPointerType() 3309 CallType = VariadicFunction; 3310 } 3311 3312 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 3313 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3314 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3315 TheCall->getCallee()->getSourceRange(), CallType); 3316 3317 return false; 3318 } 3319 3320 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 3321 /// such as function pointers returned from functions. 3322 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 3323 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 3324 TheCall->getCallee()); 3325 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 3326 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3327 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3328 TheCall->getCallee()->getSourceRange(), CallType); 3329 3330 return false; 3331 } 3332 3333 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 3334 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 3335 return false; 3336 3337 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 3338 switch (Op) { 3339 case AtomicExpr::AO__c11_atomic_init: 3340 case AtomicExpr::AO__opencl_atomic_init: 3341 llvm_unreachable("There is no ordering argument for an init"); 3342 3343 case AtomicExpr::AO__c11_atomic_load: 3344 case AtomicExpr::AO__opencl_atomic_load: 3345 case AtomicExpr::AO__atomic_load_n: 3346 case AtomicExpr::AO__atomic_load: 3347 return OrderingCABI != llvm::AtomicOrderingCABI::release && 3348 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3349 3350 case AtomicExpr::AO__c11_atomic_store: 3351 case AtomicExpr::AO__opencl_atomic_store: 3352 case AtomicExpr::AO__atomic_store: 3353 case AtomicExpr::AO__atomic_store_n: 3354 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 3355 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 3356 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3357 3358 default: 3359 return true; 3360 } 3361 } 3362 3363 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 3364 AtomicExpr::AtomicOp Op) { 3365 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3366 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3367 3368 // All the non-OpenCL operations take one of the following forms. 3369 // The OpenCL operations take the __c11 forms with one extra argument for 3370 // synchronization scope. 3371 enum { 3372 // C __c11_atomic_init(A *, C) 3373 Init, 3374 3375 // C __c11_atomic_load(A *, int) 3376 Load, 3377 3378 // void __atomic_load(A *, CP, int) 3379 LoadCopy, 3380 3381 // void __atomic_store(A *, CP, int) 3382 Copy, 3383 3384 // C __c11_atomic_add(A *, M, int) 3385 Arithmetic, 3386 3387 // C __atomic_exchange_n(A *, CP, int) 3388 Xchg, 3389 3390 // void __atomic_exchange(A *, C *, CP, int) 3391 GNUXchg, 3392 3393 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 3394 C11CmpXchg, 3395 3396 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 3397 GNUCmpXchg 3398 } Form = Init; 3399 3400 const unsigned NumForm = GNUCmpXchg + 1; 3401 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 3402 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 3403 // where: 3404 // C is an appropriate type, 3405 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 3406 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 3407 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 3408 // the int parameters are for orderings. 3409 3410 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 3411 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 3412 "need to update code for modified forms"); 3413 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 3414 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 3415 AtomicExpr::AO__atomic_load, 3416 "need to update code for modified C11 atomics"); 3417 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 3418 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 3419 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 3420 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 3421 IsOpenCL; 3422 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 3423 Op == AtomicExpr::AO__atomic_store_n || 3424 Op == AtomicExpr::AO__atomic_exchange_n || 3425 Op == AtomicExpr::AO__atomic_compare_exchange_n; 3426 bool IsAddSub = false; 3427 bool IsMinMax = false; 3428 3429 switch (Op) { 3430 case AtomicExpr::AO__c11_atomic_init: 3431 case AtomicExpr::AO__opencl_atomic_init: 3432 Form = Init; 3433 break; 3434 3435 case AtomicExpr::AO__c11_atomic_load: 3436 case AtomicExpr::AO__opencl_atomic_load: 3437 case AtomicExpr::AO__atomic_load_n: 3438 Form = Load; 3439 break; 3440 3441 case AtomicExpr::AO__atomic_load: 3442 Form = LoadCopy; 3443 break; 3444 3445 case AtomicExpr::AO__c11_atomic_store: 3446 case AtomicExpr::AO__opencl_atomic_store: 3447 case AtomicExpr::AO__atomic_store: 3448 case AtomicExpr::AO__atomic_store_n: 3449 Form = Copy; 3450 break; 3451 3452 case AtomicExpr::AO__c11_atomic_fetch_add: 3453 case AtomicExpr::AO__c11_atomic_fetch_sub: 3454 case AtomicExpr::AO__opencl_atomic_fetch_add: 3455 case AtomicExpr::AO__opencl_atomic_fetch_sub: 3456 case AtomicExpr::AO__opencl_atomic_fetch_min: 3457 case AtomicExpr::AO__opencl_atomic_fetch_max: 3458 case AtomicExpr::AO__atomic_fetch_add: 3459 case AtomicExpr::AO__atomic_fetch_sub: 3460 case AtomicExpr::AO__atomic_add_fetch: 3461 case AtomicExpr::AO__atomic_sub_fetch: 3462 IsAddSub = true; 3463 LLVM_FALLTHROUGH; 3464 case AtomicExpr::AO__c11_atomic_fetch_and: 3465 case AtomicExpr::AO__c11_atomic_fetch_or: 3466 case AtomicExpr::AO__c11_atomic_fetch_xor: 3467 case AtomicExpr::AO__opencl_atomic_fetch_and: 3468 case AtomicExpr::AO__opencl_atomic_fetch_or: 3469 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3470 case AtomicExpr::AO__atomic_fetch_and: 3471 case AtomicExpr::AO__atomic_fetch_or: 3472 case AtomicExpr::AO__atomic_fetch_xor: 3473 case AtomicExpr::AO__atomic_fetch_nand: 3474 case AtomicExpr::AO__atomic_and_fetch: 3475 case AtomicExpr::AO__atomic_or_fetch: 3476 case AtomicExpr::AO__atomic_xor_fetch: 3477 case AtomicExpr::AO__atomic_nand_fetch: 3478 Form = Arithmetic; 3479 break; 3480 3481 case AtomicExpr::AO__atomic_fetch_min: 3482 case AtomicExpr::AO__atomic_fetch_max: 3483 IsMinMax = true; 3484 Form = Arithmetic; 3485 break; 3486 3487 case AtomicExpr::AO__c11_atomic_exchange: 3488 case AtomicExpr::AO__opencl_atomic_exchange: 3489 case AtomicExpr::AO__atomic_exchange_n: 3490 Form = Xchg; 3491 break; 3492 3493 case AtomicExpr::AO__atomic_exchange: 3494 Form = GNUXchg; 3495 break; 3496 3497 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3498 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3499 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3500 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3501 Form = C11CmpXchg; 3502 break; 3503 3504 case AtomicExpr::AO__atomic_compare_exchange: 3505 case AtomicExpr::AO__atomic_compare_exchange_n: 3506 Form = GNUCmpXchg; 3507 break; 3508 } 3509 3510 unsigned AdjustedNumArgs = NumArgs[Form]; 3511 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 3512 ++AdjustedNumArgs; 3513 // Check we have the right number of arguments. 3514 if (TheCall->getNumArgs() < AdjustedNumArgs) { 3515 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3516 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3517 << TheCall->getCallee()->getSourceRange(); 3518 return ExprError(); 3519 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3520 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3521 diag::err_typecheck_call_too_many_args) 3522 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3523 << TheCall->getCallee()->getSourceRange(); 3524 return ExprError(); 3525 } 3526 3527 // Inspect the first argument of the atomic operation. 3528 Expr *Ptr = TheCall->getArg(0); 3529 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3530 if (ConvertedPtr.isInvalid()) 3531 return ExprError(); 3532 3533 Ptr = ConvertedPtr.get(); 3534 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3535 if (!pointerType) { 3536 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3537 << Ptr->getType() << Ptr->getSourceRange(); 3538 return ExprError(); 3539 } 3540 3541 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3542 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3543 QualType ValType = AtomTy; // 'C' 3544 if (IsC11) { 3545 if (!AtomTy->isAtomicType()) { 3546 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3547 << Ptr->getType() << Ptr->getSourceRange(); 3548 return ExprError(); 3549 } 3550 if (AtomTy.isConstQualified() || 3551 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3552 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3553 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3554 << Ptr->getSourceRange(); 3555 return ExprError(); 3556 } 3557 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3558 } else if (Form != Load && Form != LoadCopy) { 3559 if (ValType.isConstQualified()) { 3560 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3561 << Ptr->getType() << Ptr->getSourceRange(); 3562 return ExprError(); 3563 } 3564 } 3565 3566 // For an arithmetic operation, the implied arithmetic must be well-formed. 3567 if (Form == Arithmetic) { 3568 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3569 if (IsAddSub && !ValType->isIntegerType() 3570 && !ValType->isPointerType()) { 3571 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3572 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3573 return ExprError(); 3574 } 3575 if (IsMinMax) { 3576 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 3577 if (!BT || (BT->getKind() != BuiltinType::Int && 3578 BT->getKind() != BuiltinType::UInt)) { 3579 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr); 3580 return ExprError(); 3581 } 3582 } 3583 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 3584 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3585 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3586 return ExprError(); 3587 } 3588 if (IsC11 && ValType->isPointerType() && 3589 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3590 diag::err_incomplete_type)) { 3591 return ExprError(); 3592 } 3593 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3594 // For __atomic_*_n operations, the value type must be a scalar integral or 3595 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3596 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3597 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3598 return ExprError(); 3599 } 3600 3601 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3602 !AtomTy->isScalarType()) { 3603 // For GNU atomics, require a trivially-copyable type. This is not part of 3604 // the GNU atomics specification, but we enforce it for sanity. 3605 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3606 << Ptr->getType() << Ptr->getSourceRange(); 3607 return ExprError(); 3608 } 3609 3610 switch (ValType.getObjCLifetime()) { 3611 case Qualifiers::OCL_None: 3612 case Qualifiers::OCL_ExplicitNone: 3613 // okay 3614 break; 3615 3616 case Qualifiers::OCL_Weak: 3617 case Qualifiers::OCL_Strong: 3618 case Qualifiers::OCL_Autoreleasing: 3619 // FIXME: Can this happen? By this point, ValType should be known 3620 // to be trivially copyable. 3621 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3622 << ValType << Ptr->getSourceRange(); 3623 return ExprError(); 3624 } 3625 3626 // All atomic operations have an overload which takes a pointer to a volatile 3627 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 3628 // into the result or the other operands. Similarly atomic_load takes a 3629 // pointer to a const 'A'. 3630 ValType.removeLocalVolatile(); 3631 ValType.removeLocalConst(); 3632 QualType ResultType = ValType; 3633 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3634 Form == Init) 3635 ResultType = Context.VoidTy; 3636 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3637 ResultType = Context.BoolTy; 3638 3639 // The type of a parameter passed 'by value'. In the GNU atomics, such 3640 // arguments are actually passed as pointers. 3641 QualType ByValType = ValType; // 'CP' 3642 bool IsPassedByAddress = false; 3643 if (!IsC11 && !IsN) { 3644 ByValType = Ptr->getType(); 3645 IsPassedByAddress = true; 3646 } 3647 3648 // The first argument's non-CV pointer type is used to deduce the type of 3649 // subsequent arguments, except for: 3650 // - weak flag (always converted to bool) 3651 // - memory order (always converted to int) 3652 // - scope (always converted to int) 3653 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3654 QualType Ty; 3655 if (i < NumVals[Form] + 1) { 3656 switch (i) { 3657 case 0: 3658 // The first argument is always a pointer. It has a fixed type. 3659 // It is always dereferenced, a nullptr is undefined. 3660 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3661 // Nothing else to do: we already know all we want about this pointer. 3662 continue; 3663 case 1: 3664 // The second argument is the non-atomic operand. For arithmetic, this 3665 // is always passed by value, and for a compare_exchange it is always 3666 // passed by address. For the rest, GNU uses by-address and C11 uses 3667 // by-value. 3668 assert(Form != Load); 3669 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3670 Ty = ValType; 3671 else if (Form == Copy || Form == Xchg) { 3672 if (IsPassedByAddress) 3673 // The value pointer is always dereferenced, a nullptr is undefined. 3674 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3675 Ty = ByValType; 3676 } else if (Form == Arithmetic) 3677 Ty = Context.getPointerDiffType(); 3678 else { 3679 Expr *ValArg = TheCall->getArg(i); 3680 // The value pointer is always dereferenced, a nullptr is undefined. 3681 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3682 LangAS AS = LangAS::Default; 3683 // Keep address space of non-atomic pointer type. 3684 if (const PointerType *PtrTy = 3685 ValArg->getType()->getAs<PointerType>()) { 3686 AS = PtrTy->getPointeeType().getAddressSpace(); 3687 } 3688 Ty = Context.getPointerType( 3689 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3690 } 3691 break; 3692 case 2: 3693 // The third argument to compare_exchange / GNU exchange is the desired 3694 // value, either by-value (for the C11 and *_n variant) or as a pointer. 3695 if (IsPassedByAddress) 3696 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3697 Ty = ByValType; 3698 break; 3699 case 3: 3700 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3701 Ty = Context.BoolTy; 3702 break; 3703 } 3704 } else { 3705 // The order(s) and scope are always converted to int. 3706 Ty = Context.IntTy; 3707 } 3708 3709 InitializedEntity Entity = 3710 InitializedEntity::InitializeParameter(Context, Ty, false); 3711 ExprResult Arg = TheCall->getArg(i); 3712 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3713 if (Arg.isInvalid()) 3714 return true; 3715 TheCall->setArg(i, Arg.get()); 3716 } 3717 3718 // Permute the arguments into a 'consistent' order. 3719 SmallVector<Expr*, 5> SubExprs; 3720 SubExprs.push_back(Ptr); 3721 switch (Form) { 3722 case Init: 3723 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3724 SubExprs.push_back(TheCall->getArg(1)); // Val1 3725 break; 3726 case Load: 3727 SubExprs.push_back(TheCall->getArg(1)); // Order 3728 break; 3729 case LoadCopy: 3730 case Copy: 3731 case Arithmetic: 3732 case Xchg: 3733 SubExprs.push_back(TheCall->getArg(2)); // Order 3734 SubExprs.push_back(TheCall->getArg(1)); // Val1 3735 break; 3736 case GNUXchg: 3737 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3738 SubExprs.push_back(TheCall->getArg(3)); // Order 3739 SubExprs.push_back(TheCall->getArg(1)); // Val1 3740 SubExprs.push_back(TheCall->getArg(2)); // Val2 3741 break; 3742 case C11CmpXchg: 3743 SubExprs.push_back(TheCall->getArg(3)); // Order 3744 SubExprs.push_back(TheCall->getArg(1)); // Val1 3745 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3746 SubExprs.push_back(TheCall->getArg(2)); // Val2 3747 break; 3748 case GNUCmpXchg: 3749 SubExprs.push_back(TheCall->getArg(4)); // Order 3750 SubExprs.push_back(TheCall->getArg(1)); // Val1 3751 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3752 SubExprs.push_back(TheCall->getArg(2)); // Val2 3753 SubExprs.push_back(TheCall->getArg(3)); // Weak 3754 break; 3755 } 3756 3757 if (SubExprs.size() >= 2 && Form != Init) { 3758 llvm::APSInt Result(32); 3759 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3760 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3761 Diag(SubExprs[1]->getLocStart(), 3762 diag::warn_atomic_op_has_invalid_memory_order) 3763 << SubExprs[1]->getSourceRange(); 3764 } 3765 3766 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3767 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3768 llvm::APSInt Result(32); 3769 if (Scope->isIntegerConstantExpr(Result, Context) && 3770 !ScopeModel->isValid(Result.getZExtValue())) { 3771 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3772 << Scope->getSourceRange(); 3773 } 3774 SubExprs.push_back(Scope); 3775 } 3776 3777 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3778 SubExprs, ResultType, Op, 3779 TheCall->getRParenLoc()); 3780 3781 if ((Op == AtomicExpr::AO__c11_atomic_load || 3782 Op == AtomicExpr::AO__c11_atomic_store || 3783 Op == AtomicExpr::AO__opencl_atomic_load || 3784 Op == AtomicExpr::AO__opencl_atomic_store ) && 3785 Context.AtomicUsesUnsupportedLibcall(AE)) 3786 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3787 << ((Op == AtomicExpr::AO__c11_atomic_load || 3788 Op == AtomicExpr::AO__opencl_atomic_load) 3789 ? 0 : 1); 3790 3791 return AE; 3792 } 3793 3794 /// checkBuiltinArgument - Given a call to a builtin function, perform 3795 /// normal type-checking on the given argument, updating the call in 3796 /// place. This is useful when a builtin function requires custom 3797 /// type-checking for some of its arguments but not necessarily all of 3798 /// them. 3799 /// 3800 /// Returns true on error. 3801 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3802 FunctionDecl *Fn = E->getDirectCallee(); 3803 assert(Fn && "builtin call without direct callee!"); 3804 3805 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3806 InitializedEntity Entity = 3807 InitializedEntity::InitializeParameter(S.Context, Param); 3808 3809 ExprResult Arg = E->getArg(0); 3810 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3811 if (Arg.isInvalid()) 3812 return true; 3813 3814 E->setArg(ArgIndex, Arg.get()); 3815 return false; 3816 } 3817 3818 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3819 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3820 /// type of its first argument. The main ActOnCallExpr routines have already 3821 /// promoted the types of arguments because all of these calls are prototyped as 3822 /// void(...). 3823 /// 3824 /// This function goes through and does final semantic checking for these 3825 /// builtins, 3826 ExprResult 3827 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3828 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3829 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3830 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3831 3832 // Ensure that we have at least one argument to do type inference from. 3833 if (TheCall->getNumArgs() < 1) { 3834 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3835 << 0 << 1 << TheCall->getNumArgs() 3836 << TheCall->getCallee()->getSourceRange(); 3837 return ExprError(); 3838 } 3839 3840 // Inspect the first argument of the atomic builtin. This should always be 3841 // a pointer type, whose element is an integral scalar or pointer type. 3842 // Because it is a pointer type, we don't have to worry about any implicit 3843 // casts here. 3844 // FIXME: We don't allow floating point scalars as input. 3845 Expr *FirstArg = TheCall->getArg(0); 3846 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3847 if (FirstArgResult.isInvalid()) 3848 return ExprError(); 3849 FirstArg = FirstArgResult.get(); 3850 TheCall->setArg(0, FirstArg); 3851 3852 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3853 if (!pointerType) { 3854 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3855 << FirstArg->getType() << FirstArg->getSourceRange(); 3856 return ExprError(); 3857 } 3858 3859 QualType ValType = pointerType->getPointeeType(); 3860 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3861 !ValType->isBlockPointerType()) { 3862 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3863 << FirstArg->getType() << FirstArg->getSourceRange(); 3864 return ExprError(); 3865 } 3866 3867 if (ValType.isConstQualified()) { 3868 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const) 3869 << FirstArg->getType() << FirstArg->getSourceRange(); 3870 return ExprError(); 3871 } 3872 3873 switch (ValType.getObjCLifetime()) { 3874 case Qualifiers::OCL_None: 3875 case Qualifiers::OCL_ExplicitNone: 3876 // okay 3877 break; 3878 3879 case Qualifiers::OCL_Weak: 3880 case Qualifiers::OCL_Strong: 3881 case Qualifiers::OCL_Autoreleasing: 3882 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3883 << ValType << FirstArg->getSourceRange(); 3884 return ExprError(); 3885 } 3886 3887 // Strip any qualifiers off ValType. 3888 ValType = ValType.getUnqualifiedType(); 3889 3890 // The majority of builtins return a value, but a few have special return 3891 // types, so allow them to override appropriately below. 3892 QualType ResultType = ValType; 3893 3894 // We need to figure out which concrete builtin this maps onto. For example, 3895 // __sync_fetch_and_add with a 2 byte object turns into 3896 // __sync_fetch_and_add_2. 3897 #define BUILTIN_ROW(x) \ 3898 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3899 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3900 3901 static const unsigned BuiltinIndices[][5] = { 3902 BUILTIN_ROW(__sync_fetch_and_add), 3903 BUILTIN_ROW(__sync_fetch_and_sub), 3904 BUILTIN_ROW(__sync_fetch_and_or), 3905 BUILTIN_ROW(__sync_fetch_and_and), 3906 BUILTIN_ROW(__sync_fetch_and_xor), 3907 BUILTIN_ROW(__sync_fetch_and_nand), 3908 3909 BUILTIN_ROW(__sync_add_and_fetch), 3910 BUILTIN_ROW(__sync_sub_and_fetch), 3911 BUILTIN_ROW(__sync_and_and_fetch), 3912 BUILTIN_ROW(__sync_or_and_fetch), 3913 BUILTIN_ROW(__sync_xor_and_fetch), 3914 BUILTIN_ROW(__sync_nand_and_fetch), 3915 3916 BUILTIN_ROW(__sync_val_compare_and_swap), 3917 BUILTIN_ROW(__sync_bool_compare_and_swap), 3918 BUILTIN_ROW(__sync_lock_test_and_set), 3919 BUILTIN_ROW(__sync_lock_release), 3920 BUILTIN_ROW(__sync_swap) 3921 }; 3922 #undef BUILTIN_ROW 3923 3924 // Determine the index of the size. 3925 unsigned SizeIndex; 3926 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3927 case 1: SizeIndex = 0; break; 3928 case 2: SizeIndex = 1; break; 3929 case 4: SizeIndex = 2; break; 3930 case 8: SizeIndex = 3; break; 3931 case 16: SizeIndex = 4; break; 3932 default: 3933 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3934 << FirstArg->getType() << FirstArg->getSourceRange(); 3935 return ExprError(); 3936 } 3937 3938 // Each of these builtins has one pointer argument, followed by some number of 3939 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3940 // that we ignore. Find out which row of BuiltinIndices to read from as well 3941 // as the number of fixed args. 3942 unsigned BuiltinID = FDecl->getBuiltinID(); 3943 unsigned BuiltinIndex, NumFixed = 1; 3944 bool WarnAboutSemanticsChange = false; 3945 switch (BuiltinID) { 3946 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3947 case Builtin::BI__sync_fetch_and_add: 3948 case Builtin::BI__sync_fetch_and_add_1: 3949 case Builtin::BI__sync_fetch_and_add_2: 3950 case Builtin::BI__sync_fetch_and_add_4: 3951 case Builtin::BI__sync_fetch_and_add_8: 3952 case Builtin::BI__sync_fetch_and_add_16: 3953 BuiltinIndex = 0; 3954 break; 3955 3956 case Builtin::BI__sync_fetch_and_sub: 3957 case Builtin::BI__sync_fetch_and_sub_1: 3958 case Builtin::BI__sync_fetch_and_sub_2: 3959 case Builtin::BI__sync_fetch_and_sub_4: 3960 case Builtin::BI__sync_fetch_and_sub_8: 3961 case Builtin::BI__sync_fetch_and_sub_16: 3962 BuiltinIndex = 1; 3963 break; 3964 3965 case Builtin::BI__sync_fetch_and_or: 3966 case Builtin::BI__sync_fetch_and_or_1: 3967 case Builtin::BI__sync_fetch_and_or_2: 3968 case Builtin::BI__sync_fetch_and_or_4: 3969 case Builtin::BI__sync_fetch_and_or_8: 3970 case Builtin::BI__sync_fetch_and_or_16: 3971 BuiltinIndex = 2; 3972 break; 3973 3974 case Builtin::BI__sync_fetch_and_and: 3975 case Builtin::BI__sync_fetch_and_and_1: 3976 case Builtin::BI__sync_fetch_and_and_2: 3977 case Builtin::BI__sync_fetch_and_and_4: 3978 case Builtin::BI__sync_fetch_and_and_8: 3979 case Builtin::BI__sync_fetch_and_and_16: 3980 BuiltinIndex = 3; 3981 break; 3982 3983 case Builtin::BI__sync_fetch_and_xor: 3984 case Builtin::BI__sync_fetch_and_xor_1: 3985 case Builtin::BI__sync_fetch_and_xor_2: 3986 case Builtin::BI__sync_fetch_and_xor_4: 3987 case Builtin::BI__sync_fetch_and_xor_8: 3988 case Builtin::BI__sync_fetch_and_xor_16: 3989 BuiltinIndex = 4; 3990 break; 3991 3992 case Builtin::BI__sync_fetch_and_nand: 3993 case Builtin::BI__sync_fetch_and_nand_1: 3994 case Builtin::BI__sync_fetch_and_nand_2: 3995 case Builtin::BI__sync_fetch_and_nand_4: 3996 case Builtin::BI__sync_fetch_and_nand_8: 3997 case Builtin::BI__sync_fetch_and_nand_16: 3998 BuiltinIndex = 5; 3999 WarnAboutSemanticsChange = true; 4000 break; 4001 4002 case Builtin::BI__sync_add_and_fetch: 4003 case Builtin::BI__sync_add_and_fetch_1: 4004 case Builtin::BI__sync_add_and_fetch_2: 4005 case Builtin::BI__sync_add_and_fetch_4: 4006 case Builtin::BI__sync_add_and_fetch_8: 4007 case Builtin::BI__sync_add_and_fetch_16: 4008 BuiltinIndex = 6; 4009 break; 4010 4011 case Builtin::BI__sync_sub_and_fetch: 4012 case Builtin::BI__sync_sub_and_fetch_1: 4013 case Builtin::BI__sync_sub_and_fetch_2: 4014 case Builtin::BI__sync_sub_and_fetch_4: 4015 case Builtin::BI__sync_sub_and_fetch_8: 4016 case Builtin::BI__sync_sub_and_fetch_16: 4017 BuiltinIndex = 7; 4018 break; 4019 4020 case Builtin::BI__sync_and_and_fetch: 4021 case Builtin::BI__sync_and_and_fetch_1: 4022 case Builtin::BI__sync_and_and_fetch_2: 4023 case Builtin::BI__sync_and_and_fetch_4: 4024 case Builtin::BI__sync_and_and_fetch_8: 4025 case Builtin::BI__sync_and_and_fetch_16: 4026 BuiltinIndex = 8; 4027 break; 4028 4029 case Builtin::BI__sync_or_and_fetch: 4030 case Builtin::BI__sync_or_and_fetch_1: 4031 case Builtin::BI__sync_or_and_fetch_2: 4032 case Builtin::BI__sync_or_and_fetch_4: 4033 case Builtin::BI__sync_or_and_fetch_8: 4034 case Builtin::BI__sync_or_and_fetch_16: 4035 BuiltinIndex = 9; 4036 break; 4037 4038 case Builtin::BI__sync_xor_and_fetch: 4039 case Builtin::BI__sync_xor_and_fetch_1: 4040 case Builtin::BI__sync_xor_and_fetch_2: 4041 case Builtin::BI__sync_xor_and_fetch_4: 4042 case Builtin::BI__sync_xor_and_fetch_8: 4043 case Builtin::BI__sync_xor_and_fetch_16: 4044 BuiltinIndex = 10; 4045 break; 4046 4047 case Builtin::BI__sync_nand_and_fetch: 4048 case Builtin::BI__sync_nand_and_fetch_1: 4049 case Builtin::BI__sync_nand_and_fetch_2: 4050 case Builtin::BI__sync_nand_and_fetch_4: 4051 case Builtin::BI__sync_nand_and_fetch_8: 4052 case Builtin::BI__sync_nand_and_fetch_16: 4053 BuiltinIndex = 11; 4054 WarnAboutSemanticsChange = true; 4055 break; 4056 4057 case Builtin::BI__sync_val_compare_and_swap: 4058 case Builtin::BI__sync_val_compare_and_swap_1: 4059 case Builtin::BI__sync_val_compare_and_swap_2: 4060 case Builtin::BI__sync_val_compare_and_swap_4: 4061 case Builtin::BI__sync_val_compare_and_swap_8: 4062 case Builtin::BI__sync_val_compare_and_swap_16: 4063 BuiltinIndex = 12; 4064 NumFixed = 2; 4065 break; 4066 4067 case Builtin::BI__sync_bool_compare_and_swap: 4068 case Builtin::BI__sync_bool_compare_and_swap_1: 4069 case Builtin::BI__sync_bool_compare_and_swap_2: 4070 case Builtin::BI__sync_bool_compare_and_swap_4: 4071 case Builtin::BI__sync_bool_compare_and_swap_8: 4072 case Builtin::BI__sync_bool_compare_and_swap_16: 4073 BuiltinIndex = 13; 4074 NumFixed = 2; 4075 ResultType = Context.BoolTy; 4076 break; 4077 4078 case Builtin::BI__sync_lock_test_and_set: 4079 case Builtin::BI__sync_lock_test_and_set_1: 4080 case Builtin::BI__sync_lock_test_and_set_2: 4081 case Builtin::BI__sync_lock_test_and_set_4: 4082 case Builtin::BI__sync_lock_test_and_set_8: 4083 case Builtin::BI__sync_lock_test_and_set_16: 4084 BuiltinIndex = 14; 4085 break; 4086 4087 case Builtin::BI__sync_lock_release: 4088 case Builtin::BI__sync_lock_release_1: 4089 case Builtin::BI__sync_lock_release_2: 4090 case Builtin::BI__sync_lock_release_4: 4091 case Builtin::BI__sync_lock_release_8: 4092 case Builtin::BI__sync_lock_release_16: 4093 BuiltinIndex = 15; 4094 NumFixed = 0; 4095 ResultType = Context.VoidTy; 4096 break; 4097 4098 case Builtin::BI__sync_swap: 4099 case Builtin::BI__sync_swap_1: 4100 case Builtin::BI__sync_swap_2: 4101 case Builtin::BI__sync_swap_4: 4102 case Builtin::BI__sync_swap_8: 4103 case Builtin::BI__sync_swap_16: 4104 BuiltinIndex = 16; 4105 break; 4106 } 4107 4108 // Now that we know how many fixed arguments we expect, first check that we 4109 // have at least that many. 4110 if (TheCall->getNumArgs() < 1+NumFixed) { 4111 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 4112 << 0 << 1+NumFixed << TheCall->getNumArgs() 4113 << TheCall->getCallee()->getSourceRange(); 4114 return ExprError(); 4115 } 4116 4117 if (WarnAboutSemanticsChange) { 4118 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 4119 << TheCall->getCallee()->getSourceRange(); 4120 } 4121 4122 // Get the decl for the concrete builtin from this, we can tell what the 4123 // concrete integer type we should convert to is. 4124 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4125 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4126 FunctionDecl *NewBuiltinDecl; 4127 if (NewBuiltinID == BuiltinID) 4128 NewBuiltinDecl = FDecl; 4129 else { 4130 // Perform builtin lookup to avoid redeclaring it. 4131 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4132 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 4133 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4134 assert(Res.getFoundDecl()); 4135 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4136 if (!NewBuiltinDecl) 4137 return ExprError(); 4138 } 4139 4140 // The first argument --- the pointer --- has a fixed type; we 4141 // deduce the types of the rest of the arguments accordingly. Walk 4142 // the remaining arguments, converting them to the deduced value type. 4143 for (unsigned i = 0; i != NumFixed; ++i) { 4144 ExprResult Arg = TheCall->getArg(i+1); 4145 4146 // GCC does an implicit conversion to the pointer or integer ValType. This 4147 // can fail in some cases (1i -> int**), check for this error case now. 4148 // Initialize the argument. 4149 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4150 ValType, /*consume*/ false); 4151 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4152 if (Arg.isInvalid()) 4153 return ExprError(); 4154 4155 // Okay, we have something that *can* be converted to the right type. Check 4156 // to see if there is a potentially weird extension going on here. This can 4157 // happen when you do an atomic operation on something like an char* and 4158 // pass in 42. The 42 gets converted to char. This is even more strange 4159 // for things like 45.123 -> char, etc. 4160 // FIXME: Do this check. 4161 TheCall->setArg(i+1, Arg.get()); 4162 } 4163 4164 ASTContext& Context = this->getASTContext(); 4165 4166 // Create a new DeclRefExpr to refer to the new decl. 4167 DeclRefExpr* NewDRE = DeclRefExpr::Create( 4168 Context, 4169 DRE->getQualifierLoc(), 4170 SourceLocation(), 4171 NewBuiltinDecl, 4172 /*enclosing*/ false, 4173 DRE->getLocation(), 4174 Context.BuiltinFnTy, 4175 DRE->getValueKind()); 4176 4177 // Set the callee in the CallExpr. 4178 // FIXME: This loses syntactic information. 4179 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 4180 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 4181 CK_BuiltinFnToFnPtr); 4182 TheCall->setCallee(PromotedCall.get()); 4183 4184 // Change the result type of the call to match the original value type. This 4185 // is arbitrary, but the codegen for these builtins ins design to handle it 4186 // gracefully. 4187 TheCall->setType(ResultType); 4188 4189 return TheCallResult; 4190 } 4191 4192 /// SemaBuiltinNontemporalOverloaded - We have a call to 4193 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 4194 /// overloaded function based on the pointer type of its last argument. 4195 /// 4196 /// This function goes through and does final semantic checking for these 4197 /// builtins. 4198 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4199 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4200 DeclRefExpr *DRE = 4201 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4202 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4203 unsigned BuiltinID = FDecl->getBuiltinID(); 4204 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 4205 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 4206 "Unexpected nontemporal load/store builtin!"); 4207 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 4208 unsigned numArgs = isStore ? 2 : 1; 4209 4210 // Ensure that we have the proper number of arguments. 4211 if (checkArgCount(*this, TheCall, numArgs)) 4212 return ExprError(); 4213 4214 // Inspect the last argument of the nontemporal builtin. This should always 4215 // be a pointer type, from which we imply the type of the memory access. 4216 // Because it is a pointer type, we don't have to worry about any implicit 4217 // casts here. 4218 Expr *PointerArg = TheCall->getArg(numArgs - 1); 4219 ExprResult PointerArgResult = 4220 DefaultFunctionArrayLvalueConversion(PointerArg); 4221 4222 if (PointerArgResult.isInvalid()) 4223 return ExprError(); 4224 PointerArg = PointerArgResult.get(); 4225 TheCall->setArg(numArgs - 1, PointerArg); 4226 4227 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 4228 if (!pointerType) { 4229 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 4230 << PointerArg->getType() << PointerArg->getSourceRange(); 4231 return ExprError(); 4232 } 4233 4234 QualType ValType = pointerType->getPointeeType(); 4235 4236 // Strip any qualifiers off ValType. 4237 ValType = ValType.getUnqualifiedType(); 4238 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4239 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 4240 !ValType->isVectorType()) { 4241 Diag(DRE->getLocStart(), 4242 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 4243 << PointerArg->getType() << PointerArg->getSourceRange(); 4244 return ExprError(); 4245 } 4246 4247 if (!isStore) { 4248 TheCall->setType(ValType); 4249 return TheCallResult; 4250 } 4251 4252 ExprResult ValArg = TheCall->getArg(0); 4253 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4254 Context, ValType, /*consume*/ false); 4255 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 4256 if (ValArg.isInvalid()) 4257 return ExprError(); 4258 4259 TheCall->setArg(0, ValArg.get()); 4260 TheCall->setType(Context.VoidTy); 4261 return TheCallResult; 4262 } 4263 4264 /// CheckObjCString - Checks that the argument to the builtin 4265 /// CFString constructor is correct 4266 /// Note: It might also make sense to do the UTF-16 conversion here (would 4267 /// simplify the backend). 4268 bool Sema::CheckObjCString(Expr *Arg) { 4269 Arg = Arg->IgnoreParenCasts(); 4270 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 4271 4272 if (!Literal || !Literal->isAscii()) { 4273 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 4274 << Arg->getSourceRange(); 4275 return true; 4276 } 4277 4278 if (Literal->containsNonAsciiOrNull()) { 4279 StringRef String = Literal->getString(); 4280 unsigned NumBytes = String.size(); 4281 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 4282 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4283 llvm::UTF16 *ToPtr = &ToBuf[0]; 4284 4285 llvm::ConversionResult Result = 4286 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4287 ToPtr + NumBytes, llvm::strictConversion); 4288 // Check for conversion failure. 4289 if (Result != llvm::conversionOK) 4290 Diag(Arg->getLocStart(), 4291 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 4292 } 4293 return false; 4294 } 4295 4296 /// CheckObjCString - Checks that the format string argument to the os_log() 4297 /// and os_trace() functions is correct, and converts it to const char *. 4298 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 4299 Arg = Arg->IgnoreParenCasts(); 4300 auto *Literal = dyn_cast<StringLiteral>(Arg); 4301 if (!Literal) { 4302 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 4303 Literal = ObjcLiteral->getString(); 4304 } 4305 } 4306 4307 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 4308 return ExprError( 4309 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 4310 << Arg->getSourceRange()); 4311 } 4312 4313 ExprResult Result(Literal); 4314 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 4315 InitializedEntity Entity = 4316 InitializedEntity::InitializeParameter(Context, ResultTy, false); 4317 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 4318 return Result; 4319 } 4320 4321 /// Check that the user is calling the appropriate va_start builtin for the 4322 /// target and calling convention. 4323 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 4324 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 4325 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 4326 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 4327 bool IsWindows = TT.isOSWindows(); 4328 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 4329 if (IsX64 || IsAArch64) { 4330 CallingConv CC = CC_C; 4331 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 4332 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 4333 if (IsMSVAStart) { 4334 // Don't allow this in System V ABI functions. 4335 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 4336 return S.Diag(Fn->getLocStart(), 4337 diag::err_ms_va_start_used_in_sysv_function); 4338 } else { 4339 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 4340 // On x64 Windows, don't allow this in System V ABI functions. 4341 // (Yes, that means there's no corresponding way to support variadic 4342 // System V ABI functions on Windows.) 4343 if ((IsWindows && CC == CC_X86_64SysV) || 4344 (!IsWindows && CC == CC_Win64)) 4345 return S.Diag(Fn->getLocStart(), 4346 diag::err_va_start_used_in_wrong_abi_function) 4347 << !IsWindows; 4348 } 4349 return false; 4350 } 4351 4352 if (IsMSVAStart) 4353 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 4354 return false; 4355 } 4356 4357 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 4358 ParmVarDecl **LastParam = nullptr) { 4359 // Determine whether the current function, block, or obj-c method is variadic 4360 // and get its parameter list. 4361 bool IsVariadic = false; 4362 ArrayRef<ParmVarDecl *> Params; 4363 DeclContext *Caller = S.CurContext; 4364 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 4365 IsVariadic = Block->isVariadic(); 4366 Params = Block->parameters(); 4367 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 4368 IsVariadic = FD->isVariadic(); 4369 Params = FD->parameters(); 4370 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 4371 IsVariadic = MD->isVariadic(); 4372 // FIXME: This isn't correct for methods (results in bogus warning). 4373 Params = MD->parameters(); 4374 } else if (isa<CapturedDecl>(Caller)) { 4375 // We don't support va_start in a CapturedDecl. 4376 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 4377 return true; 4378 } else { 4379 // This must be some other declcontext that parses exprs. 4380 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 4381 return true; 4382 } 4383 4384 if (!IsVariadic) { 4385 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 4386 return true; 4387 } 4388 4389 if (LastParam) 4390 *LastParam = Params.empty() ? nullptr : Params.back(); 4391 4392 return false; 4393 } 4394 4395 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 4396 /// for validity. Emit an error and return true on failure; return false 4397 /// on success. 4398 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 4399 Expr *Fn = TheCall->getCallee(); 4400 4401 if (checkVAStartABI(*this, BuiltinID, Fn)) 4402 return true; 4403 4404 if (TheCall->getNumArgs() > 2) { 4405 Diag(TheCall->getArg(2)->getLocStart(), 4406 diag::err_typecheck_call_too_many_args) 4407 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4408 << Fn->getSourceRange() 4409 << SourceRange(TheCall->getArg(2)->getLocStart(), 4410 (*(TheCall->arg_end()-1))->getLocEnd()); 4411 return true; 4412 } 4413 4414 if (TheCall->getNumArgs() < 2) { 4415 return Diag(TheCall->getLocEnd(), 4416 diag::err_typecheck_call_too_few_args_at_least) 4417 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 4418 } 4419 4420 // Type-check the first argument normally. 4421 if (checkBuiltinArgument(*this, TheCall, 0)) 4422 return true; 4423 4424 // Check that the current function is variadic, and get its last parameter. 4425 ParmVarDecl *LastParam; 4426 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 4427 return true; 4428 4429 // Verify that the second argument to the builtin is the last argument of the 4430 // current function or method. 4431 bool SecondArgIsLastNamedArgument = false; 4432 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 4433 4434 // These are valid if SecondArgIsLastNamedArgument is false after the next 4435 // block. 4436 QualType Type; 4437 SourceLocation ParamLoc; 4438 bool IsCRegister = false; 4439 4440 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 4441 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 4442 SecondArgIsLastNamedArgument = PV == LastParam; 4443 4444 Type = PV->getType(); 4445 ParamLoc = PV->getLocation(); 4446 IsCRegister = 4447 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 4448 } 4449 } 4450 4451 if (!SecondArgIsLastNamedArgument) 4452 Diag(TheCall->getArg(1)->getLocStart(), 4453 diag::warn_second_arg_of_va_start_not_last_named_param); 4454 else if (IsCRegister || Type->isReferenceType() || 4455 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 4456 // Promotable integers are UB, but enumerations need a bit of 4457 // extra checking to see what their promotable type actually is. 4458 if (!Type->isPromotableIntegerType()) 4459 return false; 4460 if (!Type->isEnumeralType()) 4461 return true; 4462 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 4463 return !(ED && 4464 Context.typesAreCompatible(ED->getPromotionType(), Type)); 4465 }()) { 4466 unsigned Reason = 0; 4467 if (Type->isReferenceType()) Reason = 1; 4468 else if (IsCRegister) Reason = 2; 4469 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 4470 Diag(ParamLoc, diag::note_parameter_type) << Type; 4471 } 4472 4473 TheCall->setType(Context.VoidTy); 4474 return false; 4475 } 4476 4477 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 4478 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 4479 // const char *named_addr); 4480 4481 Expr *Func = Call->getCallee(); 4482 4483 if (Call->getNumArgs() < 3) 4484 return Diag(Call->getLocEnd(), 4485 diag::err_typecheck_call_too_few_args_at_least) 4486 << 0 /*function call*/ << 3 << Call->getNumArgs(); 4487 4488 // Type-check the first argument normally. 4489 if (checkBuiltinArgument(*this, Call, 0)) 4490 return true; 4491 4492 // Check that the current function is variadic. 4493 if (checkVAStartIsInVariadicFunction(*this, Func)) 4494 return true; 4495 4496 // __va_start on Windows does not validate the parameter qualifiers 4497 4498 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4499 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4500 4501 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4502 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4503 4504 const QualType &ConstCharPtrTy = 4505 Context.getPointerType(Context.CharTy.withConst()); 4506 if (!Arg1Ty->isPointerType() || 4507 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 4508 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 4509 << Arg1->getType() << ConstCharPtrTy 4510 << 1 /* different class */ 4511 << 0 /* qualifier difference */ 4512 << 3 /* parameter mismatch */ 4513 << 2 << Arg1->getType() << ConstCharPtrTy; 4514 4515 const QualType SizeTy = Context.getSizeType(); 4516 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4517 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 4518 << Arg2->getType() << SizeTy 4519 << 1 /* different class */ 4520 << 0 /* qualifier difference */ 4521 << 3 /* parameter mismatch */ 4522 << 3 << Arg2->getType() << SizeTy; 4523 4524 return false; 4525 } 4526 4527 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 4528 /// friends. This is declared to take (...), so we have to check everything. 4529 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 4530 if (TheCall->getNumArgs() < 2) 4531 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4532 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 4533 if (TheCall->getNumArgs() > 2) 4534 return Diag(TheCall->getArg(2)->getLocStart(), 4535 diag::err_typecheck_call_too_many_args) 4536 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4537 << SourceRange(TheCall->getArg(2)->getLocStart(), 4538 (*(TheCall->arg_end()-1))->getLocEnd()); 4539 4540 ExprResult OrigArg0 = TheCall->getArg(0); 4541 ExprResult OrigArg1 = TheCall->getArg(1); 4542 4543 // Do standard promotions between the two arguments, returning their common 4544 // type. 4545 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 4546 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4547 return true; 4548 4549 // Make sure any conversions are pushed back into the call; this is 4550 // type safe since unordered compare builtins are declared as "_Bool 4551 // foo(...)". 4552 TheCall->setArg(0, OrigArg0.get()); 4553 TheCall->setArg(1, OrigArg1.get()); 4554 4555 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4556 return false; 4557 4558 // If the common type isn't a real floating type, then the arguments were 4559 // invalid for this operation. 4560 if (Res.isNull() || !Res->isRealFloatingType()) 4561 return Diag(OrigArg0.get()->getLocStart(), 4562 diag::err_typecheck_call_invalid_ordered_compare) 4563 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4564 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4565 4566 return false; 4567 } 4568 4569 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4570 /// __builtin_isnan and friends. This is declared to take (...), so we have 4571 /// to check everything. We expect the last argument to be a floating point 4572 /// value. 4573 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4574 if (TheCall->getNumArgs() < NumArgs) 4575 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4576 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4577 if (TheCall->getNumArgs() > NumArgs) 4578 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4579 diag::err_typecheck_call_too_many_args) 4580 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4581 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4582 (*(TheCall->arg_end()-1))->getLocEnd()); 4583 4584 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4585 4586 if (OrigArg->isTypeDependent()) 4587 return false; 4588 4589 // This operation requires a non-_Complex floating-point number. 4590 if (!OrigArg->getType()->isRealFloatingType()) 4591 return Diag(OrigArg->getLocStart(), 4592 diag::err_typecheck_call_invalid_unary_fp) 4593 << OrigArg->getType() << OrigArg->getSourceRange(); 4594 4595 // If this is an implicit conversion from float -> float or double, remove it. 4596 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4597 // Only remove standard FloatCasts, leaving other casts inplace 4598 if (Cast->getCastKind() == CK_FloatingCast) { 4599 Expr *CastArg = Cast->getSubExpr(); 4600 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4601 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4602 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) && 4603 "promotion from float to either float or double is the only expected cast here"); 4604 Cast->setSubExpr(nullptr); 4605 TheCall->setArg(NumArgs-1, CastArg); 4606 } 4607 } 4608 } 4609 4610 return false; 4611 } 4612 4613 // Customized Sema Checking for VSX builtins that have the following signature: 4614 // vector [...] builtinName(vector [...], vector [...], const int); 4615 // Which takes the same type of vectors (any legal vector type) for the first 4616 // two arguments and takes compile time constant for the third argument. 4617 // Example builtins are : 4618 // vector double vec_xxpermdi(vector double, vector double, int); 4619 // vector short vec_xxsldwi(vector short, vector short, int); 4620 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4621 unsigned ExpectedNumArgs = 3; 4622 if (TheCall->getNumArgs() < ExpectedNumArgs) 4623 return Diag(TheCall->getLocEnd(), 4624 diag::err_typecheck_call_too_few_args_at_least) 4625 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4626 << TheCall->getSourceRange(); 4627 4628 if (TheCall->getNumArgs() > ExpectedNumArgs) 4629 return Diag(TheCall->getLocEnd(), 4630 diag::err_typecheck_call_too_many_args_at_most) 4631 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4632 << TheCall->getSourceRange(); 4633 4634 // Check the third argument is a compile time constant 4635 llvm::APSInt Value; 4636 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4637 return Diag(TheCall->getLocStart(), 4638 diag::err_vsx_builtin_nonconstant_argument) 4639 << 3 /* argument index */ << TheCall->getDirectCallee() 4640 << SourceRange(TheCall->getArg(2)->getLocStart(), 4641 TheCall->getArg(2)->getLocEnd()); 4642 4643 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4644 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4645 4646 // Check the type of argument 1 and argument 2 are vectors. 4647 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4648 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4649 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4650 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4651 << TheCall->getDirectCallee() 4652 << SourceRange(TheCall->getArg(0)->getLocStart(), 4653 TheCall->getArg(1)->getLocEnd()); 4654 } 4655 4656 // Check the first two arguments are the same type. 4657 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4658 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4659 << TheCall->getDirectCallee() 4660 << SourceRange(TheCall->getArg(0)->getLocStart(), 4661 TheCall->getArg(1)->getLocEnd()); 4662 } 4663 4664 // When default clang type checking is turned off and the customized type 4665 // checking is used, the returning type of the function must be explicitly 4666 // set. Otherwise it is _Bool by default. 4667 TheCall->setType(Arg1Ty); 4668 4669 return false; 4670 } 4671 4672 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4673 // This is declared to take (...), so we have to check everything. 4674 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4675 if (TheCall->getNumArgs() < 2) 4676 return ExprError(Diag(TheCall->getLocEnd(), 4677 diag::err_typecheck_call_too_few_args_at_least) 4678 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4679 << TheCall->getSourceRange()); 4680 4681 // Determine which of the following types of shufflevector we're checking: 4682 // 1) unary, vector mask: (lhs, mask) 4683 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4684 QualType resType = TheCall->getArg(0)->getType(); 4685 unsigned numElements = 0; 4686 4687 if (!TheCall->getArg(0)->isTypeDependent() && 4688 !TheCall->getArg(1)->isTypeDependent()) { 4689 QualType LHSType = TheCall->getArg(0)->getType(); 4690 QualType RHSType = TheCall->getArg(1)->getType(); 4691 4692 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4693 return ExprError(Diag(TheCall->getLocStart(), 4694 diag::err_vec_builtin_non_vector) 4695 << TheCall->getDirectCallee() 4696 << SourceRange(TheCall->getArg(0)->getLocStart(), 4697 TheCall->getArg(1)->getLocEnd())); 4698 4699 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4700 unsigned numResElements = TheCall->getNumArgs() - 2; 4701 4702 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4703 // with mask. If so, verify that RHS is an integer vector type with the 4704 // same number of elts as lhs. 4705 if (TheCall->getNumArgs() == 2) { 4706 if (!RHSType->hasIntegerRepresentation() || 4707 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4708 return ExprError(Diag(TheCall->getLocStart(), 4709 diag::err_vec_builtin_incompatible_vector) 4710 << TheCall->getDirectCallee() 4711 << SourceRange(TheCall->getArg(1)->getLocStart(), 4712 TheCall->getArg(1)->getLocEnd())); 4713 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4714 return ExprError(Diag(TheCall->getLocStart(), 4715 diag::err_vec_builtin_incompatible_vector) 4716 << TheCall->getDirectCallee() 4717 << SourceRange(TheCall->getArg(0)->getLocStart(), 4718 TheCall->getArg(1)->getLocEnd())); 4719 } else if (numElements != numResElements) { 4720 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4721 resType = Context.getVectorType(eltType, numResElements, 4722 VectorType::GenericVector); 4723 } 4724 } 4725 4726 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4727 if (TheCall->getArg(i)->isTypeDependent() || 4728 TheCall->getArg(i)->isValueDependent()) 4729 continue; 4730 4731 llvm::APSInt Result(32); 4732 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4733 return ExprError(Diag(TheCall->getLocStart(), 4734 diag::err_shufflevector_nonconstant_argument) 4735 << TheCall->getArg(i)->getSourceRange()); 4736 4737 // Allow -1 which will be translated to undef in the IR. 4738 if (Result.isSigned() && Result.isAllOnesValue()) 4739 continue; 4740 4741 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4742 return ExprError(Diag(TheCall->getLocStart(), 4743 diag::err_shufflevector_argument_too_large) 4744 << TheCall->getArg(i)->getSourceRange()); 4745 } 4746 4747 SmallVector<Expr*, 32> exprs; 4748 4749 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4750 exprs.push_back(TheCall->getArg(i)); 4751 TheCall->setArg(i, nullptr); 4752 } 4753 4754 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4755 TheCall->getCallee()->getLocStart(), 4756 TheCall->getRParenLoc()); 4757 } 4758 4759 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4760 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4761 SourceLocation BuiltinLoc, 4762 SourceLocation RParenLoc) { 4763 ExprValueKind VK = VK_RValue; 4764 ExprObjectKind OK = OK_Ordinary; 4765 QualType DstTy = TInfo->getType(); 4766 QualType SrcTy = E->getType(); 4767 4768 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4769 return ExprError(Diag(BuiltinLoc, 4770 diag::err_convertvector_non_vector) 4771 << E->getSourceRange()); 4772 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4773 return ExprError(Diag(BuiltinLoc, 4774 diag::err_convertvector_non_vector_type)); 4775 4776 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4777 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4778 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4779 if (SrcElts != DstElts) 4780 return ExprError(Diag(BuiltinLoc, 4781 diag::err_convertvector_incompatible_vector) 4782 << E->getSourceRange()); 4783 } 4784 4785 return new (Context) 4786 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4787 } 4788 4789 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4790 // This is declared to take (const void*, ...) and can take two 4791 // optional constant int args. 4792 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4793 unsigned NumArgs = TheCall->getNumArgs(); 4794 4795 if (NumArgs > 3) 4796 return Diag(TheCall->getLocEnd(), 4797 diag::err_typecheck_call_too_many_args_at_most) 4798 << 0 /*function call*/ << 3 << NumArgs 4799 << TheCall->getSourceRange(); 4800 4801 // Argument 0 is checked for us and the remaining arguments must be 4802 // constant integers. 4803 for (unsigned i = 1; i != NumArgs; ++i) 4804 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4805 return true; 4806 4807 return false; 4808 } 4809 4810 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4811 // __assume does not evaluate its arguments, and should warn if its argument 4812 // has side effects. 4813 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4814 Expr *Arg = TheCall->getArg(0); 4815 if (Arg->isInstantiationDependent()) return false; 4816 4817 if (Arg->HasSideEffects(Context)) 4818 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4819 << Arg->getSourceRange() 4820 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4821 4822 return false; 4823 } 4824 4825 /// Handle __builtin_alloca_with_align. This is declared 4826 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4827 /// than 8. 4828 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4829 // The alignment must be a constant integer. 4830 Expr *Arg = TheCall->getArg(1); 4831 4832 // We can't check the value of a dependent argument. 4833 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4834 if (const auto *UE = 4835 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4836 if (UE->getKind() == UETT_AlignOf) 4837 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4838 << Arg->getSourceRange(); 4839 4840 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4841 4842 if (!Result.isPowerOf2()) 4843 return Diag(TheCall->getLocStart(), 4844 diag::err_alignment_not_power_of_two) 4845 << Arg->getSourceRange(); 4846 4847 if (Result < Context.getCharWidth()) 4848 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4849 << (unsigned)Context.getCharWidth() 4850 << Arg->getSourceRange(); 4851 4852 if (Result > std::numeric_limits<int32_t>::max()) 4853 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4854 << std::numeric_limits<int32_t>::max() 4855 << Arg->getSourceRange(); 4856 } 4857 4858 return false; 4859 } 4860 4861 /// Handle __builtin_assume_aligned. This is declared 4862 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4863 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4864 unsigned NumArgs = TheCall->getNumArgs(); 4865 4866 if (NumArgs > 3) 4867 return Diag(TheCall->getLocEnd(), 4868 diag::err_typecheck_call_too_many_args_at_most) 4869 << 0 /*function call*/ << 3 << NumArgs 4870 << TheCall->getSourceRange(); 4871 4872 // The alignment must be a constant integer. 4873 Expr *Arg = TheCall->getArg(1); 4874 4875 // We can't check the value of a dependent argument. 4876 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4877 llvm::APSInt Result; 4878 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4879 return true; 4880 4881 if (!Result.isPowerOf2()) 4882 return Diag(TheCall->getLocStart(), 4883 diag::err_alignment_not_power_of_two) 4884 << Arg->getSourceRange(); 4885 } 4886 4887 if (NumArgs > 2) { 4888 ExprResult Arg(TheCall->getArg(2)); 4889 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4890 Context.getSizeType(), false); 4891 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4892 if (Arg.isInvalid()) return true; 4893 TheCall->setArg(2, Arg.get()); 4894 } 4895 4896 return false; 4897 } 4898 4899 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4900 unsigned BuiltinID = 4901 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4902 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4903 4904 unsigned NumArgs = TheCall->getNumArgs(); 4905 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4906 if (NumArgs < NumRequiredArgs) { 4907 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4908 << 0 /* function call */ << NumRequiredArgs << NumArgs 4909 << TheCall->getSourceRange(); 4910 } 4911 if (NumArgs >= NumRequiredArgs + 0x100) { 4912 return Diag(TheCall->getLocEnd(), 4913 diag::err_typecheck_call_too_many_args_at_most) 4914 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4915 << TheCall->getSourceRange(); 4916 } 4917 unsigned i = 0; 4918 4919 // For formatting call, check buffer arg. 4920 if (!IsSizeCall) { 4921 ExprResult Arg(TheCall->getArg(i)); 4922 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4923 Context, Context.VoidPtrTy, false); 4924 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4925 if (Arg.isInvalid()) 4926 return true; 4927 TheCall->setArg(i, Arg.get()); 4928 i++; 4929 } 4930 4931 // Check string literal arg. 4932 unsigned FormatIdx = i; 4933 { 4934 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4935 if (Arg.isInvalid()) 4936 return true; 4937 TheCall->setArg(i, Arg.get()); 4938 i++; 4939 } 4940 4941 // Make sure variadic args are scalar. 4942 unsigned FirstDataArg = i; 4943 while (i < NumArgs) { 4944 ExprResult Arg = DefaultVariadicArgumentPromotion( 4945 TheCall->getArg(i), VariadicFunction, nullptr); 4946 if (Arg.isInvalid()) 4947 return true; 4948 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4949 if (ArgSize.getQuantity() >= 0x100) { 4950 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4951 << i << (int)ArgSize.getQuantity() << 0xff 4952 << TheCall->getSourceRange(); 4953 } 4954 TheCall->setArg(i, Arg.get()); 4955 i++; 4956 } 4957 4958 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4959 // call to avoid duplicate diagnostics. 4960 if (!IsSizeCall) { 4961 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4962 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4963 bool Success = CheckFormatArguments( 4964 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4965 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4966 CheckedVarArgs); 4967 if (!Success) 4968 return true; 4969 } 4970 4971 if (IsSizeCall) { 4972 TheCall->setType(Context.getSizeType()); 4973 } else { 4974 TheCall->setType(Context.VoidPtrTy); 4975 } 4976 return false; 4977 } 4978 4979 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4980 /// TheCall is a constant expression. 4981 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4982 llvm::APSInt &Result) { 4983 Expr *Arg = TheCall->getArg(ArgNum); 4984 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4985 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4986 4987 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 4988 4989 if (!Arg->isIntegerConstantExpr(Result, Context)) 4990 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 4991 << FDecl->getDeclName() << Arg->getSourceRange(); 4992 4993 return false; 4994 } 4995 4996 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 4997 /// TheCall is a constant expression in the range [Low, High]. 4998 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 4999 int Low, int High) { 5000 llvm::APSInt Result; 5001 5002 // We can't check the value of a dependent argument. 5003 Expr *Arg = TheCall->getArg(ArgNum); 5004 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5005 return false; 5006 5007 // Check constant-ness first. 5008 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5009 return true; 5010 5011 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) 5012 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 5013 << Low << High << Arg->getSourceRange(); 5014 5015 return false; 5016 } 5017 5018 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5019 /// TheCall is a constant expression is a multiple of Num.. 5020 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5021 unsigned Num) { 5022 llvm::APSInt Result; 5023 5024 // We can't check the value of a dependent argument. 5025 Expr *Arg = TheCall->getArg(ArgNum); 5026 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5027 return false; 5028 5029 // Check constant-ness first. 5030 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5031 return true; 5032 5033 if (Result.getSExtValue() % Num != 0) 5034 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 5035 << Num << Arg->getSourceRange(); 5036 5037 return false; 5038 } 5039 5040 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5041 /// TheCall is an ARM/AArch64 special register string literal. 5042 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5043 int ArgNum, unsigned ExpectedFieldNum, 5044 bool AllowName) { 5045 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5046 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5047 BuiltinID == ARM::BI__builtin_arm_rsr || 5048 BuiltinID == ARM::BI__builtin_arm_rsrp || 5049 BuiltinID == ARM::BI__builtin_arm_wsr || 5050 BuiltinID == ARM::BI__builtin_arm_wsrp; 5051 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5052 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5053 BuiltinID == AArch64::BI__builtin_arm_rsr || 5054 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5055 BuiltinID == AArch64::BI__builtin_arm_wsr || 5056 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5057 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5058 5059 // We can't check the value of a dependent argument. 5060 Expr *Arg = TheCall->getArg(ArgNum); 5061 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5062 return false; 5063 5064 // Check if the argument is a string literal. 5065 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5066 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 5067 << Arg->getSourceRange(); 5068 5069 // Check the type of special register given. 5070 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 5071 SmallVector<StringRef, 6> Fields; 5072 Reg.split(Fields, ":"); 5073 5074 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 5075 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 5076 << Arg->getSourceRange(); 5077 5078 // If the string is the name of a register then we cannot check that it is 5079 // valid here but if the string is of one the forms described in ACLE then we 5080 // can check that the supplied fields are integers and within the valid 5081 // ranges. 5082 if (Fields.size() > 1) { 5083 bool FiveFields = Fields.size() == 5; 5084 5085 bool ValidString = true; 5086 if (IsARMBuiltin) { 5087 ValidString &= Fields[0].startswith_lower("cp") || 5088 Fields[0].startswith_lower("p"); 5089 if (ValidString) 5090 Fields[0] = 5091 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 5092 5093 ValidString &= Fields[2].startswith_lower("c"); 5094 if (ValidString) 5095 Fields[2] = Fields[2].drop_front(1); 5096 5097 if (FiveFields) { 5098 ValidString &= Fields[3].startswith_lower("c"); 5099 if (ValidString) 5100 Fields[3] = Fields[3].drop_front(1); 5101 } 5102 } 5103 5104 SmallVector<int, 5> Ranges; 5105 if (FiveFields) 5106 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 5107 else 5108 Ranges.append({15, 7, 15}); 5109 5110 for (unsigned i=0; i<Fields.size(); ++i) { 5111 int IntField; 5112 ValidString &= !Fields[i].getAsInteger(10, IntField); 5113 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 5114 } 5115 5116 if (!ValidString) 5117 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 5118 << Arg->getSourceRange(); 5119 } else if (IsAArch64Builtin && Fields.size() == 1) { 5120 // If the register name is one of those that appear in the condition below 5121 // and the special register builtin being used is one of the write builtins, 5122 // then we require that the argument provided for writing to the register 5123 // is an integer constant expression. This is because it will be lowered to 5124 // an MSR (immediate) instruction, so we need to know the immediate at 5125 // compile time. 5126 if (TheCall->getNumArgs() != 2) 5127 return false; 5128 5129 std::string RegLower = Reg.lower(); 5130 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 5131 RegLower != "pan" && RegLower != "uao") 5132 return false; 5133 5134 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 5135 } 5136 5137 return false; 5138 } 5139 5140 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 5141 /// This checks that the target supports __builtin_longjmp and 5142 /// that val is a constant 1. 5143 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 5144 if (!Context.getTargetInfo().hasSjLjLowering()) 5145 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 5146 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 5147 5148 Expr *Arg = TheCall->getArg(1); 5149 llvm::APSInt Result; 5150 5151 // TODO: This is less than ideal. Overload this to take a value. 5152 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5153 return true; 5154 5155 if (Result != 1) 5156 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 5157 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 5158 5159 return false; 5160 } 5161 5162 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 5163 /// This checks that the target supports __builtin_setjmp. 5164 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 5165 if (!Context.getTargetInfo().hasSjLjLowering()) 5166 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 5167 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 5168 return false; 5169 } 5170 5171 namespace { 5172 5173 class UncoveredArgHandler { 5174 enum { Unknown = -1, AllCovered = -2 }; 5175 5176 signed FirstUncoveredArg = Unknown; 5177 SmallVector<const Expr *, 4> DiagnosticExprs; 5178 5179 public: 5180 UncoveredArgHandler() = default; 5181 5182 bool hasUncoveredArg() const { 5183 return (FirstUncoveredArg >= 0); 5184 } 5185 5186 unsigned getUncoveredArg() const { 5187 assert(hasUncoveredArg() && "no uncovered argument"); 5188 return FirstUncoveredArg; 5189 } 5190 5191 void setAllCovered() { 5192 // A string has been found with all arguments covered, so clear out 5193 // the diagnostics. 5194 DiagnosticExprs.clear(); 5195 FirstUncoveredArg = AllCovered; 5196 } 5197 5198 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 5199 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 5200 5201 // Don't update if a previous string covers all arguments. 5202 if (FirstUncoveredArg == AllCovered) 5203 return; 5204 5205 // UncoveredArgHandler tracks the highest uncovered argument index 5206 // and with it all the strings that match this index. 5207 if (NewFirstUncoveredArg == FirstUncoveredArg) 5208 DiagnosticExprs.push_back(StrExpr); 5209 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 5210 DiagnosticExprs.clear(); 5211 DiagnosticExprs.push_back(StrExpr); 5212 FirstUncoveredArg = NewFirstUncoveredArg; 5213 } 5214 } 5215 5216 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 5217 }; 5218 5219 enum StringLiteralCheckType { 5220 SLCT_NotALiteral, 5221 SLCT_UncheckedLiteral, 5222 SLCT_CheckedLiteral 5223 }; 5224 5225 } // namespace 5226 5227 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 5228 BinaryOperatorKind BinOpKind, 5229 bool AddendIsRight) { 5230 unsigned BitWidth = Offset.getBitWidth(); 5231 unsigned AddendBitWidth = Addend.getBitWidth(); 5232 // There might be negative interim results. 5233 if (Addend.isUnsigned()) { 5234 Addend = Addend.zext(++AddendBitWidth); 5235 Addend.setIsSigned(true); 5236 } 5237 // Adjust the bit width of the APSInts. 5238 if (AddendBitWidth > BitWidth) { 5239 Offset = Offset.sext(AddendBitWidth); 5240 BitWidth = AddendBitWidth; 5241 } else if (BitWidth > AddendBitWidth) { 5242 Addend = Addend.sext(BitWidth); 5243 } 5244 5245 bool Ov = false; 5246 llvm::APSInt ResOffset = Offset; 5247 if (BinOpKind == BO_Add) 5248 ResOffset = Offset.sadd_ov(Addend, Ov); 5249 else { 5250 assert(AddendIsRight && BinOpKind == BO_Sub && 5251 "operator must be add or sub with addend on the right"); 5252 ResOffset = Offset.ssub_ov(Addend, Ov); 5253 } 5254 5255 // We add an offset to a pointer here so we should support an offset as big as 5256 // possible. 5257 if (Ov) { 5258 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 5259 "index (intermediate) result too big"); 5260 Offset = Offset.sext(2 * BitWidth); 5261 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 5262 return; 5263 } 5264 5265 Offset = ResOffset; 5266 } 5267 5268 namespace { 5269 5270 // This is a wrapper class around StringLiteral to support offsetted string 5271 // literals as format strings. It takes the offset into account when returning 5272 // the string and its length or the source locations to display notes correctly. 5273 class FormatStringLiteral { 5274 const StringLiteral *FExpr; 5275 int64_t Offset; 5276 5277 public: 5278 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 5279 : FExpr(fexpr), Offset(Offset) {} 5280 5281 StringRef getString() const { 5282 return FExpr->getString().drop_front(Offset); 5283 } 5284 5285 unsigned getByteLength() const { 5286 return FExpr->getByteLength() - getCharByteWidth() * Offset; 5287 } 5288 5289 unsigned getLength() const { return FExpr->getLength() - Offset; } 5290 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 5291 5292 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 5293 5294 QualType getType() const { return FExpr->getType(); } 5295 5296 bool isAscii() const { return FExpr->isAscii(); } 5297 bool isWide() const { return FExpr->isWide(); } 5298 bool isUTF8() const { return FExpr->isUTF8(); } 5299 bool isUTF16() const { return FExpr->isUTF16(); } 5300 bool isUTF32() const { return FExpr->isUTF32(); } 5301 bool isPascal() const { return FExpr->isPascal(); } 5302 5303 SourceLocation getLocationOfByte( 5304 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 5305 const TargetInfo &Target, unsigned *StartToken = nullptr, 5306 unsigned *StartTokenByteOffset = nullptr) const { 5307 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 5308 StartToken, StartTokenByteOffset); 5309 } 5310 5311 SourceLocation getLocStart() const LLVM_READONLY { 5312 return FExpr->getLocStart().getLocWithOffset(Offset); 5313 } 5314 5315 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 5316 }; 5317 5318 } // namespace 5319 5320 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 5321 const Expr *OrigFormatExpr, 5322 ArrayRef<const Expr *> Args, 5323 bool HasVAListArg, unsigned format_idx, 5324 unsigned firstDataArg, 5325 Sema::FormatStringType Type, 5326 bool inFunctionCall, 5327 Sema::VariadicCallType CallType, 5328 llvm::SmallBitVector &CheckedVarArgs, 5329 UncoveredArgHandler &UncoveredArg); 5330 5331 // Determine if an expression is a string literal or constant string. 5332 // If this function returns false on the arguments to a function expecting a 5333 // format string, we will usually need to emit a warning. 5334 // True string literals are then checked by CheckFormatString. 5335 static StringLiteralCheckType 5336 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 5337 bool HasVAListArg, unsigned format_idx, 5338 unsigned firstDataArg, Sema::FormatStringType Type, 5339 Sema::VariadicCallType CallType, bool InFunctionCall, 5340 llvm::SmallBitVector &CheckedVarArgs, 5341 UncoveredArgHandler &UncoveredArg, 5342 llvm::APSInt Offset) { 5343 tryAgain: 5344 assert(Offset.isSigned() && "invalid offset"); 5345 5346 if (E->isTypeDependent() || E->isValueDependent()) 5347 return SLCT_NotALiteral; 5348 5349 E = E->IgnoreParenCasts(); 5350 5351 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 5352 // Technically -Wformat-nonliteral does not warn about this case. 5353 // The behavior of printf and friends in this case is implementation 5354 // dependent. Ideally if the format string cannot be null then 5355 // it should have a 'nonnull' attribute in the function prototype. 5356 return SLCT_UncheckedLiteral; 5357 5358 switch (E->getStmtClass()) { 5359 case Stmt::BinaryConditionalOperatorClass: 5360 case Stmt::ConditionalOperatorClass: { 5361 // The expression is a literal if both sub-expressions were, and it was 5362 // completely checked only if both sub-expressions were checked. 5363 const AbstractConditionalOperator *C = 5364 cast<AbstractConditionalOperator>(E); 5365 5366 // Determine whether it is necessary to check both sub-expressions, for 5367 // example, because the condition expression is a constant that can be 5368 // evaluated at compile time. 5369 bool CheckLeft = true, CheckRight = true; 5370 5371 bool Cond; 5372 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 5373 if (Cond) 5374 CheckRight = false; 5375 else 5376 CheckLeft = false; 5377 } 5378 5379 // We need to maintain the offsets for the right and the left hand side 5380 // separately to check if every possible indexed expression is a valid 5381 // string literal. They might have different offsets for different string 5382 // literals in the end. 5383 StringLiteralCheckType Left; 5384 if (!CheckLeft) 5385 Left = SLCT_UncheckedLiteral; 5386 else { 5387 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 5388 HasVAListArg, format_idx, firstDataArg, 5389 Type, CallType, InFunctionCall, 5390 CheckedVarArgs, UncoveredArg, Offset); 5391 if (Left == SLCT_NotALiteral || !CheckRight) { 5392 return Left; 5393 } 5394 } 5395 5396 StringLiteralCheckType Right = 5397 checkFormatStringExpr(S, C->getFalseExpr(), Args, 5398 HasVAListArg, format_idx, firstDataArg, 5399 Type, CallType, InFunctionCall, CheckedVarArgs, 5400 UncoveredArg, Offset); 5401 5402 return (CheckLeft && Left < Right) ? Left : Right; 5403 } 5404 5405 case Stmt::ImplicitCastExprClass: 5406 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 5407 goto tryAgain; 5408 5409 case Stmt::OpaqueValueExprClass: 5410 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 5411 E = src; 5412 goto tryAgain; 5413 } 5414 return SLCT_NotALiteral; 5415 5416 case Stmt::PredefinedExprClass: 5417 // While __func__, etc., are technically not string literals, they 5418 // cannot contain format specifiers and thus are not a security 5419 // liability. 5420 return SLCT_UncheckedLiteral; 5421 5422 case Stmt::DeclRefExprClass: { 5423 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 5424 5425 // As an exception, do not flag errors for variables binding to 5426 // const string literals. 5427 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 5428 bool isConstant = false; 5429 QualType T = DR->getType(); 5430 5431 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 5432 isConstant = AT->getElementType().isConstant(S.Context); 5433 } else if (const PointerType *PT = T->getAs<PointerType>()) { 5434 isConstant = T.isConstant(S.Context) && 5435 PT->getPointeeType().isConstant(S.Context); 5436 } else if (T->isObjCObjectPointerType()) { 5437 // In ObjC, there is usually no "const ObjectPointer" type, 5438 // so don't check if the pointee type is constant. 5439 isConstant = T.isConstant(S.Context); 5440 } 5441 5442 if (isConstant) { 5443 if (const Expr *Init = VD->getAnyInitializer()) { 5444 // Look through initializers like const char c[] = { "foo" } 5445 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 5446 if (InitList->isStringLiteralInit()) 5447 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 5448 } 5449 return checkFormatStringExpr(S, Init, Args, 5450 HasVAListArg, format_idx, 5451 firstDataArg, Type, CallType, 5452 /*InFunctionCall*/ false, CheckedVarArgs, 5453 UncoveredArg, Offset); 5454 } 5455 } 5456 5457 // For vprintf* functions (i.e., HasVAListArg==true), we add a 5458 // special check to see if the format string is a function parameter 5459 // of the function calling the printf function. If the function 5460 // has an attribute indicating it is a printf-like function, then we 5461 // should suppress warnings concerning non-literals being used in a call 5462 // to a vprintf function. For example: 5463 // 5464 // void 5465 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 5466 // va_list ap; 5467 // va_start(ap, fmt); 5468 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 5469 // ... 5470 // } 5471 if (HasVAListArg) { 5472 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 5473 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 5474 int PVIndex = PV->getFunctionScopeIndex() + 1; 5475 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 5476 // adjust for implicit parameter 5477 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5478 if (MD->isInstance()) 5479 ++PVIndex; 5480 // We also check if the formats are compatible. 5481 // We can't pass a 'scanf' string to a 'printf' function. 5482 if (PVIndex == PVFormat->getFormatIdx() && 5483 Type == S.GetFormatStringType(PVFormat)) 5484 return SLCT_UncheckedLiteral; 5485 } 5486 } 5487 } 5488 } 5489 } 5490 5491 return SLCT_NotALiteral; 5492 } 5493 5494 case Stmt::CallExprClass: 5495 case Stmt::CXXMemberCallExprClass: { 5496 const CallExpr *CE = cast<CallExpr>(E); 5497 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 5498 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 5499 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 5500 return checkFormatStringExpr(S, Arg, Args, 5501 HasVAListArg, format_idx, firstDataArg, 5502 Type, CallType, InFunctionCall, 5503 CheckedVarArgs, UncoveredArg, Offset); 5504 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5505 unsigned BuiltinID = FD->getBuiltinID(); 5506 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 5507 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 5508 const Expr *Arg = CE->getArg(0); 5509 return checkFormatStringExpr(S, Arg, Args, 5510 HasVAListArg, format_idx, 5511 firstDataArg, Type, CallType, 5512 InFunctionCall, CheckedVarArgs, 5513 UncoveredArg, Offset); 5514 } 5515 } 5516 } 5517 5518 return SLCT_NotALiteral; 5519 } 5520 case Stmt::ObjCMessageExprClass: { 5521 const auto *ME = cast<ObjCMessageExpr>(E); 5522 if (const auto *ND = ME->getMethodDecl()) { 5523 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 5524 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 5525 return checkFormatStringExpr( 5526 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 5527 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 5528 } 5529 } 5530 5531 return SLCT_NotALiteral; 5532 } 5533 case Stmt::ObjCStringLiteralClass: 5534 case Stmt::StringLiteralClass: { 5535 const StringLiteral *StrE = nullptr; 5536 5537 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 5538 StrE = ObjCFExpr->getString(); 5539 else 5540 StrE = cast<StringLiteral>(E); 5541 5542 if (StrE) { 5543 if (Offset.isNegative() || Offset > StrE->getLength()) { 5544 // TODO: It would be better to have an explicit warning for out of 5545 // bounds literals. 5546 return SLCT_NotALiteral; 5547 } 5548 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5549 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5550 firstDataArg, Type, InFunctionCall, CallType, 5551 CheckedVarArgs, UncoveredArg); 5552 return SLCT_CheckedLiteral; 5553 } 5554 5555 return SLCT_NotALiteral; 5556 } 5557 case Stmt::BinaryOperatorClass: { 5558 llvm::APSInt LResult; 5559 llvm::APSInt RResult; 5560 5561 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5562 5563 // A string literal + an int offset is still a string literal. 5564 if (BinOp->isAdditiveOp()) { 5565 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5566 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5567 5568 if (LIsInt != RIsInt) { 5569 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5570 5571 if (LIsInt) { 5572 if (BinOpKind == BO_Add) { 5573 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5574 E = BinOp->getRHS(); 5575 goto tryAgain; 5576 } 5577 } else { 5578 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5579 E = BinOp->getLHS(); 5580 goto tryAgain; 5581 } 5582 } 5583 } 5584 5585 return SLCT_NotALiteral; 5586 } 5587 case Stmt::UnaryOperatorClass: { 5588 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5589 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5590 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 5591 llvm::APSInt IndexResult; 5592 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5593 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5594 E = ASE->getBase(); 5595 goto tryAgain; 5596 } 5597 } 5598 5599 return SLCT_NotALiteral; 5600 } 5601 5602 default: 5603 return SLCT_NotALiteral; 5604 } 5605 } 5606 5607 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5608 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5609 .Case("scanf", FST_Scanf) 5610 .Cases("printf", "printf0", FST_Printf) 5611 .Cases("NSString", "CFString", FST_NSString) 5612 .Case("strftime", FST_Strftime) 5613 .Case("strfmon", FST_Strfmon) 5614 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5615 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5616 .Case("os_trace", FST_OSLog) 5617 .Case("os_log", FST_OSLog) 5618 .Default(FST_Unknown); 5619 } 5620 5621 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5622 /// functions) for correct use of format strings. 5623 /// Returns true if a format string has been fully checked. 5624 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5625 ArrayRef<const Expr *> Args, 5626 bool IsCXXMember, 5627 VariadicCallType CallType, 5628 SourceLocation Loc, SourceRange Range, 5629 llvm::SmallBitVector &CheckedVarArgs) { 5630 FormatStringInfo FSI; 5631 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5632 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5633 FSI.FirstDataArg, GetFormatStringType(Format), 5634 CallType, Loc, Range, CheckedVarArgs); 5635 return false; 5636 } 5637 5638 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5639 bool HasVAListArg, unsigned format_idx, 5640 unsigned firstDataArg, FormatStringType Type, 5641 VariadicCallType CallType, 5642 SourceLocation Loc, SourceRange Range, 5643 llvm::SmallBitVector &CheckedVarArgs) { 5644 // CHECK: printf/scanf-like function is called with no format string. 5645 if (format_idx >= Args.size()) { 5646 Diag(Loc, diag::warn_missing_format_string) << Range; 5647 return false; 5648 } 5649 5650 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5651 5652 // CHECK: format string is not a string literal. 5653 // 5654 // Dynamically generated format strings are difficult to 5655 // automatically vet at compile time. Requiring that format strings 5656 // are string literals: (1) permits the checking of format strings by 5657 // the compiler and thereby (2) can practically remove the source of 5658 // many format string exploits. 5659 5660 // Format string can be either ObjC string (e.g. @"%d") or 5661 // C string (e.g. "%d") 5662 // ObjC string uses the same format specifiers as C string, so we can use 5663 // the same format string checking logic for both ObjC and C strings. 5664 UncoveredArgHandler UncoveredArg; 5665 StringLiteralCheckType CT = 5666 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5667 format_idx, firstDataArg, Type, CallType, 5668 /*IsFunctionCall*/ true, CheckedVarArgs, 5669 UncoveredArg, 5670 /*no string offset*/ llvm::APSInt(64, false) = 0); 5671 5672 // Generate a diagnostic where an uncovered argument is detected. 5673 if (UncoveredArg.hasUncoveredArg()) { 5674 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5675 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5676 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5677 } 5678 5679 if (CT != SLCT_NotALiteral) 5680 // Literal format string found, check done! 5681 return CT == SLCT_CheckedLiteral; 5682 5683 // Strftime is particular as it always uses a single 'time' argument, 5684 // so it is safe to pass a non-literal string. 5685 if (Type == FST_Strftime) 5686 return false; 5687 5688 // Do not emit diag when the string param is a macro expansion and the 5689 // format is either NSString or CFString. This is a hack to prevent 5690 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5691 // which are usually used in place of NS and CF string literals. 5692 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5693 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5694 return false; 5695 5696 // If there are no arguments specified, warn with -Wformat-security, otherwise 5697 // warn only with -Wformat-nonliteral. 5698 if (Args.size() == firstDataArg) { 5699 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5700 << OrigFormatExpr->getSourceRange(); 5701 switch (Type) { 5702 default: 5703 break; 5704 case FST_Kprintf: 5705 case FST_FreeBSDKPrintf: 5706 case FST_Printf: 5707 Diag(FormatLoc, diag::note_format_security_fixit) 5708 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5709 break; 5710 case FST_NSString: 5711 Diag(FormatLoc, diag::note_format_security_fixit) 5712 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5713 break; 5714 } 5715 } else { 5716 Diag(FormatLoc, diag::warn_format_nonliteral) 5717 << OrigFormatExpr->getSourceRange(); 5718 } 5719 return false; 5720 } 5721 5722 namespace { 5723 5724 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5725 protected: 5726 Sema &S; 5727 const FormatStringLiteral *FExpr; 5728 const Expr *OrigFormatExpr; 5729 const Sema::FormatStringType FSType; 5730 const unsigned FirstDataArg; 5731 const unsigned NumDataArgs; 5732 const char *Beg; // Start of format string. 5733 const bool HasVAListArg; 5734 ArrayRef<const Expr *> Args; 5735 unsigned FormatIdx; 5736 llvm::SmallBitVector CoveredArgs; 5737 bool usesPositionalArgs = false; 5738 bool atFirstArg = true; 5739 bool inFunctionCall; 5740 Sema::VariadicCallType CallType; 5741 llvm::SmallBitVector &CheckedVarArgs; 5742 UncoveredArgHandler &UncoveredArg; 5743 5744 public: 5745 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5746 const Expr *origFormatExpr, 5747 const Sema::FormatStringType type, unsigned firstDataArg, 5748 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5749 ArrayRef<const Expr *> Args, unsigned formatIdx, 5750 bool inFunctionCall, Sema::VariadicCallType callType, 5751 llvm::SmallBitVector &CheckedVarArgs, 5752 UncoveredArgHandler &UncoveredArg) 5753 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5754 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5755 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5756 inFunctionCall(inFunctionCall), CallType(callType), 5757 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5758 CoveredArgs.resize(numDataArgs); 5759 CoveredArgs.reset(); 5760 } 5761 5762 void DoneProcessing(); 5763 5764 void HandleIncompleteSpecifier(const char *startSpecifier, 5765 unsigned specifierLen) override; 5766 5767 void HandleInvalidLengthModifier( 5768 const analyze_format_string::FormatSpecifier &FS, 5769 const analyze_format_string::ConversionSpecifier &CS, 5770 const char *startSpecifier, unsigned specifierLen, 5771 unsigned DiagID); 5772 5773 void HandleNonStandardLengthModifier( 5774 const analyze_format_string::FormatSpecifier &FS, 5775 const char *startSpecifier, unsigned specifierLen); 5776 5777 void HandleNonStandardConversionSpecifier( 5778 const analyze_format_string::ConversionSpecifier &CS, 5779 const char *startSpecifier, unsigned specifierLen); 5780 5781 void HandlePosition(const char *startPos, unsigned posLen) override; 5782 5783 void HandleInvalidPosition(const char *startSpecifier, 5784 unsigned specifierLen, 5785 analyze_format_string::PositionContext p) override; 5786 5787 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5788 5789 void HandleNullChar(const char *nullCharacter) override; 5790 5791 template <typename Range> 5792 static void 5793 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5794 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5795 bool IsStringLocation, Range StringRange, 5796 ArrayRef<FixItHint> Fixit = None); 5797 5798 protected: 5799 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5800 const char *startSpec, 5801 unsigned specifierLen, 5802 const char *csStart, unsigned csLen); 5803 5804 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5805 const char *startSpec, 5806 unsigned specifierLen); 5807 5808 SourceRange getFormatStringRange(); 5809 CharSourceRange getSpecifierRange(const char *startSpecifier, 5810 unsigned specifierLen); 5811 SourceLocation getLocationOfByte(const char *x); 5812 5813 const Expr *getDataArg(unsigned i) const; 5814 5815 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5816 const analyze_format_string::ConversionSpecifier &CS, 5817 const char *startSpecifier, unsigned specifierLen, 5818 unsigned argIndex); 5819 5820 template <typename Range> 5821 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5822 bool IsStringLocation, Range StringRange, 5823 ArrayRef<FixItHint> Fixit = None); 5824 }; 5825 5826 } // namespace 5827 5828 SourceRange CheckFormatHandler::getFormatStringRange() { 5829 return OrigFormatExpr->getSourceRange(); 5830 } 5831 5832 CharSourceRange CheckFormatHandler:: 5833 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5834 SourceLocation Start = getLocationOfByte(startSpecifier); 5835 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5836 5837 // Advance the end SourceLocation by one due to half-open ranges. 5838 End = End.getLocWithOffset(1); 5839 5840 return CharSourceRange::getCharRange(Start, End); 5841 } 5842 5843 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5844 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5845 S.getLangOpts(), S.Context.getTargetInfo()); 5846 } 5847 5848 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5849 unsigned specifierLen){ 5850 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5851 getLocationOfByte(startSpecifier), 5852 /*IsStringLocation*/true, 5853 getSpecifierRange(startSpecifier, specifierLen)); 5854 } 5855 5856 void CheckFormatHandler::HandleInvalidLengthModifier( 5857 const analyze_format_string::FormatSpecifier &FS, 5858 const analyze_format_string::ConversionSpecifier &CS, 5859 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5860 using namespace analyze_format_string; 5861 5862 const LengthModifier &LM = FS.getLengthModifier(); 5863 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5864 5865 // See if we know how to fix this length modifier. 5866 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5867 if (FixedLM) { 5868 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5869 getLocationOfByte(LM.getStart()), 5870 /*IsStringLocation*/true, 5871 getSpecifierRange(startSpecifier, specifierLen)); 5872 5873 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5874 << FixedLM->toString() 5875 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5876 5877 } else { 5878 FixItHint Hint; 5879 if (DiagID == diag::warn_format_nonsensical_length) 5880 Hint = FixItHint::CreateRemoval(LMRange); 5881 5882 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5883 getLocationOfByte(LM.getStart()), 5884 /*IsStringLocation*/true, 5885 getSpecifierRange(startSpecifier, specifierLen), 5886 Hint); 5887 } 5888 } 5889 5890 void CheckFormatHandler::HandleNonStandardLengthModifier( 5891 const analyze_format_string::FormatSpecifier &FS, 5892 const char *startSpecifier, unsigned specifierLen) { 5893 using namespace analyze_format_string; 5894 5895 const LengthModifier &LM = FS.getLengthModifier(); 5896 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5897 5898 // See if we know how to fix this length modifier. 5899 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5900 if (FixedLM) { 5901 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5902 << LM.toString() << 0, 5903 getLocationOfByte(LM.getStart()), 5904 /*IsStringLocation*/true, 5905 getSpecifierRange(startSpecifier, specifierLen)); 5906 5907 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5908 << FixedLM->toString() 5909 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5910 5911 } else { 5912 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5913 << LM.toString() << 0, 5914 getLocationOfByte(LM.getStart()), 5915 /*IsStringLocation*/true, 5916 getSpecifierRange(startSpecifier, specifierLen)); 5917 } 5918 } 5919 5920 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5921 const analyze_format_string::ConversionSpecifier &CS, 5922 const char *startSpecifier, unsigned specifierLen) { 5923 using namespace analyze_format_string; 5924 5925 // See if we know how to fix this conversion specifier. 5926 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5927 if (FixedCS) { 5928 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5929 << CS.toString() << /*conversion specifier*/1, 5930 getLocationOfByte(CS.getStart()), 5931 /*IsStringLocation*/true, 5932 getSpecifierRange(startSpecifier, specifierLen)); 5933 5934 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5935 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5936 << FixedCS->toString() 5937 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5938 } else { 5939 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5940 << CS.toString() << /*conversion specifier*/1, 5941 getLocationOfByte(CS.getStart()), 5942 /*IsStringLocation*/true, 5943 getSpecifierRange(startSpecifier, specifierLen)); 5944 } 5945 } 5946 5947 void CheckFormatHandler::HandlePosition(const char *startPos, 5948 unsigned posLen) { 5949 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5950 getLocationOfByte(startPos), 5951 /*IsStringLocation*/true, 5952 getSpecifierRange(startPos, posLen)); 5953 } 5954 5955 void 5956 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5957 analyze_format_string::PositionContext p) { 5958 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5959 << (unsigned) p, 5960 getLocationOfByte(startPos), /*IsStringLocation*/true, 5961 getSpecifierRange(startPos, posLen)); 5962 } 5963 5964 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5965 unsigned posLen) { 5966 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5967 getLocationOfByte(startPos), 5968 /*IsStringLocation*/true, 5969 getSpecifierRange(startPos, posLen)); 5970 } 5971 5972 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5973 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5974 // The presence of a null character is likely an error. 5975 EmitFormatDiagnostic( 5976 S.PDiag(diag::warn_printf_format_string_contains_null_char), 5977 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 5978 getFormatStringRange()); 5979 } 5980 } 5981 5982 // Note that this may return NULL if there was an error parsing or building 5983 // one of the argument expressions. 5984 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 5985 return Args[FirstDataArg + i]; 5986 } 5987 5988 void CheckFormatHandler::DoneProcessing() { 5989 // Does the number of data arguments exceed the number of 5990 // format conversions in the format string? 5991 if (!HasVAListArg) { 5992 // Find any arguments that weren't covered. 5993 CoveredArgs.flip(); 5994 signed notCoveredArg = CoveredArgs.find_first(); 5995 if (notCoveredArg >= 0) { 5996 assert((unsigned)notCoveredArg < NumDataArgs); 5997 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 5998 } else { 5999 UncoveredArg.setAllCovered(); 6000 } 6001 } 6002 } 6003 6004 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6005 const Expr *ArgExpr) { 6006 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6007 "Invalid state"); 6008 6009 if (!ArgExpr) 6010 return; 6011 6012 SourceLocation Loc = ArgExpr->getLocStart(); 6013 6014 if (S.getSourceManager().isInSystemMacro(Loc)) 6015 return; 6016 6017 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6018 for (auto E : DiagnosticExprs) 6019 PDiag << E->getSourceRange(); 6020 6021 CheckFormatHandler::EmitFormatDiagnostic( 6022 S, IsFunctionCall, DiagnosticExprs[0], 6023 PDiag, Loc, /*IsStringLocation*/false, 6024 DiagnosticExprs[0]->getSourceRange()); 6025 } 6026 6027 bool 6028 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6029 SourceLocation Loc, 6030 const char *startSpec, 6031 unsigned specifierLen, 6032 const char *csStart, 6033 unsigned csLen) { 6034 bool keepGoing = true; 6035 if (argIndex < NumDataArgs) { 6036 // Consider the argument coverered, even though the specifier doesn't 6037 // make sense. 6038 CoveredArgs.set(argIndex); 6039 } 6040 else { 6041 // If argIndex exceeds the number of data arguments we 6042 // don't issue a warning because that is just a cascade of warnings (and 6043 // they may have intended '%%' anyway). We don't want to continue processing 6044 // the format string after this point, however, as we will like just get 6045 // gibberish when trying to match arguments. 6046 keepGoing = false; 6047 } 6048 6049 StringRef Specifier(csStart, csLen); 6050 6051 // If the specifier in non-printable, it could be the first byte of a UTF-8 6052 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6053 // hex value. 6054 std::string CodePointStr; 6055 if (!llvm::sys::locale::isPrint(*csStart)) { 6056 llvm::UTF32 CodePoint; 6057 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6058 const llvm::UTF8 *E = 6059 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6060 llvm::ConversionResult Result = 6061 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6062 6063 if (Result != llvm::conversionOK) { 6064 unsigned char FirstChar = *csStart; 6065 CodePoint = (llvm::UTF32)FirstChar; 6066 } 6067 6068 llvm::raw_string_ostream OS(CodePointStr); 6069 if (CodePoint < 256) 6070 OS << "\\x" << llvm::format("%02x", CodePoint); 6071 else if (CodePoint <= 0xFFFF) 6072 OS << "\\u" << llvm::format("%04x", CodePoint); 6073 else 6074 OS << "\\U" << llvm::format("%08x", CodePoint); 6075 OS.flush(); 6076 Specifier = CodePointStr; 6077 } 6078 6079 EmitFormatDiagnostic( 6080 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 6081 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 6082 6083 return keepGoing; 6084 } 6085 6086 void 6087 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 6088 const char *startSpec, 6089 unsigned specifierLen) { 6090 EmitFormatDiagnostic( 6091 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 6092 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 6093 } 6094 6095 bool 6096 CheckFormatHandler::CheckNumArgs( 6097 const analyze_format_string::FormatSpecifier &FS, 6098 const analyze_format_string::ConversionSpecifier &CS, 6099 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 6100 6101 if (argIndex >= NumDataArgs) { 6102 PartialDiagnostic PDiag = FS.usesPositionalArg() 6103 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 6104 << (argIndex+1) << NumDataArgs) 6105 : S.PDiag(diag::warn_printf_insufficient_data_args); 6106 EmitFormatDiagnostic( 6107 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 6108 getSpecifierRange(startSpecifier, specifierLen)); 6109 6110 // Since more arguments than conversion tokens are given, by extension 6111 // all arguments are covered, so mark this as so. 6112 UncoveredArg.setAllCovered(); 6113 return false; 6114 } 6115 return true; 6116 } 6117 6118 template<typename Range> 6119 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 6120 SourceLocation Loc, 6121 bool IsStringLocation, 6122 Range StringRange, 6123 ArrayRef<FixItHint> FixIt) { 6124 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 6125 Loc, IsStringLocation, StringRange, FixIt); 6126 } 6127 6128 /// If the format string is not within the function call, emit a note 6129 /// so that the function call and string are in diagnostic messages. 6130 /// 6131 /// \param InFunctionCall if true, the format string is within the function 6132 /// call and only one diagnostic message will be produced. Otherwise, an 6133 /// extra note will be emitted pointing to location of the format string. 6134 /// 6135 /// \param ArgumentExpr the expression that is passed as the format string 6136 /// argument in the function call. Used for getting locations when two 6137 /// diagnostics are emitted. 6138 /// 6139 /// \param PDiag the callee should already have provided any strings for the 6140 /// diagnostic message. This function only adds locations and fixits 6141 /// to diagnostics. 6142 /// 6143 /// \param Loc primary location for diagnostic. If two diagnostics are 6144 /// required, one will be at Loc and a new SourceLocation will be created for 6145 /// the other one. 6146 /// 6147 /// \param IsStringLocation if true, Loc points to the format string should be 6148 /// used for the note. Otherwise, Loc points to the argument list and will 6149 /// be used with PDiag. 6150 /// 6151 /// \param StringRange some or all of the string to highlight. This is 6152 /// templated so it can accept either a CharSourceRange or a SourceRange. 6153 /// 6154 /// \param FixIt optional fix it hint for the format string. 6155 template <typename Range> 6156 void CheckFormatHandler::EmitFormatDiagnostic( 6157 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 6158 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 6159 Range StringRange, ArrayRef<FixItHint> FixIt) { 6160 if (InFunctionCall) { 6161 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 6162 D << StringRange; 6163 D << FixIt; 6164 } else { 6165 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 6166 << ArgumentExpr->getSourceRange(); 6167 6168 const Sema::SemaDiagnosticBuilder &Note = 6169 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 6170 diag::note_format_string_defined); 6171 6172 Note << StringRange; 6173 Note << FixIt; 6174 } 6175 } 6176 6177 //===--- CHECK: Printf format string checking ------------------------------===// 6178 6179 namespace { 6180 6181 class CheckPrintfHandler : public CheckFormatHandler { 6182 public: 6183 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 6184 const Expr *origFormatExpr, 6185 const Sema::FormatStringType type, unsigned firstDataArg, 6186 unsigned numDataArgs, bool isObjC, const char *beg, 6187 bool hasVAListArg, ArrayRef<const Expr *> Args, 6188 unsigned formatIdx, bool inFunctionCall, 6189 Sema::VariadicCallType CallType, 6190 llvm::SmallBitVector &CheckedVarArgs, 6191 UncoveredArgHandler &UncoveredArg) 6192 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6193 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6194 inFunctionCall, CallType, CheckedVarArgs, 6195 UncoveredArg) {} 6196 6197 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 6198 6199 /// Returns true if '%@' specifiers are allowed in the format string. 6200 bool allowsObjCArg() const { 6201 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 6202 FSType == Sema::FST_OSTrace; 6203 } 6204 6205 bool HandleInvalidPrintfConversionSpecifier( 6206 const analyze_printf::PrintfSpecifier &FS, 6207 const char *startSpecifier, 6208 unsigned specifierLen) override; 6209 6210 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 6211 const char *startSpecifier, 6212 unsigned specifierLen) override; 6213 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6214 const char *StartSpecifier, 6215 unsigned SpecifierLen, 6216 const Expr *E); 6217 6218 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 6219 const char *startSpecifier, unsigned specifierLen); 6220 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 6221 const analyze_printf::OptionalAmount &Amt, 6222 unsigned type, 6223 const char *startSpecifier, unsigned specifierLen); 6224 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6225 const analyze_printf::OptionalFlag &flag, 6226 const char *startSpecifier, unsigned specifierLen); 6227 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 6228 const analyze_printf::OptionalFlag &ignoredFlag, 6229 const analyze_printf::OptionalFlag &flag, 6230 const char *startSpecifier, unsigned specifierLen); 6231 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 6232 const Expr *E); 6233 6234 void HandleEmptyObjCModifierFlag(const char *startFlag, 6235 unsigned flagLen) override; 6236 6237 void HandleInvalidObjCModifierFlag(const char *startFlag, 6238 unsigned flagLen) override; 6239 6240 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 6241 const char *flagsEnd, 6242 const char *conversionPosition) 6243 override; 6244 }; 6245 6246 } // namespace 6247 6248 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 6249 const analyze_printf::PrintfSpecifier &FS, 6250 const char *startSpecifier, 6251 unsigned specifierLen) { 6252 const analyze_printf::PrintfConversionSpecifier &CS = 6253 FS.getConversionSpecifier(); 6254 6255 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6256 getLocationOfByte(CS.getStart()), 6257 startSpecifier, specifierLen, 6258 CS.getStart(), CS.getLength()); 6259 } 6260 6261 bool CheckPrintfHandler::HandleAmount( 6262 const analyze_format_string::OptionalAmount &Amt, 6263 unsigned k, const char *startSpecifier, 6264 unsigned specifierLen) { 6265 if (Amt.hasDataArgument()) { 6266 if (!HasVAListArg) { 6267 unsigned argIndex = Amt.getArgIndex(); 6268 if (argIndex >= NumDataArgs) { 6269 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 6270 << k, 6271 getLocationOfByte(Amt.getStart()), 6272 /*IsStringLocation*/true, 6273 getSpecifierRange(startSpecifier, specifierLen)); 6274 // Don't do any more checking. We will just emit 6275 // spurious errors. 6276 return false; 6277 } 6278 6279 // Type check the data argument. It should be an 'int'. 6280 // Although not in conformance with C99, we also allow the argument to be 6281 // an 'unsigned int' as that is a reasonably safe case. GCC also 6282 // doesn't emit a warning for that case. 6283 CoveredArgs.set(argIndex); 6284 const Expr *Arg = getDataArg(argIndex); 6285 if (!Arg) 6286 return false; 6287 6288 QualType T = Arg->getType(); 6289 6290 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 6291 assert(AT.isValid()); 6292 6293 if (!AT.matchesType(S.Context, T)) { 6294 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 6295 << k << AT.getRepresentativeTypeName(S.Context) 6296 << T << Arg->getSourceRange(), 6297 getLocationOfByte(Amt.getStart()), 6298 /*IsStringLocation*/true, 6299 getSpecifierRange(startSpecifier, specifierLen)); 6300 // Don't do any more checking. We will just emit 6301 // spurious errors. 6302 return false; 6303 } 6304 } 6305 } 6306 return true; 6307 } 6308 6309 void CheckPrintfHandler::HandleInvalidAmount( 6310 const analyze_printf::PrintfSpecifier &FS, 6311 const analyze_printf::OptionalAmount &Amt, 6312 unsigned type, 6313 const char *startSpecifier, 6314 unsigned specifierLen) { 6315 const analyze_printf::PrintfConversionSpecifier &CS = 6316 FS.getConversionSpecifier(); 6317 6318 FixItHint fixit = 6319 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 6320 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 6321 Amt.getConstantLength())) 6322 : FixItHint(); 6323 6324 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 6325 << type << CS.toString(), 6326 getLocationOfByte(Amt.getStart()), 6327 /*IsStringLocation*/true, 6328 getSpecifierRange(startSpecifier, specifierLen), 6329 fixit); 6330 } 6331 6332 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6333 const analyze_printf::OptionalFlag &flag, 6334 const char *startSpecifier, 6335 unsigned specifierLen) { 6336 // Warn about pointless flag with a fixit removal. 6337 const analyze_printf::PrintfConversionSpecifier &CS = 6338 FS.getConversionSpecifier(); 6339 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 6340 << flag.toString() << CS.toString(), 6341 getLocationOfByte(flag.getPosition()), 6342 /*IsStringLocation*/true, 6343 getSpecifierRange(startSpecifier, specifierLen), 6344 FixItHint::CreateRemoval( 6345 getSpecifierRange(flag.getPosition(), 1))); 6346 } 6347 6348 void CheckPrintfHandler::HandleIgnoredFlag( 6349 const analyze_printf::PrintfSpecifier &FS, 6350 const analyze_printf::OptionalFlag &ignoredFlag, 6351 const analyze_printf::OptionalFlag &flag, 6352 const char *startSpecifier, 6353 unsigned specifierLen) { 6354 // Warn about ignored flag with a fixit removal. 6355 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 6356 << ignoredFlag.toString() << flag.toString(), 6357 getLocationOfByte(ignoredFlag.getPosition()), 6358 /*IsStringLocation*/true, 6359 getSpecifierRange(startSpecifier, specifierLen), 6360 FixItHint::CreateRemoval( 6361 getSpecifierRange(ignoredFlag.getPosition(), 1))); 6362 } 6363 6364 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 6365 unsigned flagLen) { 6366 // Warn about an empty flag. 6367 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 6368 getLocationOfByte(startFlag), 6369 /*IsStringLocation*/true, 6370 getSpecifierRange(startFlag, flagLen)); 6371 } 6372 6373 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 6374 unsigned flagLen) { 6375 // Warn about an invalid flag. 6376 auto Range = getSpecifierRange(startFlag, flagLen); 6377 StringRef flag(startFlag, flagLen); 6378 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 6379 getLocationOfByte(startFlag), 6380 /*IsStringLocation*/true, 6381 Range, FixItHint::CreateRemoval(Range)); 6382 } 6383 6384 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 6385 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 6386 // Warn about using '[...]' without a '@' conversion. 6387 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 6388 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 6389 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 6390 getLocationOfByte(conversionPosition), 6391 /*IsStringLocation*/true, 6392 Range, FixItHint::CreateRemoval(Range)); 6393 } 6394 6395 // Determines if the specified is a C++ class or struct containing 6396 // a member with the specified name and kind (e.g. a CXXMethodDecl named 6397 // "c_str()"). 6398 template<typename MemberKind> 6399 static llvm::SmallPtrSet<MemberKind*, 1> 6400 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 6401 const RecordType *RT = Ty->getAs<RecordType>(); 6402 llvm::SmallPtrSet<MemberKind*, 1> Results; 6403 6404 if (!RT) 6405 return Results; 6406 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 6407 if (!RD || !RD->getDefinition()) 6408 return Results; 6409 6410 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 6411 Sema::LookupMemberName); 6412 R.suppressDiagnostics(); 6413 6414 // We just need to include all members of the right kind turned up by the 6415 // filter, at this point. 6416 if (S.LookupQualifiedName(R, RT->getDecl())) 6417 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6418 NamedDecl *decl = (*I)->getUnderlyingDecl(); 6419 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 6420 Results.insert(FK); 6421 } 6422 return Results; 6423 } 6424 6425 /// Check if we could call '.c_str()' on an object. 6426 /// 6427 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 6428 /// allow the call, or if it would be ambiguous). 6429 bool Sema::hasCStrMethod(const Expr *E) { 6430 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6431 6432 MethodSet Results = 6433 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 6434 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6435 MI != ME; ++MI) 6436 if ((*MI)->getMinRequiredArguments() == 0) 6437 return true; 6438 return false; 6439 } 6440 6441 // Check if a (w)string was passed when a (w)char* was needed, and offer a 6442 // better diagnostic if so. AT is assumed to be valid. 6443 // Returns true when a c_str() conversion method is found. 6444 bool CheckPrintfHandler::checkForCStrMembers( 6445 const analyze_printf::ArgType &AT, const Expr *E) { 6446 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6447 6448 MethodSet Results = 6449 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 6450 6451 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6452 MI != ME; ++MI) { 6453 const CXXMethodDecl *Method = *MI; 6454 if (Method->getMinRequiredArguments() == 0 && 6455 AT.matchesType(S.Context, Method->getReturnType())) { 6456 // FIXME: Suggest parens if the expression needs them. 6457 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 6458 S.Diag(E->getLocStart(), diag::note_printf_c_str) 6459 << "c_str()" 6460 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 6461 return true; 6462 } 6463 } 6464 6465 return false; 6466 } 6467 6468 bool 6469 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 6470 &FS, 6471 const char *startSpecifier, 6472 unsigned specifierLen) { 6473 using namespace analyze_format_string; 6474 using namespace analyze_printf; 6475 6476 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 6477 6478 if (FS.consumesDataArgument()) { 6479 if (atFirstArg) { 6480 atFirstArg = false; 6481 usesPositionalArgs = FS.usesPositionalArg(); 6482 } 6483 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6484 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6485 startSpecifier, specifierLen); 6486 return false; 6487 } 6488 } 6489 6490 // First check if the field width, precision, and conversion specifier 6491 // have matching data arguments. 6492 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 6493 startSpecifier, specifierLen)) { 6494 return false; 6495 } 6496 6497 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 6498 startSpecifier, specifierLen)) { 6499 return false; 6500 } 6501 6502 if (!CS.consumesDataArgument()) { 6503 // FIXME: Technically specifying a precision or field width here 6504 // makes no sense. Worth issuing a warning at some point. 6505 return true; 6506 } 6507 6508 // Consume the argument. 6509 unsigned argIndex = FS.getArgIndex(); 6510 if (argIndex < NumDataArgs) { 6511 // The check to see if the argIndex is valid will come later. 6512 // We set the bit here because we may exit early from this 6513 // function if we encounter some other error. 6514 CoveredArgs.set(argIndex); 6515 } 6516 6517 // FreeBSD kernel extensions. 6518 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 6519 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 6520 // We need at least two arguments. 6521 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 6522 return false; 6523 6524 // Claim the second argument. 6525 CoveredArgs.set(argIndex + 1); 6526 6527 // Type check the first argument (int for %b, pointer for %D) 6528 const Expr *Ex = getDataArg(argIndex); 6529 const analyze_printf::ArgType &AT = 6530 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 6531 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 6532 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 6533 EmitFormatDiagnostic( 6534 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6535 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 6536 << false << Ex->getSourceRange(), 6537 Ex->getLocStart(), /*IsStringLocation*/false, 6538 getSpecifierRange(startSpecifier, specifierLen)); 6539 6540 // Type check the second argument (char * for both %b and %D) 6541 Ex = getDataArg(argIndex + 1); 6542 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 6543 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 6544 EmitFormatDiagnostic( 6545 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6546 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 6547 << false << Ex->getSourceRange(), 6548 Ex->getLocStart(), /*IsStringLocation*/false, 6549 getSpecifierRange(startSpecifier, specifierLen)); 6550 6551 return true; 6552 } 6553 6554 // Check for using an Objective-C specific conversion specifier 6555 // in a non-ObjC literal. 6556 if (!allowsObjCArg() && CS.isObjCArg()) { 6557 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6558 specifierLen); 6559 } 6560 6561 // %P can only be used with os_log. 6562 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6563 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6564 specifierLen); 6565 } 6566 6567 // %n is not allowed with os_log. 6568 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6569 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6570 getLocationOfByte(CS.getStart()), 6571 /*IsStringLocation*/ false, 6572 getSpecifierRange(startSpecifier, specifierLen)); 6573 6574 return true; 6575 } 6576 6577 // Only scalars are allowed for os_trace. 6578 if (FSType == Sema::FST_OSTrace && 6579 (CS.getKind() == ConversionSpecifier::PArg || 6580 CS.getKind() == ConversionSpecifier::sArg || 6581 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6582 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6583 specifierLen); 6584 } 6585 6586 // Check for use of public/private annotation outside of os_log(). 6587 if (FSType != Sema::FST_OSLog) { 6588 if (FS.isPublic().isSet()) { 6589 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6590 << "public", 6591 getLocationOfByte(FS.isPublic().getPosition()), 6592 /*IsStringLocation*/ false, 6593 getSpecifierRange(startSpecifier, specifierLen)); 6594 } 6595 if (FS.isPrivate().isSet()) { 6596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6597 << "private", 6598 getLocationOfByte(FS.isPrivate().getPosition()), 6599 /*IsStringLocation*/ false, 6600 getSpecifierRange(startSpecifier, specifierLen)); 6601 } 6602 } 6603 6604 // Check for invalid use of field width 6605 if (!FS.hasValidFieldWidth()) { 6606 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6607 startSpecifier, specifierLen); 6608 } 6609 6610 // Check for invalid use of precision 6611 if (!FS.hasValidPrecision()) { 6612 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6613 startSpecifier, specifierLen); 6614 } 6615 6616 // Precision is mandatory for %P specifier. 6617 if (CS.getKind() == ConversionSpecifier::PArg && 6618 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6619 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6620 getLocationOfByte(startSpecifier), 6621 /*IsStringLocation*/ false, 6622 getSpecifierRange(startSpecifier, specifierLen)); 6623 } 6624 6625 // Check each flag does not conflict with any other component. 6626 if (!FS.hasValidThousandsGroupingPrefix()) 6627 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6628 if (!FS.hasValidLeadingZeros()) 6629 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6630 if (!FS.hasValidPlusPrefix()) 6631 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6632 if (!FS.hasValidSpacePrefix()) 6633 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6634 if (!FS.hasValidAlternativeForm()) 6635 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6636 if (!FS.hasValidLeftJustified()) 6637 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6638 6639 // Check that flags are not ignored by another flag 6640 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6641 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6642 startSpecifier, specifierLen); 6643 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6644 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6645 startSpecifier, specifierLen); 6646 6647 // Check the length modifier is valid with the given conversion specifier. 6648 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6649 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6650 diag::warn_format_nonsensical_length); 6651 else if (!FS.hasStandardLengthModifier()) 6652 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6653 else if (!FS.hasStandardLengthConversionCombination()) 6654 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6655 diag::warn_format_non_standard_conversion_spec); 6656 6657 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6658 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6659 6660 // The remaining checks depend on the data arguments. 6661 if (HasVAListArg) 6662 return true; 6663 6664 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6665 return false; 6666 6667 const Expr *Arg = getDataArg(argIndex); 6668 if (!Arg) 6669 return true; 6670 6671 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6672 } 6673 6674 static bool requiresParensToAddCast(const Expr *E) { 6675 // FIXME: We should have a general way to reason about operator 6676 // precedence and whether parens are actually needed here. 6677 // Take care of a few common cases where they aren't. 6678 const Expr *Inside = E->IgnoreImpCasts(); 6679 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6680 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6681 6682 switch (Inside->getStmtClass()) { 6683 case Stmt::ArraySubscriptExprClass: 6684 case Stmt::CallExprClass: 6685 case Stmt::CharacterLiteralClass: 6686 case Stmt::CXXBoolLiteralExprClass: 6687 case Stmt::DeclRefExprClass: 6688 case Stmt::FloatingLiteralClass: 6689 case Stmt::IntegerLiteralClass: 6690 case Stmt::MemberExprClass: 6691 case Stmt::ObjCArrayLiteralClass: 6692 case Stmt::ObjCBoolLiteralExprClass: 6693 case Stmt::ObjCBoxedExprClass: 6694 case Stmt::ObjCDictionaryLiteralClass: 6695 case Stmt::ObjCEncodeExprClass: 6696 case Stmt::ObjCIvarRefExprClass: 6697 case Stmt::ObjCMessageExprClass: 6698 case Stmt::ObjCPropertyRefExprClass: 6699 case Stmt::ObjCStringLiteralClass: 6700 case Stmt::ObjCSubscriptRefExprClass: 6701 case Stmt::ParenExprClass: 6702 case Stmt::StringLiteralClass: 6703 case Stmt::UnaryOperatorClass: 6704 return false; 6705 default: 6706 return true; 6707 } 6708 } 6709 6710 static std::pair<QualType, StringRef> 6711 shouldNotPrintDirectly(const ASTContext &Context, 6712 QualType IntendedTy, 6713 const Expr *E) { 6714 // Use a 'while' to peel off layers of typedefs. 6715 QualType TyTy = IntendedTy; 6716 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6717 StringRef Name = UserTy->getDecl()->getName(); 6718 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6719 .Case("CFIndex", Context.getNSIntegerType()) 6720 .Case("NSInteger", Context.getNSIntegerType()) 6721 .Case("NSUInteger", Context.getNSUIntegerType()) 6722 .Case("SInt32", Context.IntTy) 6723 .Case("UInt32", Context.UnsignedIntTy) 6724 .Default(QualType()); 6725 6726 if (!CastTy.isNull()) 6727 return std::make_pair(CastTy, Name); 6728 6729 TyTy = UserTy->desugar(); 6730 } 6731 6732 // Strip parens if necessary. 6733 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6734 return shouldNotPrintDirectly(Context, 6735 PE->getSubExpr()->getType(), 6736 PE->getSubExpr()); 6737 6738 // If this is a conditional expression, then its result type is constructed 6739 // via usual arithmetic conversions and thus there might be no necessary 6740 // typedef sugar there. Recurse to operands to check for NSInteger & 6741 // Co. usage condition. 6742 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6743 QualType TrueTy, FalseTy; 6744 StringRef TrueName, FalseName; 6745 6746 std::tie(TrueTy, TrueName) = 6747 shouldNotPrintDirectly(Context, 6748 CO->getTrueExpr()->getType(), 6749 CO->getTrueExpr()); 6750 std::tie(FalseTy, FalseName) = 6751 shouldNotPrintDirectly(Context, 6752 CO->getFalseExpr()->getType(), 6753 CO->getFalseExpr()); 6754 6755 if (TrueTy == FalseTy) 6756 return std::make_pair(TrueTy, TrueName); 6757 else if (TrueTy.isNull()) 6758 return std::make_pair(FalseTy, FalseName); 6759 else if (FalseTy.isNull()) 6760 return std::make_pair(TrueTy, TrueName); 6761 } 6762 6763 return std::make_pair(QualType(), StringRef()); 6764 } 6765 6766 bool 6767 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6768 const char *StartSpecifier, 6769 unsigned SpecifierLen, 6770 const Expr *E) { 6771 using namespace analyze_format_string; 6772 using namespace analyze_printf; 6773 6774 // Now type check the data expression that matches the 6775 // format specifier. 6776 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6777 if (!AT.isValid()) 6778 return true; 6779 6780 QualType ExprTy = E->getType(); 6781 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6782 ExprTy = TET->getUnderlyingExpr()->getType(); 6783 } 6784 6785 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy); 6786 6787 if (match == analyze_printf::ArgType::Match) { 6788 return true; 6789 } 6790 6791 // Look through argument promotions for our error message's reported type. 6792 // This includes the integral and floating promotions, but excludes array 6793 // and function pointer decay; seeing that an argument intended to be a 6794 // string has type 'char [6]' is probably more confusing than 'char *'. 6795 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6796 if (ICE->getCastKind() == CK_IntegralCast || 6797 ICE->getCastKind() == CK_FloatingCast) { 6798 E = ICE->getSubExpr(); 6799 ExprTy = E->getType(); 6800 6801 // Check if we didn't match because of an implicit cast from a 'char' 6802 // or 'short' to an 'int'. This is done because printf is a varargs 6803 // function. 6804 if (ICE->getType() == S.Context.IntTy || 6805 ICE->getType() == S.Context.UnsignedIntTy) { 6806 // All further checking is done on the subexpression. 6807 if (AT.matchesType(S.Context, ExprTy)) 6808 return true; 6809 } 6810 } 6811 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6812 // Special case for 'a', which has type 'int' in C. 6813 // Note, however, that we do /not/ want to treat multibyte constants like 6814 // 'MooV' as characters! This form is deprecated but still exists. 6815 if (ExprTy == S.Context.IntTy) 6816 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6817 ExprTy = S.Context.CharTy; 6818 } 6819 6820 // Look through enums to their underlying type. 6821 bool IsEnum = false; 6822 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6823 ExprTy = EnumTy->getDecl()->getIntegerType(); 6824 IsEnum = true; 6825 } 6826 6827 // %C in an Objective-C context prints a unichar, not a wchar_t. 6828 // If the argument is an integer of some kind, believe the %C and suggest 6829 // a cast instead of changing the conversion specifier. 6830 QualType IntendedTy = ExprTy; 6831 if (isObjCContext() && 6832 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6833 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6834 !ExprTy->isCharType()) { 6835 // 'unichar' is defined as a typedef of unsigned short, but we should 6836 // prefer using the typedef if it is visible. 6837 IntendedTy = S.Context.UnsignedShortTy; 6838 6839 // While we are here, check if the value is an IntegerLiteral that happens 6840 // to be within the valid range. 6841 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6842 const llvm::APInt &V = IL->getValue(); 6843 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6844 return true; 6845 } 6846 6847 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6848 Sema::LookupOrdinaryName); 6849 if (S.LookupName(Result, S.getCurScope())) { 6850 NamedDecl *ND = Result.getFoundDecl(); 6851 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6852 if (TD->getUnderlyingType() == IntendedTy) 6853 IntendedTy = S.Context.getTypedefType(TD); 6854 } 6855 } 6856 } 6857 6858 // Special-case some of Darwin's platform-independence types by suggesting 6859 // casts to primitive types that are known to be large enough. 6860 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6861 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6862 QualType CastTy; 6863 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6864 if (!CastTy.isNull()) { 6865 IntendedTy = CastTy; 6866 ShouldNotPrintDirectly = true; 6867 } 6868 } 6869 6870 // We may be able to offer a FixItHint if it is a supported type. 6871 PrintfSpecifier fixedFS = FS; 6872 bool success = 6873 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6874 6875 if (success) { 6876 // Get the fix string from the fixed format specifier 6877 SmallString<16> buf; 6878 llvm::raw_svector_ostream os(buf); 6879 fixedFS.toString(os); 6880 6881 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6882 6883 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6884 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6885 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 6886 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6887 } 6888 // In this case, the specifier is wrong and should be changed to match 6889 // the argument. 6890 EmitFormatDiagnostic(S.PDiag(diag) 6891 << AT.getRepresentativeTypeName(S.Context) 6892 << IntendedTy << IsEnum << E->getSourceRange(), 6893 E->getLocStart(), 6894 /*IsStringLocation*/ false, SpecRange, 6895 FixItHint::CreateReplacement(SpecRange, os.str())); 6896 } else { 6897 // The canonical type for formatting this value is different from the 6898 // actual type of the expression. (This occurs, for example, with Darwin's 6899 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6900 // should be printed as 'long' for 64-bit compatibility.) 6901 // Rather than emitting a normal format/argument mismatch, we want to 6902 // add a cast to the recommended type (and correct the format string 6903 // if necessary). 6904 SmallString<16> CastBuf; 6905 llvm::raw_svector_ostream CastFix(CastBuf); 6906 CastFix << "("; 6907 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6908 CastFix << ")"; 6909 6910 SmallVector<FixItHint,4> Hints; 6911 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6912 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6913 6914 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6915 // If there's already a cast present, just replace it. 6916 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6917 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6918 6919 } else if (!requiresParensToAddCast(E)) { 6920 // If the expression has high enough precedence, 6921 // just write the C-style cast. 6922 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6923 CastFix.str())); 6924 } else { 6925 // Otherwise, add parens around the expression as well as the cast. 6926 CastFix << "("; 6927 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6928 CastFix.str())); 6929 6930 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6931 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6932 } 6933 6934 if (ShouldNotPrintDirectly) { 6935 // The expression has a type that should not be printed directly. 6936 // We extract the name from the typedef because we don't want to show 6937 // the underlying type in the diagnostic. 6938 StringRef Name; 6939 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6940 Name = TypedefTy->getDecl()->getName(); 6941 else 6942 Name = CastTyName; 6943 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast) 6944 << Name << IntendedTy << IsEnum 6945 << E->getSourceRange(), 6946 E->getLocStart(), /*IsStringLocation=*/false, 6947 SpecRange, Hints); 6948 } else { 6949 // In this case, the expression could be printed using a different 6950 // specifier, but we've decided that the specifier is probably correct 6951 // and we should cast instead. Just use the normal warning message. 6952 EmitFormatDiagnostic( 6953 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6954 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6955 << E->getSourceRange(), 6956 E->getLocStart(), /*IsStringLocation*/false, 6957 SpecRange, Hints); 6958 } 6959 } 6960 } else { 6961 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6962 SpecifierLen); 6963 // Since the warning for passing non-POD types to variadic functions 6964 // was deferred until now, we emit a warning for non-POD 6965 // arguments here. 6966 switch (S.isValidVarArgType(ExprTy)) { 6967 case Sema::VAK_Valid: 6968 case Sema::VAK_ValidInCXX11: { 6969 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 6970 if (match == analyze_printf::ArgType::NoMatchPedantic) { 6971 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 6972 } 6973 6974 EmitFormatDiagnostic( 6975 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 6976 << IsEnum << CSR << E->getSourceRange(), 6977 E->getLocStart(), /*IsStringLocation*/ false, CSR); 6978 break; 6979 } 6980 case Sema::VAK_Undefined: 6981 case Sema::VAK_MSVCUndefined: 6982 EmitFormatDiagnostic( 6983 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 6984 << S.getLangOpts().CPlusPlus11 6985 << ExprTy 6986 << CallType 6987 << AT.getRepresentativeTypeName(S.Context) 6988 << CSR 6989 << E->getSourceRange(), 6990 E->getLocStart(), /*IsStringLocation*/false, CSR); 6991 checkForCStrMembers(AT, E); 6992 break; 6993 6994 case Sema::VAK_Invalid: 6995 if (ExprTy->isObjCObjectType()) 6996 EmitFormatDiagnostic( 6997 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 6998 << S.getLangOpts().CPlusPlus11 6999 << ExprTy 7000 << CallType 7001 << AT.getRepresentativeTypeName(S.Context) 7002 << CSR 7003 << E->getSourceRange(), 7004 E->getLocStart(), /*IsStringLocation*/false, CSR); 7005 else 7006 // FIXME: If this is an initializer list, suggest removing the braces 7007 // or inserting a cast to the target type. 7008 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 7009 << isa<InitListExpr>(E) << ExprTy << CallType 7010 << AT.getRepresentativeTypeName(S.Context) 7011 << E->getSourceRange(); 7012 break; 7013 } 7014 7015 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7016 "format string specifier index out of range"); 7017 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7018 } 7019 7020 return true; 7021 } 7022 7023 //===--- CHECK: Scanf format string checking ------------------------------===// 7024 7025 namespace { 7026 7027 class CheckScanfHandler : public CheckFormatHandler { 7028 public: 7029 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7030 const Expr *origFormatExpr, Sema::FormatStringType type, 7031 unsigned firstDataArg, unsigned numDataArgs, 7032 const char *beg, bool hasVAListArg, 7033 ArrayRef<const Expr *> Args, unsigned formatIdx, 7034 bool inFunctionCall, Sema::VariadicCallType CallType, 7035 llvm::SmallBitVector &CheckedVarArgs, 7036 UncoveredArgHandler &UncoveredArg) 7037 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7038 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7039 inFunctionCall, CallType, CheckedVarArgs, 7040 UncoveredArg) {} 7041 7042 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7043 const char *startSpecifier, 7044 unsigned specifierLen) override; 7045 7046 bool HandleInvalidScanfConversionSpecifier( 7047 const analyze_scanf::ScanfSpecifier &FS, 7048 const char *startSpecifier, 7049 unsigned specifierLen) override; 7050 7051 void HandleIncompleteScanList(const char *start, const char *end) override; 7052 }; 7053 7054 } // namespace 7055 7056 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7057 const char *end) { 7058 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7059 getLocationOfByte(end), /*IsStringLocation*/true, 7060 getSpecifierRange(start, end - start)); 7061 } 7062 7063 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7064 const analyze_scanf::ScanfSpecifier &FS, 7065 const char *startSpecifier, 7066 unsigned specifierLen) { 7067 const analyze_scanf::ScanfConversionSpecifier &CS = 7068 FS.getConversionSpecifier(); 7069 7070 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7071 getLocationOfByte(CS.getStart()), 7072 startSpecifier, specifierLen, 7073 CS.getStart(), CS.getLength()); 7074 } 7075 7076 bool CheckScanfHandler::HandleScanfSpecifier( 7077 const analyze_scanf::ScanfSpecifier &FS, 7078 const char *startSpecifier, 7079 unsigned specifierLen) { 7080 using namespace analyze_scanf; 7081 using namespace analyze_format_string; 7082 7083 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 7084 7085 // Handle case where '%' and '*' don't consume an argument. These shouldn't 7086 // be used to decide if we are using positional arguments consistently. 7087 if (FS.consumesDataArgument()) { 7088 if (atFirstArg) { 7089 atFirstArg = false; 7090 usesPositionalArgs = FS.usesPositionalArg(); 7091 } 7092 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7093 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7094 startSpecifier, specifierLen); 7095 return false; 7096 } 7097 } 7098 7099 // Check if the field with is non-zero. 7100 const OptionalAmount &Amt = FS.getFieldWidth(); 7101 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 7102 if (Amt.getConstantAmount() == 0) { 7103 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 7104 Amt.getConstantLength()); 7105 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 7106 getLocationOfByte(Amt.getStart()), 7107 /*IsStringLocation*/true, R, 7108 FixItHint::CreateRemoval(R)); 7109 } 7110 } 7111 7112 if (!FS.consumesDataArgument()) { 7113 // FIXME: Technically specifying a precision or field width here 7114 // makes no sense. Worth issuing a warning at some point. 7115 return true; 7116 } 7117 7118 // Consume the argument. 7119 unsigned argIndex = FS.getArgIndex(); 7120 if (argIndex < NumDataArgs) { 7121 // The check to see if the argIndex is valid will come later. 7122 // We set the bit here because we may exit early from this 7123 // function if we encounter some other error. 7124 CoveredArgs.set(argIndex); 7125 } 7126 7127 // Check the length modifier is valid with the given conversion specifier. 7128 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7129 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7130 diag::warn_format_nonsensical_length); 7131 else if (!FS.hasStandardLengthModifier()) 7132 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7133 else if (!FS.hasStandardLengthConversionCombination()) 7134 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7135 diag::warn_format_non_standard_conversion_spec); 7136 7137 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7138 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7139 7140 // The remaining checks depend on the data arguments. 7141 if (HasVAListArg) 7142 return true; 7143 7144 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7145 return false; 7146 7147 // Check that the argument type matches the format specifier. 7148 const Expr *Ex = getDataArg(argIndex); 7149 if (!Ex) 7150 return true; 7151 7152 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 7153 7154 if (!AT.isValid()) { 7155 return true; 7156 } 7157 7158 analyze_format_string::ArgType::MatchKind match = 7159 AT.matchesType(S.Context, Ex->getType()); 7160 if (match == analyze_format_string::ArgType::Match) { 7161 return true; 7162 } 7163 7164 ScanfSpecifier fixedFS = FS; 7165 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 7166 S.getLangOpts(), S.Context); 7167 7168 unsigned diag = diag::warn_format_conversion_argument_type_mismatch; 7169 if (match == analyze_format_string::ArgType::NoMatchPedantic) { 7170 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 7171 } 7172 7173 if (success) { 7174 // Get the fix string from the fixed format specifier. 7175 SmallString<128> buf; 7176 llvm::raw_svector_ostream os(buf); 7177 fixedFS.toString(os); 7178 7179 EmitFormatDiagnostic( 7180 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) 7181 << Ex->getType() << false << Ex->getSourceRange(), 7182 Ex->getLocStart(), 7183 /*IsStringLocation*/ false, 7184 getSpecifierRange(startSpecifier, specifierLen), 7185 FixItHint::CreateReplacement( 7186 getSpecifierRange(startSpecifier, specifierLen), os.str())); 7187 } else { 7188 EmitFormatDiagnostic(S.PDiag(diag) 7189 << AT.getRepresentativeTypeName(S.Context) 7190 << Ex->getType() << false << Ex->getSourceRange(), 7191 Ex->getLocStart(), 7192 /*IsStringLocation*/ false, 7193 getSpecifierRange(startSpecifier, specifierLen)); 7194 } 7195 7196 return true; 7197 } 7198 7199 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7200 const Expr *OrigFormatExpr, 7201 ArrayRef<const Expr *> Args, 7202 bool HasVAListArg, unsigned format_idx, 7203 unsigned firstDataArg, 7204 Sema::FormatStringType Type, 7205 bool inFunctionCall, 7206 Sema::VariadicCallType CallType, 7207 llvm::SmallBitVector &CheckedVarArgs, 7208 UncoveredArgHandler &UncoveredArg) { 7209 // CHECK: is the format string a wide literal? 7210 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 7211 CheckFormatHandler::EmitFormatDiagnostic( 7212 S, inFunctionCall, Args[format_idx], 7213 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 7214 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7215 return; 7216 } 7217 7218 // Str - The format string. NOTE: this is NOT null-terminated! 7219 StringRef StrRef = FExpr->getString(); 7220 const char *Str = StrRef.data(); 7221 // Account for cases where the string literal is truncated in a declaration. 7222 const ConstantArrayType *T = 7223 S.Context.getAsConstantArrayType(FExpr->getType()); 7224 assert(T && "String literal not of constant array type!"); 7225 size_t TypeSize = T->getSize().getZExtValue(); 7226 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7227 const unsigned numDataArgs = Args.size() - firstDataArg; 7228 7229 // Emit a warning if the string literal is truncated and does not contain an 7230 // embedded null character. 7231 if (TypeSize <= StrRef.size() && 7232 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 7233 CheckFormatHandler::EmitFormatDiagnostic( 7234 S, inFunctionCall, Args[format_idx], 7235 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 7236 FExpr->getLocStart(), 7237 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 7238 return; 7239 } 7240 7241 // CHECK: empty format string? 7242 if (StrLen == 0 && numDataArgs > 0) { 7243 CheckFormatHandler::EmitFormatDiagnostic( 7244 S, inFunctionCall, Args[format_idx], 7245 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 7246 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7247 return; 7248 } 7249 7250 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 7251 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 7252 Type == Sema::FST_OSTrace) { 7253 CheckPrintfHandler H( 7254 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 7255 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 7256 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 7257 CheckedVarArgs, UncoveredArg); 7258 7259 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 7260 S.getLangOpts(), 7261 S.Context.getTargetInfo(), 7262 Type == Sema::FST_FreeBSDKPrintf)) 7263 H.DoneProcessing(); 7264 } else if (Type == Sema::FST_Scanf) { 7265 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 7266 numDataArgs, Str, HasVAListArg, Args, format_idx, 7267 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 7268 7269 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 7270 S.getLangOpts(), 7271 S.Context.getTargetInfo())) 7272 H.DoneProcessing(); 7273 } // TODO: handle other formats 7274 } 7275 7276 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 7277 // Str - The format string. NOTE: this is NOT null-terminated! 7278 StringRef StrRef = FExpr->getString(); 7279 const char *Str = StrRef.data(); 7280 // Account for cases where the string literal is truncated in a declaration. 7281 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 7282 assert(T && "String literal not of constant array type!"); 7283 size_t TypeSize = T->getSize().getZExtValue(); 7284 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7285 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 7286 getLangOpts(), 7287 Context.getTargetInfo()); 7288 } 7289 7290 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 7291 7292 // Returns the related absolute value function that is larger, of 0 if one 7293 // does not exist. 7294 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 7295 switch (AbsFunction) { 7296 default: 7297 return 0; 7298 7299 case Builtin::BI__builtin_abs: 7300 return Builtin::BI__builtin_labs; 7301 case Builtin::BI__builtin_labs: 7302 return Builtin::BI__builtin_llabs; 7303 case Builtin::BI__builtin_llabs: 7304 return 0; 7305 7306 case Builtin::BI__builtin_fabsf: 7307 return Builtin::BI__builtin_fabs; 7308 case Builtin::BI__builtin_fabs: 7309 return Builtin::BI__builtin_fabsl; 7310 case Builtin::BI__builtin_fabsl: 7311 return 0; 7312 7313 case Builtin::BI__builtin_cabsf: 7314 return Builtin::BI__builtin_cabs; 7315 case Builtin::BI__builtin_cabs: 7316 return Builtin::BI__builtin_cabsl; 7317 case Builtin::BI__builtin_cabsl: 7318 return 0; 7319 7320 case Builtin::BIabs: 7321 return Builtin::BIlabs; 7322 case Builtin::BIlabs: 7323 return Builtin::BIllabs; 7324 case Builtin::BIllabs: 7325 return 0; 7326 7327 case Builtin::BIfabsf: 7328 return Builtin::BIfabs; 7329 case Builtin::BIfabs: 7330 return Builtin::BIfabsl; 7331 case Builtin::BIfabsl: 7332 return 0; 7333 7334 case Builtin::BIcabsf: 7335 return Builtin::BIcabs; 7336 case Builtin::BIcabs: 7337 return Builtin::BIcabsl; 7338 case Builtin::BIcabsl: 7339 return 0; 7340 } 7341 } 7342 7343 // Returns the argument type of the absolute value function. 7344 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 7345 unsigned AbsType) { 7346 if (AbsType == 0) 7347 return QualType(); 7348 7349 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 7350 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 7351 if (Error != ASTContext::GE_None) 7352 return QualType(); 7353 7354 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 7355 if (!FT) 7356 return QualType(); 7357 7358 if (FT->getNumParams() != 1) 7359 return QualType(); 7360 7361 return FT->getParamType(0); 7362 } 7363 7364 // Returns the best absolute value function, or zero, based on type and 7365 // current absolute value function. 7366 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 7367 unsigned AbsFunctionKind) { 7368 unsigned BestKind = 0; 7369 uint64_t ArgSize = Context.getTypeSize(ArgType); 7370 for (unsigned Kind = AbsFunctionKind; Kind != 0; 7371 Kind = getLargerAbsoluteValueFunction(Kind)) { 7372 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 7373 if (Context.getTypeSize(ParamType) >= ArgSize) { 7374 if (BestKind == 0) 7375 BestKind = Kind; 7376 else if (Context.hasSameType(ParamType, ArgType)) { 7377 BestKind = Kind; 7378 break; 7379 } 7380 } 7381 } 7382 return BestKind; 7383 } 7384 7385 enum AbsoluteValueKind { 7386 AVK_Integer, 7387 AVK_Floating, 7388 AVK_Complex 7389 }; 7390 7391 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 7392 if (T->isIntegralOrEnumerationType()) 7393 return AVK_Integer; 7394 if (T->isRealFloatingType()) 7395 return AVK_Floating; 7396 if (T->isAnyComplexType()) 7397 return AVK_Complex; 7398 7399 llvm_unreachable("Type not integer, floating, or complex"); 7400 } 7401 7402 // Changes the absolute value function to a different type. Preserves whether 7403 // the function is a builtin. 7404 static unsigned changeAbsFunction(unsigned AbsKind, 7405 AbsoluteValueKind ValueKind) { 7406 switch (ValueKind) { 7407 case AVK_Integer: 7408 switch (AbsKind) { 7409 default: 7410 return 0; 7411 case Builtin::BI__builtin_fabsf: 7412 case Builtin::BI__builtin_fabs: 7413 case Builtin::BI__builtin_fabsl: 7414 case Builtin::BI__builtin_cabsf: 7415 case Builtin::BI__builtin_cabs: 7416 case Builtin::BI__builtin_cabsl: 7417 return Builtin::BI__builtin_abs; 7418 case Builtin::BIfabsf: 7419 case Builtin::BIfabs: 7420 case Builtin::BIfabsl: 7421 case Builtin::BIcabsf: 7422 case Builtin::BIcabs: 7423 case Builtin::BIcabsl: 7424 return Builtin::BIabs; 7425 } 7426 case AVK_Floating: 7427 switch (AbsKind) { 7428 default: 7429 return 0; 7430 case Builtin::BI__builtin_abs: 7431 case Builtin::BI__builtin_labs: 7432 case Builtin::BI__builtin_llabs: 7433 case Builtin::BI__builtin_cabsf: 7434 case Builtin::BI__builtin_cabs: 7435 case Builtin::BI__builtin_cabsl: 7436 return Builtin::BI__builtin_fabsf; 7437 case Builtin::BIabs: 7438 case Builtin::BIlabs: 7439 case Builtin::BIllabs: 7440 case Builtin::BIcabsf: 7441 case Builtin::BIcabs: 7442 case Builtin::BIcabsl: 7443 return Builtin::BIfabsf; 7444 } 7445 case AVK_Complex: 7446 switch (AbsKind) { 7447 default: 7448 return 0; 7449 case Builtin::BI__builtin_abs: 7450 case Builtin::BI__builtin_labs: 7451 case Builtin::BI__builtin_llabs: 7452 case Builtin::BI__builtin_fabsf: 7453 case Builtin::BI__builtin_fabs: 7454 case Builtin::BI__builtin_fabsl: 7455 return Builtin::BI__builtin_cabsf; 7456 case Builtin::BIabs: 7457 case Builtin::BIlabs: 7458 case Builtin::BIllabs: 7459 case Builtin::BIfabsf: 7460 case Builtin::BIfabs: 7461 case Builtin::BIfabsl: 7462 return Builtin::BIcabsf; 7463 } 7464 } 7465 llvm_unreachable("Unable to convert function"); 7466 } 7467 7468 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 7469 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 7470 if (!FnInfo) 7471 return 0; 7472 7473 switch (FDecl->getBuiltinID()) { 7474 default: 7475 return 0; 7476 case Builtin::BI__builtin_abs: 7477 case Builtin::BI__builtin_fabs: 7478 case Builtin::BI__builtin_fabsf: 7479 case Builtin::BI__builtin_fabsl: 7480 case Builtin::BI__builtin_labs: 7481 case Builtin::BI__builtin_llabs: 7482 case Builtin::BI__builtin_cabs: 7483 case Builtin::BI__builtin_cabsf: 7484 case Builtin::BI__builtin_cabsl: 7485 case Builtin::BIabs: 7486 case Builtin::BIlabs: 7487 case Builtin::BIllabs: 7488 case Builtin::BIfabs: 7489 case Builtin::BIfabsf: 7490 case Builtin::BIfabsl: 7491 case Builtin::BIcabs: 7492 case Builtin::BIcabsf: 7493 case Builtin::BIcabsl: 7494 return FDecl->getBuiltinID(); 7495 } 7496 llvm_unreachable("Unknown Builtin type"); 7497 } 7498 7499 // If the replacement is valid, emit a note with replacement function. 7500 // Additionally, suggest including the proper header if not already included. 7501 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 7502 unsigned AbsKind, QualType ArgType) { 7503 bool EmitHeaderHint = true; 7504 const char *HeaderName = nullptr; 7505 const char *FunctionName = nullptr; 7506 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 7507 FunctionName = "std::abs"; 7508 if (ArgType->isIntegralOrEnumerationType()) { 7509 HeaderName = "cstdlib"; 7510 } else if (ArgType->isRealFloatingType()) { 7511 HeaderName = "cmath"; 7512 } else { 7513 llvm_unreachable("Invalid Type"); 7514 } 7515 7516 // Lookup all std::abs 7517 if (NamespaceDecl *Std = S.getStdNamespace()) { 7518 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 7519 R.suppressDiagnostics(); 7520 S.LookupQualifiedName(R, Std); 7521 7522 for (const auto *I : R) { 7523 const FunctionDecl *FDecl = nullptr; 7524 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 7525 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 7526 } else { 7527 FDecl = dyn_cast<FunctionDecl>(I); 7528 } 7529 if (!FDecl) 7530 continue; 7531 7532 // Found std::abs(), check that they are the right ones. 7533 if (FDecl->getNumParams() != 1) 7534 continue; 7535 7536 // Check that the parameter type can handle the argument. 7537 QualType ParamType = FDecl->getParamDecl(0)->getType(); 7538 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 7539 S.Context.getTypeSize(ArgType) <= 7540 S.Context.getTypeSize(ParamType)) { 7541 // Found a function, don't need the header hint. 7542 EmitHeaderHint = false; 7543 break; 7544 } 7545 } 7546 } 7547 } else { 7548 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 7549 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7550 7551 if (HeaderName) { 7552 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7553 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7554 R.suppressDiagnostics(); 7555 S.LookupName(R, S.getCurScope()); 7556 7557 if (R.isSingleResult()) { 7558 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7559 if (FD && FD->getBuiltinID() == AbsKind) { 7560 EmitHeaderHint = false; 7561 } else { 7562 return; 7563 } 7564 } else if (!R.empty()) { 7565 return; 7566 } 7567 } 7568 } 7569 7570 S.Diag(Loc, diag::note_replace_abs_function) 7571 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7572 7573 if (!HeaderName) 7574 return; 7575 7576 if (!EmitHeaderHint) 7577 return; 7578 7579 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7580 << FunctionName; 7581 } 7582 7583 template <std::size_t StrLen> 7584 static bool IsStdFunction(const FunctionDecl *FDecl, 7585 const char (&Str)[StrLen]) { 7586 if (!FDecl) 7587 return false; 7588 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7589 return false; 7590 if (!FDecl->isInStdNamespace()) 7591 return false; 7592 7593 return true; 7594 } 7595 7596 // Warn when using the wrong abs() function. 7597 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7598 const FunctionDecl *FDecl) { 7599 if (Call->getNumArgs() != 1) 7600 return; 7601 7602 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7603 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7604 if (AbsKind == 0 && !IsStdAbs) 7605 return; 7606 7607 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7608 QualType ParamType = Call->getArg(0)->getType(); 7609 7610 // Unsigned types cannot be negative. Suggest removing the absolute value 7611 // function call. 7612 if (ArgType->isUnsignedIntegerType()) { 7613 const char *FunctionName = 7614 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7615 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7616 Diag(Call->getExprLoc(), diag::note_remove_abs) 7617 << FunctionName 7618 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7619 return; 7620 } 7621 7622 // Taking the absolute value of a pointer is very suspicious, they probably 7623 // wanted to index into an array, dereference a pointer, call a function, etc. 7624 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7625 unsigned DiagType = 0; 7626 if (ArgType->isFunctionType()) 7627 DiagType = 1; 7628 else if (ArgType->isArrayType()) 7629 DiagType = 2; 7630 7631 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7632 return; 7633 } 7634 7635 // std::abs has overloads which prevent most of the absolute value problems 7636 // from occurring. 7637 if (IsStdAbs) 7638 return; 7639 7640 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7641 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7642 7643 // The argument and parameter are the same kind. Check if they are the right 7644 // size. 7645 if (ArgValueKind == ParamValueKind) { 7646 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7647 return; 7648 7649 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7650 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7651 << FDecl << ArgType << ParamType; 7652 7653 if (NewAbsKind == 0) 7654 return; 7655 7656 emitReplacement(*this, Call->getExprLoc(), 7657 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7658 return; 7659 } 7660 7661 // ArgValueKind != ParamValueKind 7662 // The wrong type of absolute value function was used. Attempt to find the 7663 // proper one. 7664 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7665 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7666 if (NewAbsKind == 0) 7667 return; 7668 7669 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7670 << FDecl << ParamValueKind << ArgValueKind; 7671 7672 emitReplacement(*this, Call->getExprLoc(), 7673 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7674 } 7675 7676 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7677 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7678 const FunctionDecl *FDecl) { 7679 if (!Call || !FDecl) return; 7680 7681 // Ignore template specializations and macros. 7682 if (inTemplateInstantiation()) return; 7683 if (Call->getExprLoc().isMacroID()) return; 7684 7685 // Only care about the one template argument, two function parameter std::max 7686 if (Call->getNumArgs() != 2) return; 7687 if (!IsStdFunction(FDecl, "max")) return; 7688 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7689 if (!ArgList) return; 7690 if (ArgList->size() != 1) return; 7691 7692 // Check that template type argument is unsigned integer. 7693 const auto& TA = ArgList->get(0); 7694 if (TA.getKind() != TemplateArgument::Type) return; 7695 QualType ArgType = TA.getAsType(); 7696 if (!ArgType->isUnsignedIntegerType()) return; 7697 7698 // See if either argument is a literal zero. 7699 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7700 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7701 if (!MTE) return false; 7702 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7703 if (!Num) return false; 7704 if (Num->getValue() != 0) return false; 7705 return true; 7706 }; 7707 7708 const Expr *FirstArg = Call->getArg(0); 7709 const Expr *SecondArg = Call->getArg(1); 7710 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7711 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7712 7713 // Only warn when exactly one argument is zero. 7714 if (IsFirstArgZero == IsSecondArgZero) return; 7715 7716 SourceRange FirstRange = FirstArg->getSourceRange(); 7717 SourceRange SecondRange = SecondArg->getSourceRange(); 7718 7719 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7720 7721 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7722 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7723 7724 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7725 SourceRange RemovalRange; 7726 if (IsFirstArgZero) { 7727 RemovalRange = SourceRange(FirstRange.getBegin(), 7728 SecondRange.getBegin().getLocWithOffset(-1)); 7729 } else { 7730 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7731 SecondRange.getEnd()); 7732 } 7733 7734 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7735 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7736 << FixItHint::CreateRemoval(RemovalRange); 7737 } 7738 7739 //===--- CHECK: Standard memory functions ---------------------------------===// 7740 7741 /// Takes the expression passed to the size_t parameter of functions 7742 /// such as memcmp, strncat, etc and warns if it's a comparison. 7743 /// 7744 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7745 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7746 IdentifierInfo *FnName, 7747 SourceLocation FnLoc, 7748 SourceLocation RParenLoc) { 7749 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7750 if (!Size) 7751 return false; 7752 7753 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 7754 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 7755 return false; 7756 7757 SourceRange SizeRange = Size->getSourceRange(); 7758 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7759 << SizeRange << FnName; 7760 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7761 << FnName << FixItHint::CreateInsertion( 7762 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7763 << FixItHint::CreateRemoval(RParenLoc); 7764 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7765 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7766 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7767 ")"); 7768 7769 return true; 7770 } 7771 7772 /// Determine whether the given type is or contains a dynamic class type 7773 /// (e.g., whether it has a vtable). 7774 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7775 bool &IsContained) { 7776 // Look through array types while ignoring qualifiers. 7777 const Type *Ty = T->getBaseElementTypeUnsafe(); 7778 IsContained = false; 7779 7780 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7781 RD = RD ? RD->getDefinition() : nullptr; 7782 if (!RD || RD->isInvalidDecl()) 7783 return nullptr; 7784 7785 if (RD->isDynamicClass()) 7786 return RD; 7787 7788 // Check all the fields. If any bases were dynamic, the class is dynamic. 7789 // It's impossible for a class to transitively contain itself by value, so 7790 // infinite recursion is impossible. 7791 for (auto *FD : RD->fields()) { 7792 bool SubContained; 7793 if (const CXXRecordDecl *ContainedRD = 7794 getContainedDynamicClass(FD->getType(), SubContained)) { 7795 IsContained = true; 7796 return ContainedRD; 7797 } 7798 } 7799 7800 return nullptr; 7801 } 7802 7803 /// If E is a sizeof expression, returns its argument expression, 7804 /// otherwise returns NULL. 7805 static const Expr *getSizeOfExprArg(const Expr *E) { 7806 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7807 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7808 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType()) 7809 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7810 7811 return nullptr; 7812 } 7813 7814 /// If E is a sizeof expression, returns its argument type. 7815 static QualType getSizeOfArgType(const Expr *E) { 7816 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7817 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7818 if (SizeOf->getKind() == UETT_SizeOf) 7819 return SizeOf->getTypeOfArgument(); 7820 7821 return QualType(); 7822 } 7823 7824 namespace { 7825 7826 struct SearchNonTrivialToInitializeField 7827 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 7828 using Super = 7829 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 7830 7831 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 7832 7833 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 7834 SourceLocation SL) { 7835 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7836 asDerived().visitArray(PDIK, AT, SL); 7837 return; 7838 } 7839 7840 Super::visitWithKind(PDIK, FT, SL); 7841 } 7842 7843 void visitARCStrong(QualType FT, SourceLocation SL) { 7844 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7845 } 7846 void visitARCWeak(QualType FT, SourceLocation SL) { 7847 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7848 } 7849 void visitStruct(QualType FT, SourceLocation SL) { 7850 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7851 visit(FD->getType(), FD->getLocation()); 7852 } 7853 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 7854 const ArrayType *AT, SourceLocation SL) { 7855 visit(getContext().getBaseElementType(AT), SL); 7856 } 7857 void visitTrivial(QualType FT, SourceLocation SL) {} 7858 7859 static void diag(QualType RT, const Expr *E, Sema &S) { 7860 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 7861 } 7862 7863 ASTContext &getContext() { return S.getASTContext(); } 7864 7865 const Expr *E; 7866 Sema &S; 7867 }; 7868 7869 struct SearchNonTrivialToCopyField 7870 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 7871 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 7872 7873 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 7874 7875 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 7876 SourceLocation SL) { 7877 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7878 asDerived().visitArray(PCK, AT, SL); 7879 return; 7880 } 7881 7882 Super::visitWithKind(PCK, FT, SL); 7883 } 7884 7885 void visitARCStrong(QualType FT, SourceLocation SL) { 7886 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7887 } 7888 void visitARCWeak(QualType FT, SourceLocation SL) { 7889 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7890 } 7891 void visitStruct(QualType FT, SourceLocation SL) { 7892 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7893 visit(FD->getType(), FD->getLocation()); 7894 } 7895 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 7896 SourceLocation SL) { 7897 visit(getContext().getBaseElementType(AT), SL); 7898 } 7899 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 7900 SourceLocation SL) {} 7901 void visitTrivial(QualType FT, SourceLocation SL) {} 7902 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 7903 7904 static void diag(QualType RT, const Expr *E, Sema &S) { 7905 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 7906 } 7907 7908 ASTContext &getContext() { return S.getASTContext(); } 7909 7910 const Expr *E; 7911 Sema &S; 7912 }; 7913 7914 } 7915 7916 /// Check for dangerous or invalid arguments to memset(). 7917 /// 7918 /// This issues warnings on known problematic, dangerous or unspecified 7919 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7920 /// function calls. 7921 /// 7922 /// \param Call The call expression to diagnose. 7923 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7924 unsigned BId, 7925 IdentifierInfo *FnName) { 7926 assert(BId != 0); 7927 7928 // It is possible to have a non-standard definition of memset. Validate 7929 // we have enough arguments, and if not, abort further checking. 7930 unsigned ExpectedNumArgs = 7931 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7932 if (Call->getNumArgs() < ExpectedNumArgs) 7933 return; 7934 7935 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7936 BId == Builtin::BIstrndup ? 1 : 2); 7937 unsigned LenArg = 7938 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7939 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7940 7941 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7942 Call->getLocStart(), Call->getRParenLoc())) 7943 return; 7944 7945 // We have special checking when the length is a sizeof expression. 7946 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7947 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7948 llvm::FoldingSetNodeID SizeOfArgID; 7949 7950 // Although widely used, 'bzero' is not a standard function. Be more strict 7951 // with the argument types before allowing diagnostics and only allow the 7952 // form bzero(ptr, sizeof(...)). 7953 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7954 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7955 return; 7956 7957 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7958 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7959 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7960 7961 QualType DestTy = Dest->getType(); 7962 QualType PointeeTy; 7963 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7964 PointeeTy = DestPtrTy->getPointeeType(); 7965 7966 // Never warn about void type pointers. This can be used to suppress 7967 // false positives. 7968 if (PointeeTy->isVoidType()) 7969 continue; 7970 7971 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 7972 // actually comparing the expressions for equality. Because computing the 7973 // expression IDs can be expensive, we only do this if the diagnostic is 7974 // enabled. 7975 if (SizeOfArg && 7976 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 7977 SizeOfArg->getExprLoc())) { 7978 // We only compute IDs for expressions if the warning is enabled, and 7979 // cache the sizeof arg's ID. 7980 if (SizeOfArgID == llvm::FoldingSetNodeID()) 7981 SizeOfArg->Profile(SizeOfArgID, Context, true); 7982 llvm::FoldingSetNodeID DestID; 7983 Dest->Profile(DestID, Context, true); 7984 if (DestID == SizeOfArgID) { 7985 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 7986 // over sizeof(src) as well. 7987 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 7988 StringRef ReadableName = FnName->getName(); 7989 7990 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 7991 if (UnaryOp->getOpcode() == UO_AddrOf) 7992 ActionIdx = 1; // If its an address-of operator, just remove it. 7993 if (!PointeeTy->isIncompleteType() && 7994 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 7995 ActionIdx = 2; // If the pointee's size is sizeof(char), 7996 // suggest an explicit length. 7997 7998 // If the function is defined as a builtin macro, do not show macro 7999 // expansion. 8000 SourceLocation SL = SizeOfArg->getExprLoc(); 8001 SourceRange DSR = Dest->getSourceRange(); 8002 SourceRange SSR = SizeOfArg->getSourceRange(); 8003 SourceManager &SM = getSourceManager(); 8004 8005 if (SM.isMacroArgExpansion(SL)) { 8006 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 8007 SL = SM.getSpellingLoc(SL); 8008 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 8009 SM.getSpellingLoc(DSR.getEnd())); 8010 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 8011 SM.getSpellingLoc(SSR.getEnd())); 8012 } 8013 8014 DiagRuntimeBehavior(SL, SizeOfArg, 8015 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 8016 << ReadableName 8017 << PointeeTy 8018 << DestTy 8019 << DSR 8020 << SSR); 8021 DiagRuntimeBehavior(SL, SizeOfArg, 8022 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 8023 << ActionIdx 8024 << SSR); 8025 8026 break; 8027 } 8028 } 8029 8030 // Also check for cases where the sizeof argument is the exact same 8031 // type as the memory argument, and where it points to a user-defined 8032 // record type. 8033 if (SizeOfArgTy != QualType()) { 8034 if (PointeeTy->isRecordType() && 8035 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 8036 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 8037 PDiag(diag::warn_sizeof_pointer_type_memaccess) 8038 << FnName << SizeOfArgTy << ArgIdx 8039 << PointeeTy << Dest->getSourceRange() 8040 << LenExpr->getSourceRange()); 8041 break; 8042 } 8043 } 8044 } else if (DestTy->isArrayType()) { 8045 PointeeTy = DestTy; 8046 } 8047 8048 if (PointeeTy == QualType()) 8049 continue; 8050 8051 // Always complain about dynamic classes. 8052 bool IsContained; 8053 if (const CXXRecordDecl *ContainedRD = 8054 getContainedDynamicClass(PointeeTy, IsContained)) { 8055 8056 unsigned OperationType = 0; 8057 // "overwritten" if we're warning about the destination for any call 8058 // but memcmp; otherwise a verb appropriate to the call. 8059 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 8060 if (BId == Builtin::BImemcpy) 8061 OperationType = 1; 8062 else if(BId == Builtin::BImemmove) 8063 OperationType = 2; 8064 else if (BId == Builtin::BImemcmp) 8065 OperationType = 3; 8066 } 8067 8068 DiagRuntimeBehavior( 8069 Dest->getExprLoc(), Dest, 8070 PDiag(diag::warn_dyn_class_memaccess) 8071 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 8072 << FnName << IsContained << ContainedRD << OperationType 8073 << Call->getCallee()->getSourceRange()); 8074 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 8075 BId != Builtin::BImemset) 8076 DiagRuntimeBehavior( 8077 Dest->getExprLoc(), Dest, 8078 PDiag(diag::warn_arc_object_memaccess) 8079 << ArgIdx << FnName << PointeeTy 8080 << Call->getCallee()->getSourceRange()); 8081 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 8082 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 8083 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 8084 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 8085 PDiag(diag::warn_cstruct_memaccess) 8086 << ArgIdx << FnName << PointeeTy << 0); 8087 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 8088 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 8089 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 8090 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 8091 PDiag(diag::warn_cstruct_memaccess) 8092 << ArgIdx << FnName << PointeeTy << 1); 8093 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 8094 } else { 8095 continue; 8096 } 8097 } else 8098 continue; 8099 8100 DiagRuntimeBehavior( 8101 Dest->getExprLoc(), Dest, 8102 PDiag(diag::note_bad_memaccess_silence) 8103 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 8104 break; 8105 } 8106 } 8107 8108 // A little helper routine: ignore addition and subtraction of integer literals. 8109 // This intentionally does not ignore all integer constant expressions because 8110 // we don't want to remove sizeof(). 8111 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 8112 Ex = Ex->IgnoreParenCasts(); 8113 8114 while (true) { 8115 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 8116 if (!BO || !BO->isAdditiveOp()) 8117 break; 8118 8119 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 8120 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 8121 8122 if (isa<IntegerLiteral>(RHS)) 8123 Ex = LHS; 8124 else if (isa<IntegerLiteral>(LHS)) 8125 Ex = RHS; 8126 else 8127 break; 8128 } 8129 8130 return Ex; 8131 } 8132 8133 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 8134 ASTContext &Context) { 8135 // Only handle constant-sized or VLAs, but not flexible members. 8136 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 8137 // Only issue the FIXIT for arrays of size > 1. 8138 if (CAT->getSize().getSExtValue() <= 1) 8139 return false; 8140 } else if (!Ty->isVariableArrayType()) { 8141 return false; 8142 } 8143 return true; 8144 } 8145 8146 // Warn if the user has made the 'size' argument to strlcpy or strlcat 8147 // be the size of the source, instead of the destination. 8148 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 8149 IdentifierInfo *FnName) { 8150 8151 // Don't crash if the user has the wrong number of arguments 8152 unsigned NumArgs = Call->getNumArgs(); 8153 if ((NumArgs != 3) && (NumArgs != 4)) 8154 return; 8155 8156 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 8157 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 8158 const Expr *CompareWithSrc = nullptr; 8159 8160 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 8161 Call->getLocStart(), Call->getRParenLoc())) 8162 return; 8163 8164 // Look for 'strlcpy(dst, x, sizeof(x))' 8165 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 8166 CompareWithSrc = Ex; 8167 else { 8168 // Look for 'strlcpy(dst, x, strlen(x))' 8169 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 8170 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 8171 SizeCall->getNumArgs() == 1) 8172 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 8173 } 8174 } 8175 8176 if (!CompareWithSrc) 8177 return; 8178 8179 // Determine if the argument to sizeof/strlen is equal to the source 8180 // argument. In principle there's all kinds of things you could do 8181 // here, for instance creating an == expression and evaluating it with 8182 // EvaluateAsBooleanCondition, but this uses a more direct technique: 8183 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 8184 if (!SrcArgDRE) 8185 return; 8186 8187 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 8188 if (!CompareWithSrcDRE || 8189 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 8190 return; 8191 8192 const Expr *OriginalSizeArg = Call->getArg(2); 8193 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 8194 << OriginalSizeArg->getSourceRange() << FnName; 8195 8196 // Output a FIXIT hint if the destination is an array (rather than a 8197 // pointer to an array). This could be enhanced to handle some 8198 // pointers if we know the actual size, like if DstArg is 'array+2' 8199 // we could say 'sizeof(array)-2'. 8200 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 8201 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 8202 return; 8203 8204 SmallString<128> sizeString; 8205 llvm::raw_svector_ostream OS(sizeString); 8206 OS << "sizeof("; 8207 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8208 OS << ")"; 8209 8210 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 8211 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 8212 OS.str()); 8213 } 8214 8215 /// Check if two expressions refer to the same declaration. 8216 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 8217 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 8218 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 8219 return D1->getDecl() == D2->getDecl(); 8220 return false; 8221 } 8222 8223 static const Expr *getStrlenExprArg(const Expr *E) { 8224 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8225 const FunctionDecl *FD = CE->getDirectCallee(); 8226 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 8227 return nullptr; 8228 return CE->getArg(0)->IgnoreParenCasts(); 8229 } 8230 return nullptr; 8231 } 8232 8233 // Warn on anti-patterns as the 'size' argument to strncat. 8234 // The correct size argument should look like following: 8235 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 8236 void Sema::CheckStrncatArguments(const CallExpr *CE, 8237 IdentifierInfo *FnName) { 8238 // Don't crash if the user has the wrong number of arguments. 8239 if (CE->getNumArgs() < 3) 8240 return; 8241 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 8242 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 8243 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 8244 8245 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 8246 CE->getRParenLoc())) 8247 return; 8248 8249 // Identify common expressions, which are wrongly used as the size argument 8250 // to strncat and may lead to buffer overflows. 8251 unsigned PatternType = 0; 8252 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 8253 // - sizeof(dst) 8254 if (referToTheSameDecl(SizeOfArg, DstArg)) 8255 PatternType = 1; 8256 // - sizeof(src) 8257 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 8258 PatternType = 2; 8259 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 8260 if (BE->getOpcode() == BO_Sub) { 8261 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 8262 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 8263 // - sizeof(dst) - strlen(dst) 8264 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 8265 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 8266 PatternType = 1; 8267 // - sizeof(src) - (anything) 8268 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 8269 PatternType = 2; 8270 } 8271 } 8272 8273 if (PatternType == 0) 8274 return; 8275 8276 // Generate the diagnostic. 8277 SourceLocation SL = LenArg->getLocStart(); 8278 SourceRange SR = LenArg->getSourceRange(); 8279 SourceManager &SM = getSourceManager(); 8280 8281 // If the function is defined as a builtin macro, do not show macro expansion. 8282 if (SM.isMacroArgExpansion(SL)) { 8283 SL = SM.getSpellingLoc(SL); 8284 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 8285 SM.getSpellingLoc(SR.getEnd())); 8286 } 8287 8288 // Check if the destination is an array (rather than a pointer to an array). 8289 QualType DstTy = DstArg->getType(); 8290 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 8291 Context); 8292 if (!isKnownSizeArray) { 8293 if (PatternType == 1) 8294 Diag(SL, diag::warn_strncat_wrong_size) << SR; 8295 else 8296 Diag(SL, diag::warn_strncat_src_size) << SR; 8297 return; 8298 } 8299 8300 if (PatternType == 1) 8301 Diag(SL, diag::warn_strncat_large_size) << SR; 8302 else 8303 Diag(SL, diag::warn_strncat_src_size) << SR; 8304 8305 SmallString<128> sizeString; 8306 llvm::raw_svector_ostream OS(sizeString); 8307 OS << "sizeof("; 8308 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8309 OS << ") - "; 8310 OS << "strlen("; 8311 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8312 OS << ") - 1"; 8313 8314 Diag(SL, diag::note_strncat_wrong_size) 8315 << FixItHint::CreateReplacement(SR, OS.str()); 8316 } 8317 8318 //===--- CHECK: Return Address of Stack Variable --------------------------===// 8319 8320 static const Expr *EvalVal(const Expr *E, 8321 SmallVectorImpl<const DeclRefExpr *> &refVars, 8322 const Decl *ParentDecl); 8323 static const Expr *EvalAddr(const Expr *E, 8324 SmallVectorImpl<const DeclRefExpr *> &refVars, 8325 const Decl *ParentDecl); 8326 8327 /// CheckReturnStackAddr - Check if a return statement returns the address 8328 /// of a stack variable. 8329 static void 8330 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 8331 SourceLocation ReturnLoc) { 8332 const Expr *stackE = nullptr; 8333 SmallVector<const DeclRefExpr *, 8> refVars; 8334 8335 // Perform checking for returned stack addresses, local blocks, 8336 // label addresses or references to temporaries. 8337 if (lhsType->isPointerType() || 8338 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 8339 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 8340 } else if (lhsType->isReferenceType()) { 8341 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 8342 } 8343 8344 if (!stackE) 8345 return; // Nothing suspicious was found. 8346 8347 // Parameters are initialized in the calling scope, so taking the address 8348 // of a parameter reference doesn't need a warning. 8349 for (auto *DRE : refVars) 8350 if (isa<ParmVarDecl>(DRE->getDecl())) 8351 return; 8352 8353 SourceLocation diagLoc; 8354 SourceRange diagRange; 8355 if (refVars.empty()) { 8356 diagLoc = stackE->getLocStart(); 8357 diagRange = stackE->getSourceRange(); 8358 } else { 8359 // We followed through a reference variable. 'stackE' contains the 8360 // problematic expression but we will warn at the return statement pointing 8361 // at the reference variable. We will later display the "trail" of 8362 // reference variables using notes. 8363 diagLoc = refVars[0]->getLocStart(); 8364 diagRange = refVars[0]->getSourceRange(); 8365 } 8366 8367 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 8368 // address of local var 8369 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 8370 << DR->getDecl()->getDeclName() << diagRange; 8371 } else if (isa<BlockExpr>(stackE)) { // local block. 8372 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 8373 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 8374 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 8375 } else { // local temporary. 8376 // If there is an LValue->RValue conversion, then the value of the 8377 // reference type is used, not the reference. 8378 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 8379 if (ICE->getCastKind() == CK_LValueToRValue) { 8380 return; 8381 } 8382 } 8383 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 8384 << lhsType->isReferenceType() << diagRange; 8385 } 8386 8387 // Display the "trail" of reference variables that we followed until we 8388 // found the problematic expression using notes. 8389 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 8390 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 8391 // If this var binds to another reference var, show the range of the next 8392 // var, otherwise the var binds to the problematic expression, in which case 8393 // show the range of the expression. 8394 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 8395 : stackE->getSourceRange(); 8396 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 8397 << VD->getDeclName() << range; 8398 } 8399 } 8400 8401 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 8402 /// check if the expression in a return statement evaluates to an address 8403 /// to a location on the stack, a local block, an address of a label, or a 8404 /// reference to local temporary. The recursion is used to traverse the 8405 /// AST of the return expression, with recursion backtracking when we 8406 /// encounter a subexpression that (1) clearly does not lead to one of the 8407 /// above problematic expressions (2) is something we cannot determine leads to 8408 /// a problematic expression based on such local checking. 8409 /// 8410 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 8411 /// the expression that they point to. Such variables are added to the 8412 /// 'refVars' vector so that we know what the reference variable "trail" was. 8413 /// 8414 /// EvalAddr processes expressions that are pointers that are used as 8415 /// references (and not L-values). EvalVal handles all other values. 8416 /// At the base case of the recursion is a check for the above problematic 8417 /// expressions. 8418 /// 8419 /// This implementation handles: 8420 /// 8421 /// * pointer-to-pointer casts 8422 /// * implicit conversions from array references to pointers 8423 /// * taking the address of fields 8424 /// * arbitrary interplay between "&" and "*" operators 8425 /// * pointer arithmetic from an address of a stack variable 8426 /// * taking the address of an array element where the array is on the stack 8427 static const Expr *EvalAddr(const Expr *E, 8428 SmallVectorImpl<const DeclRefExpr *> &refVars, 8429 const Decl *ParentDecl) { 8430 if (E->isTypeDependent()) 8431 return nullptr; 8432 8433 // We should only be called for evaluating pointer expressions. 8434 assert((E->getType()->isAnyPointerType() || 8435 E->getType()->isBlockPointerType() || 8436 E->getType()->isObjCQualifiedIdType()) && 8437 "EvalAddr only works on pointers"); 8438 8439 E = E->IgnoreParens(); 8440 8441 // Our "symbolic interpreter" is just a dispatch off the currently 8442 // viewed AST node. We then recursively traverse the AST by calling 8443 // EvalAddr and EvalVal appropriately. 8444 switch (E->getStmtClass()) { 8445 case Stmt::DeclRefExprClass: { 8446 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8447 8448 // If we leave the immediate function, the lifetime isn't about to end. 8449 if (DR->refersToEnclosingVariableOrCapture()) 8450 return nullptr; 8451 8452 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 8453 // If this is a reference variable, follow through to the expression that 8454 // it points to. 8455 if (V->hasLocalStorage() && 8456 V->getType()->isReferenceType() && V->hasInit()) { 8457 // Add the reference variable to the "trail". 8458 refVars.push_back(DR); 8459 return EvalAddr(V->getInit(), refVars, ParentDecl); 8460 } 8461 8462 return nullptr; 8463 } 8464 8465 case Stmt::UnaryOperatorClass: { 8466 // The only unary operator that make sense to handle here 8467 // is AddrOf. All others don't make sense as pointers. 8468 const UnaryOperator *U = cast<UnaryOperator>(E); 8469 8470 if (U->getOpcode() == UO_AddrOf) 8471 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 8472 return nullptr; 8473 } 8474 8475 case Stmt::BinaryOperatorClass: { 8476 // Handle pointer arithmetic. All other binary operators are not valid 8477 // in this context. 8478 const BinaryOperator *B = cast<BinaryOperator>(E); 8479 BinaryOperatorKind op = B->getOpcode(); 8480 8481 if (op != BO_Add && op != BO_Sub) 8482 return nullptr; 8483 8484 const Expr *Base = B->getLHS(); 8485 8486 // Determine which argument is the real pointer base. It could be 8487 // the RHS argument instead of the LHS. 8488 if (!Base->getType()->isPointerType()) 8489 Base = B->getRHS(); 8490 8491 assert(Base->getType()->isPointerType()); 8492 return EvalAddr(Base, refVars, ParentDecl); 8493 } 8494 8495 // For conditional operators we need to see if either the LHS or RHS are 8496 // valid DeclRefExpr*s. If one of them is valid, we return it. 8497 case Stmt::ConditionalOperatorClass: { 8498 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8499 8500 // Handle the GNU extension for missing LHS. 8501 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 8502 if (const Expr *LHSExpr = C->getLHS()) { 8503 // In C++, we can have a throw-expression, which has 'void' type. 8504 if (!LHSExpr->getType()->isVoidType()) 8505 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 8506 return LHS; 8507 } 8508 8509 // In C++, we can have a throw-expression, which has 'void' type. 8510 if (C->getRHS()->getType()->isVoidType()) 8511 return nullptr; 8512 8513 return EvalAddr(C->getRHS(), refVars, ParentDecl); 8514 } 8515 8516 case Stmt::BlockExprClass: 8517 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 8518 return E; // local block. 8519 return nullptr; 8520 8521 case Stmt::AddrLabelExprClass: 8522 return E; // address of label. 8523 8524 case Stmt::ExprWithCleanupsClass: 8525 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8526 ParentDecl); 8527 8528 // For casts, we need to handle conversions from arrays to 8529 // pointer values, and pointer-to-pointer conversions. 8530 case Stmt::ImplicitCastExprClass: 8531 case Stmt::CStyleCastExprClass: 8532 case Stmt::CXXFunctionalCastExprClass: 8533 case Stmt::ObjCBridgedCastExprClass: 8534 case Stmt::CXXStaticCastExprClass: 8535 case Stmt::CXXDynamicCastExprClass: 8536 case Stmt::CXXConstCastExprClass: 8537 case Stmt::CXXReinterpretCastExprClass: { 8538 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 8539 switch (cast<CastExpr>(E)->getCastKind()) { 8540 case CK_LValueToRValue: 8541 case CK_NoOp: 8542 case CK_BaseToDerived: 8543 case CK_DerivedToBase: 8544 case CK_UncheckedDerivedToBase: 8545 case CK_Dynamic: 8546 case CK_CPointerToObjCPointerCast: 8547 case CK_BlockPointerToObjCPointerCast: 8548 case CK_AnyPointerToBlockPointerCast: 8549 return EvalAddr(SubExpr, refVars, ParentDecl); 8550 8551 case CK_ArrayToPointerDecay: 8552 return EvalVal(SubExpr, refVars, ParentDecl); 8553 8554 case CK_BitCast: 8555 if (SubExpr->getType()->isAnyPointerType() || 8556 SubExpr->getType()->isBlockPointerType() || 8557 SubExpr->getType()->isObjCQualifiedIdType()) 8558 return EvalAddr(SubExpr, refVars, ParentDecl); 8559 else 8560 return nullptr; 8561 8562 default: 8563 return nullptr; 8564 } 8565 } 8566 8567 case Stmt::MaterializeTemporaryExprClass: 8568 if (const Expr *Result = 8569 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8570 refVars, ParentDecl)) 8571 return Result; 8572 return E; 8573 8574 // Everything else: we simply don't reason about them. 8575 default: 8576 return nullptr; 8577 } 8578 } 8579 8580 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 8581 /// See the comments for EvalAddr for more details. 8582 static const Expr *EvalVal(const Expr *E, 8583 SmallVectorImpl<const DeclRefExpr *> &refVars, 8584 const Decl *ParentDecl) { 8585 do { 8586 // We should only be called for evaluating non-pointer expressions, or 8587 // expressions with a pointer type that are not used as references but 8588 // instead 8589 // are l-values (e.g., DeclRefExpr with a pointer type). 8590 8591 // Our "symbolic interpreter" is just a dispatch off the currently 8592 // viewed AST node. We then recursively traverse the AST by calling 8593 // EvalAddr and EvalVal appropriately. 8594 8595 E = E->IgnoreParens(); 8596 switch (E->getStmtClass()) { 8597 case Stmt::ImplicitCastExprClass: { 8598 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 8599 if (IE->getValueKind() == VK_LValue) { 8600 E = IE->getSubExpr(); 8601 continue; 8602 } 8603 return nullptr; 8604 } 8605 8606 case Stmt::ExprWithCleanupsClass: 8607 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8608 ParentDecl); 8609 8610 case Stmt::DeclRefExprClass: { 8611 // When we hit a DeclRefExpr we are looking at code that refers to a 8612 // variable's name. If it's not a reference variable we check if it has 8613 // local storage within the function, and if so, return the expression. 8614 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8615 8616 // If we leave the immediate function, the lifetime isn't about to end. 8617 if (DR->refersToEnclosingVariableOrCapture()) 8618 return nullptr; 8619 8620 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 8621 // Check if it refers to itself, e.g. "int& i = i;". 8622 if (V == ParentDecl) 8623 return DR; 8624 8625 if (V->hasLocalStorage()) { 8626 if (!V->getType()->isReferenceType()) 8627 return DR; 8628 8629 // Reference variable, follow through to the expression that 8630 // it points to. 8631 if (V->hasInit()) { 8632 // Add the reference variable to the "trail". 8633 refVars.push_back(DR); 8634 return EvalVal(V->getInit(), refVars, V); 8635 } 8636 } 8637 } 8638 8639 return nullptr; 8640 } 8641 8642 case Stmt::UnaryOperatorClass: { 8643 // The only unary operator that make sense to handle here 8644 // is Deref. All others don't resolve to a "name." This includes 8645 // handling all sorts of rvalues passed to a unary operator. 8646 const UnaryOperator *U = cast<UnaryOperator>(E); 8647 8648 if (U->getOpcode() == UO_Deref) 8649 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 8650 8651 return nullptr; 8652 } 8653 8654 case Stmt::ArraySubscriptExprClass: { 8655 // Array subscripts are potential references to data on the stack. We 8656 // retrieve the DeclRefExpr* for the array variable if it indeed 8657 // has local storage. 8658 const auto *ASE = cast<ArraySubscriptExpr>(E); 8659 if (ASE->isTypeDependent()) 8660 return nullptr; 8661 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8662 } 8663 8664 case Stmt::OMPArraySectionExprClass: { 8665 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8666 ParentDecl); 8667 } 8668 8669 case Stmt::ConditionalOperatorClass: { 8670 // For conditional operators we need to see if either the LHS or RHS are 8671 // non-NULL Expr's. If one is non-NULL, we return it. 8672 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8673 8674 // Handle the GNU extension for missing LHS. 8675 if (const Expr *LHSExpr = C->getLHS()) { 8676 // In C++, we can have a throw-expression, which has 'void' type. 8677 if (!LHSExpr->getType()->isVoidType()) 8678 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8679 return LHS; 8680 } 8681 8682 // In C++, we can have a throw-expression, which has 'void' type. 8683 if (C->getRHS()->getType()->isVoidType()) 8684 return nullptr; 8685 8686 return EvalVal(C->getRHS(), refVars, ParentDecl); 8687 } 8688 8689 // Accesses to members are potential references to data on the stack. 8690 case Stmt::MemberExprClass: { 8691 const MemberExpr *M = cast<MemberExpr>(E); 8692 8693 // Check for indirect access. We only want direct field accesses. 8694 if (M->isArrow()) 8695 return nullptr; 8696 8697 // Check whether the member type is itself a reference, in which case 8698 // we're not going to refer to the member, but to what the member refers 8699 // to. 8700 if (M->getMemberDecl()->getType()->isReferenceType()) 8701 return nullptr; 8702 8703 return EvalVal(M->getBase(), refVars, ParentDecl); 8704 } 8705 8706 case Stmt::MaterializeTemporaryExprClass: 8707 if (const Expr *Result = 8708 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8709 refVars, ParentDecl)) 8710 return Result; 8711 return E; 8712 8713 default: 8714 // Check that we don't return or take the address of a reference to a 8715 // temporary. This is only useful in C++. 8716 if (!E->isTypeDependent() && E->isRValue()) 8717 return E; 8718 8719 // Everything else: we simply don't reason about them. 8720 return nullptr; 8721 } 8722 } while (true); 8723 } 8724 8725 void 8726 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8727 SourceLocation ReturnLoc, 8728 bool isObjCMethod, 8729 const AttrVec *Attrs, 8730 const FunctionDecl *FD) { 8731 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8732 8733 // Check if the return value is null but should not be. 8734 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8735 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8736 CheckNonNullExpr(*this, RetValExp)) 8737 Diag(ReturnLoc, diag::warn_null_ret) 8738 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8739 8740 // C++11 [basic.stc.dynamic.allocation]p4: 8741 // If an allocation function declared with a non-throwing 8742 // exception-specification fails to allocate storage, it shall return 8743 // a null pointer. Any other allocation function that fails to allocate 8744 // storage shall indicate failure only by throwing an exception [...] 8745 if (FD) { 8746 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8747 if (Op == OO_New || Op == OO_Array_New) { 8748 const FunctionProtoType *Proto 8749 = FD->getType()->castAs<FunctionProtoType>(); 8750 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 8751 CheckNonNullExpr(*this, RetValExp)) 8752 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8753 << FD << getLangOpts().CPlusPlus11; 8754 } 8755 } 8756 } 8757 8758 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8759 8760 /// Check for comparisons of floating point operands using != and ==. 8761 /// Issue a warning if these are no self-comparisons, as they are not likely 8762 /// to do what the programmer intended. 8763 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8764 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8765 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8766 8767 // Special case: check for x == x (which is OK). 8768 // Do not emit warnings for such cases. 8769 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8770 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8771 if (DRL->getDecl() == DRR->getDecl()) 8772 return; 8773 8774 // Special case: check for comparisons against literals that can be exactly 8775 // represented by APFloat. In such cases, do not emit a warning. This 8776 // is a heuristic: often comparison against such literals are used to 8777 // detect if a value in a variable has not changed. This clearly can 8778 // lead to false negatives. 8779 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8780 if (FLL->isExact()) 8781 return; 8782 } else 8783 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8784 if (FLR->isExact()) 8785 return; 8786 8787 // Check for comparisons with builtin types. 8788 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8789 if (CL->getBuiltinCallee()) 8790 return; 8791 8792 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8793 if (CR->getBuiltinCallee()) 8794 return; 8795 8796 // Emit the diagnostic. 8797 Diag(Loc, diag::warn_floatingpoint_eq) 8798 << LHS->getSourceRange() << RHS->getSourceRange(); 8799 } 8800 8801 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8802 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8803 8804 namespace { 8805 8806 /// Structure recording the 'active' range of an integer-valued 8807 /// expression. 8808 struct IntRange { 8809 /// The number of bits active in the int. 8810 unsigned Width; 8811 8812 /// True if the int is known not to have negative values. 8813 bool NonNegative; 8814 8815 IntRange(unsigned Width, bool NonNegative) 8816 : Width(Width), NonNegative(NonNegative) {} 8817 8818 /// Returns the range of the bool type. 8819 static IntRange forBoolType() { 8820 return IntRange(1, true); 8821 } 8822 8823 /// Returns the range of an opaque value of the given integral type. 8824 static IntRange forValueOfType(ASTContext &C, QualType T) { 8825 return forValueOfCanonicalType(C, 8826 T->getCanonicalTypeInternal().getTypePtr()); 8827 } 8828 8829 /// Returns the range of an opaque value of a canonical integral type. 8830 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8831 assert(T->isCanonicalUnqualified()); 8832 8833 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8834 T = VT->getElementType().getTypePtr(); 8835 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8836 T = CT->getElementType().getTypePtr(); 8837 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8838 T = AT->getValueType().getTypePtr(); 8839 8840 if (!C.getLangOpts().CPlusPlus) { 8841 // For enum types in C code, use the underlying datatype. 8842 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8843 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 8844 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8845 // For enum types in C++, use the known bit width of the enumerators. 8846 EnumDecl *Enum = ET->getDecl(); 8847 // In C++11, enums can have a fixed underlying type. Use this type to 8848 // compute the range. 8849 if (Enum->isFixed()) { 8850 return IntRange(C.getIntWidth(QualType(T, 0)), 8851 !ET->isSignedIntegerOrEnumerationType()); 8852 } 8853 8854 unsigned NumPositive = Enum->getNumPositiveBits(); 8855 unsigned NumNegative = Enum->getNumNegativeBits(); 8856 8857 if (NumNegative == 0) 8858 return IntRange(NumPositive, true/*NonNegative*/); 8859 else 8860 return IntRange(std::max(NumPositive + 1, NumNegative), 8861 false/*NonNegative*/); 8862 } 8863 8864 const BuiltinType *BT = cast<BuiltinType>(T); 8865 assert(BT->isInteger()); 8866 8867 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8868 } 8869 8870 /// Returns the "target" range of a canonical integral type, i.e. 8871 /// the range of values expressible in the type. 8872 /// 8873 /// This matches forValueOfCanonicalType except that enums have the 8874 /// full range of their type, not the range of their enumerators. 8875 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8876 assert(T->isCanonicalUnqualified()); 8877 8878 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8879 T = VT->getElementType().getTypePtr(); 8880 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8881 T = CT->getElementType().getTypePtr(); 8882 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8883 T = AT->getValueType().getTypePtr(); 8884 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8885 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8886 8887 const BuiltinType *BT = cast<BuiltinType>(T); 8888 assert(BT->isInteger()); 8889 8890 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8891 } 8892 8893 /// Returns the supremum of two ranges: i.e. their conservative merge. 8894 static IntRange join(IntRange L, IntRange R) { 8895 return IntRange(std::max(L.Width, R.Width), 8896 L.NonNegative && R.NonNegative); 8897 } 8898 8899 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8900 static IntRange meet(IntRange L, IntRange R) { 8901 return IntRange(std::min(L.Width, R.Width), 8902 L.NonNegative || R.NonNegative); 8903 } 8904 }; 8905 8906 } // namespace 8907 8908 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 8909 unsigned MaxWidth) { 8910 if (value.isSigned() && value.isNegative()) 8911 return IntRange(value.getMinSignedBits(), false); 8912 8913 if (value.getBitWidth() > MaxWidth) 8914 value = value.trunc(MaxWidth); 8915 8916 // isNonNegative() just checks the sign bit without considering 8917 // signedness. 8918 return IntRange(value.getActiveBits(), true); 8919 } 8920 8921 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8922 unsigned MaxWidth) { 8923 if (result.isInt()) 8924 return GetValueRange(C, result.getInt(), MaxWidth); 8925 8926 if (result.isVector()) { 8927 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8928 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8929 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8930 R = IntRange::join(R, El); 8931 } 8932 return R; 8933 } 8934 8935 if (result.isComplexInt()) { 8936 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8937 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8938 return IntRange::join(R, I); 8939 } 8940 8941 // This can happen with lossless casts to intptr_t of "based" lvalues. 8942 // Assume it might use arbitrary bits. 8943 // FIXME: The only reason we need to pass the type in here is to get 8944 // the sign right on this one case. It would be nice if APValue 8945 // preserved this. 8946 assert(result.isLValue() || result.isAddrLabelDiff()); 8947 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8948 } 8949 8950 static QualType GetExprType(const Expr *E) { 8951 QualType Ty = E->getType(); 8952 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8953 Ty = AtomicRHS->getValueType(); 8954 return Ty; 8955 } 8956 8957 /// Pseudo-evaluate the given integer expression, estimating the 8958 /// range of values it might take. 8959 /// 8960 /// \param MaxWidth - the width to which the value will be truncated 8961 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8962 E = E->IgnoreParens(); 8963 8964 // Try a full evaluation first. 8965 Expr::EvalResult result; 8966 if (E->EvaluateAsRValue(result, C)) 8967 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8968 8969 // I think we only want to look through implicit casts here; if the 8970 // user has an explicit widening cast, we should treat the value as 8971 // being of the new, wider type. 8972 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 8973 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 8974 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 8975 8976 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 8977 8978 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 8979 CE->getCastKind() == CK_BooleanToSignedIntegral; 8980 8981 // Assume that non-integer casts can span the full range of the type. 8982 if (!isIntegerCast) 8983 return OutputTypeRange; 8984 8985 IntRange SubRange 8986 = GetExprRange(C, CE->getSubExpr(), 8987 std::min(MaxWidth, OutputTypeRange.Width)); 8988 8989 // Bail out if the subexpr's range is as wide as the cast type. 8990 if (SubRange.Width >= OutputTypeRange.Width) 8991 return OutputTypeRange; 8992 8993 // Otherwise, we take the smaller width, and we're non-negative if 8994 // either the output type or the subexpr is. 8995 return IntRange(SubRange.Width, 8996 SubRange.NonNegative || OutputTypeRange.NonNegative); 8997 } 8998 8999 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9000 // If we can fold the condition, just take that operand. 9001 bool CondResult; 9002 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9003 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9004 : CO->getFalseExpr(), 9005 MaxWidth); 9006 9007 // Otherwise, conservatively merge. 9008 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9009 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9010 return IntRange::join(L, R); 9011 } 9012 9013 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9014 switch (BO->getOpcode()) { 9015 case BO_Cmp: 9016 llvm_unreachable("builtin <=> should have class type"); 9017 9018 // Boolean-valued operations are single-bit and positive. 9019 case BO_LAnd: 9020 case BO_LOr: 9021 case BO_LT: 9022 case BO_GT: 9023 case BO_LE: 9024 case BO_GE: 9025 case BO_EQ: 9026 case BO_NE: 9027 return IntRange::forBoolType(); 9028 9029 // The type of the assignments is the type of the LHS, so the RHS 9030 // is not necessarily the same type. 9031 case BO_MulAssign: 9032 case BO_DivAssign: 9033 case BO_RemAssign: 9034 case BO_AddAssign: 9035 case BO_SubAssign: 9036 case BO_XorAssign: 9037 case BO_OrAssign: 9038 // TODO: bitfields? 9039 return IntRange::forValueOfType(C, GetExprType(E)); 9040 9041 // Simple assignments just pass through the RHS, which will have 9042 // been coerced to the LHS type. 9043 case BO_Assign: 9044 // TODO: bitfields? 9045 return GetExprRange(C, BO->getRHS(), MaxWidth); 9046 9047 // Operations with opaque sources are black-listed. 9048 case BO_PtrMemD: 9049 case BO_PtrMemI: 9050 return IntRange::forValueOfType(C, GetExprType(E)); 9051 9052 // Bitwise-and uses the *infinum* of the two source ranges. 9053 case BO_And: 9054 case BO_AndAssign: 9055 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9056 GetExprRange(C, BO->getRHS(), MaxWidth)); 9057 9058 // Left shift gets black-listed based on a judgement call. 9059 case BO_Shl: 9060 // ...except that we want to treat '1 << (blah)' as logically 9061 // positive. It's an important idiom. 9062 if (IntegerLiteral *I 9063 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9064 if (I->getValue() == 1) { 9065 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9066 return IntRange(R.Width, /*NonNegative*/ true); 9067 } 9068 } 9069 LLVM_FALLTHROUGH; 9070 9071 case BO_ShlAssign: 9072 return IntRange::forValueOfType(C, GetExprType(E)); 9073 9074 // Right shift by a constant can narrow its left argument. 9075 case BO_Shr: 9076 case BO_ShrAssign: { 9077 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9078 9079 // If the shift amount is a positive constant, drop the width by 9080 // that much. 9081 llvm::APSInt shift; 9082 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9083 shift.isNonNegative()) { 9084 unsigned zext = shift.getZExtValue(); 9085 if (zext >= L.Width) 9086 L.Width = (L.NonNegative ? 0 : 1); 9087 else 9088 L.Width -= zext; 9089 } 9090 9091 return L; 9092 } 9093 9094 // Comma acts as its right operand. 9095 case BO_Comma: 9096 return GetExprRange(C, BO->getRHS(), MaxWidth); 9097 9098 // Black-list pointer subtractions. 9099 case BO_Sub: 9100 if (BO->getLHS()->getType()->isPointerType()) 9101 return IntRange::forValueOfType(C, GetExprType(E)); 9102 break; 9103 9104 // The width of a division result is mostly determined by the size 9105 // of the LHS. 9106 case BO_Div: { 9107 // Don't 'pre-truncate' the operands. 9108 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9109 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9110 9111 // If the divisor is constant, use that. 9112 llvm::APSInt divisor; 9113 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9114 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9115 if (log2 >= L.Width) 9116 L.Width = (L.NonNegative ? 0 : 1); 9117 else 9118 L.Width = std::min(L.Width - log2, MaxWidth); 9119 return L; 9120 } 9121 9122 // Otherwise, just use the LHS's width. 9123 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9124 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9125 } 9126 9127 // The result of a remainder can't be larger than the result of 9128 // either side. 9129 case BO_Rem: { 9130 // Don't 'pre-truncate' the operands. 9131 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9132 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9133 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9134 9135 IntRange meet = IntRange::meet(L, R); 9136 meet.Width = std::min(meet.Width, MaxWidth); 9137 return meet; 9138 } 9139 9140 // The default behavior is okay for these. 9141 case BO_Mul: 9142 case BO_Add: 9143 case BO_Xor: 9144 case BO_Or: 9145 break; 9146 } 9147 9148 // The default case is to treat the operation as if it were closed 9149 // on the narrowest type that encompasses both operands. 9150 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9151 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9152 return IntRange::join(L, R); 9153 } 9154 9155 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9156 switch (UO->getOpcode()) { 9157 // Boolean-valued operations are white-listed. 9158 case UO_LNot: 9159 return IntRange::forBoolType(); 9160 9161 // Operations with opaque sources are black-listed. 9162 case UO_Deref: 9163 case UO_AddrOf: // should be impossible 9164 return IntRange::forValueOfType(C, GetExprType(E)); 9165 9166 default: 9167 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9168 } 9169 } 9170 9171 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9172 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9173 9174 if (const auto *BitField = E->getSourceBitField()) 9175 return IntRange(BitField->getBitWidthValue(C), 9176 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9177 9178 return IntRange::forValueOfType(C, GetExprType(E)); 9179 } 9180 9181 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9182 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9183 } 9184 9185 /// Checks whether the given value, which currently has the given 9186 /// source semantics, has the same value when coerced through the 9187 /// target semantics. 9188 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9189 const llvm::fltSemantics &Src, 9190 const llvm::fltSemantics &Tgt) { 9191 llvm::APFloat truncated = value; 9192 9193 bool ignored; 9194 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9195 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9196 9197 return truncated.bitwiseIsEqual(value); 9198 } 9199 9200 /// Checks whether the given value, which currently has the given 9201 /// source semantics, has the same value when coerced through the 9202 /// target semantics. 9203 /// 9204 /// The value might be a vector of floats (or a complex number). 9205 static bool IsSameFloatAfterCast(const APValue &value, 9206 const llvm::fltSemantics &Src, 9207 const llvm::fltSemantics &Tgt) { 9208 if (value.isFloat()) 9209 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9210 9211 if (value.isVector()) { 9212 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9213 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9214 return false; 9215 return true; 9216 } 9217 9218 assert(value.isComplexFloat()); 9219 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9220 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9221 } 9222 9223 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9224 9225 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9226 // Suppress cases where we are comparing against an enum constant. 9227 if (const DeclRefExpr *DR = 9228 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9229 if (isa<EnumConstantDecl>(DR->getDecl())) 9230 return true; 9231 9232 // Suppress cases where the '0' value is expanded from a macro. 9233 if (E->getLocStart().isMacroID()) 9234 return true; 9235 9236 return false; 9237 } 9238 9239 static bool isKnownToHaveUnsignedValue(Expr *E) { 9240 return E->getType()->isIntegerType() && 9241 (!E->getType()->isSignedIntegerType() || 9242 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9243 } 9244 9245 namespace { 9246 /// The promoted range of values of a type. In general this has the 9247 /// following structure: 9248 /// 9249 /// |-----------| . . . |-----------| 9250 /// ^ ^ ^ ^ 9251 /// Min HoleMin HoleMax Max 9252 /// 9253 /// ... where there is only a hole if a signed type is promoted to unsigned 9254 /// (in which case Min and Max are the smallest and largest representable 9255 /// values). 9256 struct PromotedRange { 9257 // Min, or HoleMax if there is a hole. 9258 llvm::APSInt PromotedMin; 9259 // Max, or HoleMin if there is a hole. 9260 llvm::APSInt PromotedMax; 9261 9262 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9263 if (R.Width == 0) 9264 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9265 else if (R.Width >= BitWidth && !Unsigned) { 9266 // Promotion made the type *narrower*. This happens when promoting 9267 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9268 // Treat all values of 'signed int' as being in range for now. 9269 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9270 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9271 } else { 9272 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9273 .extOrTrunc(BitWidth); 9274 PromotedMin.setIsUnsigned(Unsigned); 9275 9276 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9277 .extOrTrunc(BitWidth); 9278 PromotedMax.setIsUnsigned(Unsigned); 9279 } 9280 } 9281 9282 // Determine whether this range is contiguous (has no hole). 9283 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9284 9285 // Where a constant value is within the range. 9286 enum ComparisonResult { 9287 LT = 0x1, 9288 LE = 0x2, 9289 GT = 0x4, 9290 GE = 0x8, 9291 EQ = 0x10, 9292 NE = 0x20, 9293 InRangeFlag = 0x40, 9294 9295 Less = LE | LT | NE, 9296 Min = LE | InRangeFlag, 9297 InRange = InRangeFlag, 9298 Max = GE | InRangeFlag, 9299 Greater = GE | GT | NE, 9300 9301 OnlyValue = LE | GE | EQ | InRangeFlag, 9302 InHole = NE 9303 }; 9304 9305 ComparisonResult compare(const llvm::APSInt &Value) const { 9306 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9307 Value.isUnsigned() == PromotedMin.isUnsigned()); 9308 if (!isContiguous()) { 9309 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9310 if (Value.isMinValue()) return Min; 9311 if (Value.isMaxValue()) return Max; 9312 if (Value >= PromotedMin) return InRange; 9313 if (Value <= PromotedMax) return InRange; 9314 return InHole; 9315 } 9316 9317 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9318 case -1: return Less; 9319 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9320 case 1: 9321 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9322 case -1: return InRange; 9323 case 0: return Max; 9324 case 1: return Greater; 9325 } 9326 } 9327 9328 llvm_unreachable("impossible compare result"); 9329 } 9330 9331 static llvm::Optional<StringRef> 9332 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9333 if (Op == BO_Cmp) { 9334 ComparisonResult LTFlag = LT, GTFlag = GT; 9335 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9336 9337 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9338 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9339 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9340 return llvm::None; 9341 } 9342 9343 ComparisonResult TrueFlag, FalseFlag; 9344 if (Op == BO_EQ) { 9345 TrueFlag = EQ; 9346 FalseFlag = NE; 9347 } else if (Op == BO_NE) { 9348 TrueFlag = NE; 9349 FalseFlag = EQ; 9350 } else { 9351 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9352 TrueFlag = LT; 9353 FalseFlag = GE; 9354 } else { 9355 TrueFlag = GT; 9356 FalseFlag = LE; 9357 } 9358 if (Op == BO_GE || Op == BO_LE) 9359 std::swap(TrueFlag, FalseFlag); 9360 } 9361 if (R & TrueFlag) 9362 return StringRef("true"); 9363 if (R & FalseFlag) 9364 return StringRef("false"); 9365 return llvm::None; 9366 } 9367 }; 9368 } 9369 9370 static bool HasEnumType(Expr *E) { 9371 // Strip off implicit integral promotions. 9372 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9373 if (ICE->getCastKind() != CK_IntegralCast && 9374 ICE->getCastKind() != CK_NoOp) 9375 break; 9376 E = ICE->getSubExpr(); 9377 } 9378 9379 return E->getType()->isEnumeralType(); 9380 } 9381 9382 static int classifyConstantValue(Expr *Constant) { 9383 // The values of this enumeration are used in the diagnostics 9384 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9385 enum ConstantValueKind { 9386 Miscellaneous = 0, 9387 LiteralTrue, 9388 LiteralFalse 9389 }; 9390 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9391 return BL->getValue() ? ConstantValueKind::LiteralTrue 9392 : ConstantValueKind::LiteralFalse; 9393 return ConstantValueKind::Miscellaneous; 9394 } 9395 9396 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9397 Expr *Constant, Expr *Other, 9398 const llvm::APSInt &Value, 9399 bool RhsConstant) { 9400 if (S.inTemplateInstantiation()) 9401 return false; 9402 9403 Expr *OriginalOther = Other; 9404 9405 Constant = Constant->IgnoreParenImpCasts(); 9406 Other = Other->IgnoreParenImpCasts(); 9407 9408 // Suppress warnings on tautological comparisons between values of the same 9409 // enumeration type. There are only two ways we could warn on this: 9410 // - If the constant is outside the range of representable values of 9411 // the enumeration. In such a case, we should warn about the cast 9412 // to enumeration type, not about the comparison. 9413 // - If the constant is the maximum / minimum in-range value. For an 9414 // enumeratin type, such comparisons can be meaningful and useful. 9415 if (Constant->getType()->isEnumeralType() && 9416 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9417 return false; 9418 9419 // TODO: Investigate using GetExprRange() to get tighter bounds 9420 // on the bit ranges. 9421 QualType OtherT = Other->getType(); 9422 if (const auto *AT = OtherT->getAs<AtomicType>()) 9423 OtherT = AT->getValueType(); 9424 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9425 9426 // Whether we're treating Other as being a bool because of the form of 9427 // expression despite it having another type (typically 'int' in C). 9428 bool OtherIsBooleanDespiteType = 9429 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9430 if (OtherIsBooleanDespiteType) 9431 OtherRange = IntRange::forBoolType(); 9432 9433 // Determine the promoted range of the other type and see if a comparison of 9434 // the constant against that range is tautological. 9435 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9436 Value.isUnsigned()); 9437 auto Cmp = OtherPromotedRange.compare(Value); 9438 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9439 if (!Result) 9440 return false; 9441 9442 // Suppress the diagnostic for an in-range comparison if the constant comes 9443 // from a macro or enumerator. We don't want to diagnose 9444 // 9445 // some_long_value <= INT_MAX 9446 // 9447 // when sizeof(int) == sizeof(long). 9448 bool InRange = Cmp & PromotedRange::InRangeFlag; 9449 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 9450 return false; 9451 9452 // If this is a comparison to an enum constant, include that 9453 // constant in the diagnostic. 9454 const EnumConstantDecl *ED = nullptr; 9455 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 9456 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 9457 9458 // Should be enough for uint128 (39 decimal digits) 9459 SmallString<64> PrettySourceValue; 9460 llvm::raw_svector_ostream OS(PrettySourceValue); 9461 if (ED) 9462 OS << '\'' << *ED << "' (" << Value << ")"; 9463 else 9464 OS << Value; 9465 9466 // FIXME: We use a somewhat different formatting for the in-range cases and 9467 // cases involving boolean values for historical reasons. We should pick a 9468 // consistent way of presenting these diagnostics. 9469 if (!InRange || Other->isKnownToHaveBooleanValue()) { 9470 S.DiagRuntimeBehavior( 9471 E->getOperatorLoc(), E, 9472 S.PDiag(!InRange ? diag::warn_out_of_range_compare 9473 : diag::warn_tautological_bool_compare) 9474 << OS.str() << classifyConstantValue(Constant) 9475 << OtherT << OtherIsBooleanDespiteType << *Result 9476 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 9477 } else { 9478 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 9479 ? (HasEnumType(OriginalOther) 9480 ? diag::warn_unsigned_enum_always_true_comparison 9481 : diag::warn_unsigned_always_true_comparison) 9482 : diag::warn_tautological_constant_compare; 9483 9484 S.Diag(E->getOperatorLoc(), Diag) 9485 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 9486 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 9487 } 9488 9489 return true; 9490 } 9491 9492 /// Analyze the operands of the given comparison. Implements the 9493 /// fallback case from AnalyzeComparison. 9494 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 9495 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9496 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9497 } 9498 9499 /// Implements -Wsign-compare. 9500 /// 9501 /// \param E the binary operator to check for warnings 9502 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 9503 // The type the comparison is being performed in. 9504 QualType T = E->getLHS()->getType(); 9505 9506 // Only analyze comparison operators where both sides have been converted to 9507 // the same type. 9508 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 9509 return AnalyzeImpConvsInComparison(S, E); 9510 9511 // Don't analyze value-dependent comparisons directly. 9512 if (E->isValueDependent()) 9513 return AnalyzeImpConvsInComparison(S, E); 9514 9515 Expr *LHS = E->getLHS(); 9516 Expr *RHS = E->getRHS(); 9517 9518 if (T->isIntegralType(S.Context)) { 9519 llvm::APSInt RHSValue; 9520 llvm::APSInt LHSValue; 9521 9522 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 9523 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 9524 9525 // We don't care about expressions whose result is a constant. 9526 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 9527 return AnalyzeImpConvsInComparison(S, E); 9528 9529 // We only care about expressions where just one side is literal 9530 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 9531 // Is the constant on the RHS or LHS? 9532 const bool RhsConstant = IsRHSIntegralLiteral; 9533 Expr *Const = RhsConstant ? RHS : LHS; 9534 Expr *Other = RhsConstant ? LHS : RHS; 9535 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 9536 9537 // Check whether an integer constant comparison results in a value 9538 // of 'true' or 'false'. 9539 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 9540 return AnalyzeImpConvsInComparison(S, E); 9541 } 9542 } 9543 9544 if (!T->hasUnsignedIntegerRepresentation()) { 9545 // We don't do anything special if this isn't an unsigned integral 9546 // comparison: we're only interested in integral comparisons, and 9547 // signed comparisons only happen in cases we don't care to warn about. 9548 return AnalyzeImpConvsInComparison(S, E); 9549 } 9550 9551 LHS = LHS->IgnoreParenImpCasts(); 9552 RHS = RHS->IgnoreParenImpCasts(); 9553 9554 if (!S.getLangOpts().CPlusPlus) { 9555 // Avoid warning about comparison of integers with different signs when 9556 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 9557 // the type of `E`. 9558 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 9559 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9560 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 9561 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9562 } 9563 9564 // Check to see if one of the (unmodified) operands is of different 9565 // signedness. 9566 Expr *signedOperand, *unsignedOperand; 9567 if (LHS->getType()->hasSignedIntegerRepresentation()) { 9568 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 9569 "unsigned comparison between two signed integer expressions?"); 9570 signedOperand = LHS; 9571 unsignedOperand = RHS; 9572 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 9573 signedOperand = RHS; 9574 unsignedOperand = LHS; 9575 } else { 9576 return AnalyzeImpConvsInComparison(S, E); 9577 } 9578 9579 // Otherwise, calculate the effective range of the signed operand. 9580 IntRange signedRange = GetExprRange(S.Context, signedOperand); 9581 9582 // Go ahead and analyze implicit conversions in the operands. Note 9583 // that we skip the implicit conversions on both sides. 9584 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 9585 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 9586 9587 // If the signed range is non-negative, -Wsign-compare won't fire. 9588 if (signedRange.NonNegative) 9589 return; 9590 9591 // For (in)equality comparisons, if the unsigned operand is a 9592 // constant which cannot collide with a overflowed signed operand, 9593 // then reinterpreting the signed operand as unsigned will not 9594 // change the result of the comparison. 9595 if (E->isEqualityOp()) { 9596 unsigned comparisonWidth = S.Context.getIntWidth(T); 9597 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 9598 9599 // We should never be unable to prove that the unsigned operand is 9600 // non-negative. 9601 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 9602 9603 if (unsignedRange.Width < comparisonWidth) 9604 return; 9605 } 9606 9607 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9608 S.PDiag(diag::warn_mixed_sign_comparison) 9609 << LHS->getType() << RHS->getType() 9610 << LHS->getSourceRange() << RHS->getSourceRange()); 9611 } 9612 9613 /// Analyzes an attempt to assign the given value to a bitfield. 9614 /// 9615 /// Returns true if there was something fishy about the attempt. 9616 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9617 SourceLocation InitLoc) { 9618 assert(Bitfield->isBitField()); 9619 if (Bitfield->isInvalidDecl()) 9620 return false; 9621 9622 // White-list bool bitfields. 9623 QualType BitfieldType = Bitfield->getType(); 9624 if (BitfieldType->isBooleanType()) 9625 return false; 9626 9627 if (BitfieldType->isEnumeralType()) { 9628 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9629 // If the underlying enum type was not explicitly specified as an unsigned 9630 // type and the enum contain only positive values, MSVC++ will cause an 9631 // inconsistency by storing this as a signed type. 9632 if (S.getLangOpts().CPlusPlus11 && 9633 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9634 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9635 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9636 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9637 << BitfieldEnumDecl->getNameAsString(); 9638 } 9639 } 9640 9641 if (Bitfield->getType()->isBooleanType()) 9642 return false; 9643 9644 // Ignore value- or type-dependent expressions. 9645 if (Bitfield->getBitWidth()->isValueDependent() || 9646 Bitfield->getBitWidth()->isTypeDependent() || 9647 Init->isValueDependent() || 9648 Init->isTypeDependent()) 9649 return false; 9650 9651 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9652 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9653 9654 llvm::APSInt Value; 9655 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9656 Expr::SE_AllowSideEffects)) { 9657 // The RHS is not constant. If the RHS has an enum type, make sure the 9658 // bitfield is wide enough to hold all the values of the enum without 9659 // truncation. 9660 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9661 EnumDecl *ED = EnumTy->getDecl(); 9662 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9663 9664 // Enum types are implicitly signed on Windows, so check if there are any 9665 // negative enumerators to see if the enum was intended to be signed or 9666 // not. 9667 bool SignedEnum = ED->getNumNegativeBits() > 0; 9668 9669 // Check for surprising sign changes when assigning enum values to a 9670 // bitfield of different signedness. If the bitfield is signed and we 9671 // have exactly the right number of bits to store this unsigned enum, 9672 // suggest changing the enum to an unsigned type. This typically happens 9673 // on Windows where unfixed enums always use an underlying type of 'int'. 9674 unsigned DiagID = 0; 9675 if (SignedEnum && !SignedBitfield) { 9676 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9677 } else if (SignedBitfield && !SignedEnum && 9678 ED->getNumPositiveBits() == FieldWidth) { 9679 DiagID = diag::warn_signed_bitfield_enum_conversion; 9680 } 9681 9682 if (DiagID) { 9683 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9684 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9685 SourceRange TypeRange = 9686 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9687 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9688 << SignedEnum << TypeRange; 9689 } 9690 9691 // Compute the required bitwidth. If the enum has negative values, we need 9692 // one more bit than the normal number of positive bits to represent the 9693 // sign bit. 9694 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9695 ED->getNumNegativeBits()) 9696 : ED->getNumPositiveBits(); 9697 9698 // Check the bitwidth. 9699 if (BitsNeeded > FieldWidth) { 9700 Expr *WidthExpr = Bitfield->getBitWidth(); 9701 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9702 << Bitfield << ED; 9703 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9704 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9705 } 9706 } 9707 9708 return false; 9709 } 9710 9711 unsigned OriginalWidth = Value.getBitWidth(); 9712 9713 if (!Value.isSigned() || Value.isNegative()) 9714 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9715 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9716 OriginalWidth = Value.getMinSignedBits(); 9717 9718 if (OriginalWidth <= FieldWidth) 9719 return false; 9720 9721 // Compute the value which the bitfield will contain. 9722 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9723 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9724 9725 // Check whether the stored value is equal to the original value. 9726 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9727 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9728 return false; 9729 9730 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9731 // therefore don't strictly fit into a signed bitfield of width 1. 9732 if (FieldWidth == 1 && Value == 1) 9733 return false; 9734 9735 std::string PrettyValue = Value.toString(10); 9736 std::string PrettyTrunc = TruncatedValue.toString(10); 9737 9738 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9739 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9740 << Init->getSourceRange(); 9741 9742 return true; 9743 } 9744 9745 /// Analyze the given simple or compound assignment for warning-worthy 9746 /// operations. 9747 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9748 // Just recurse on the LHS. 9749 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9750 9751 // We want to recurse on the RHS as normal unless we're assigning to 9752 // a bitfield. 9753 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9754 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9755 E->getOperatorLoc())) { 9756 // Recurse, ignoring any implicit conversions on the RHS. 9757 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9758 E->getOperatorLoc()); 9759 } 9760 } 9761 9762 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9763 } 9764 9765 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9766 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9767 SourceLocation CContext, unsigned diag, 9768 bool pruneControlFlow = false) { 9769 if (pruneControlFlow) { 9770 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9771 S.PDiag(diag) 9772 << SourceType << T << E->getSourceRange() 9773 << SourceRange(CContext)); 9774 return; 9775 } 9776 S.Diag(E->getExprLoc(), diag) 9777 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9778 } 9779 9780 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9781 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 9782 SourceLocation CContext, 9783 unsigned diag, bool pruneControlFlow = false) { 9784 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9785 } 9786 9787 /// Analyze the given compound assignment for the possible losing of 9788 /// floating-point precision. 9789 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 9790 assert(isa<CompoundAssignOperator>(E) && 9791 "Must be compound assignment operation"); 9792 // Recurse on the LHS and RHS in here 9793 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9794 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9795 9796 // Now check the outermost expression 9797 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 9798 const auto *RBT = cast<CompoundAssignOperator>(E) 9799 ->getComputationResultType() 9800 ->getAs<BuiltinType>(); 9801 9802 // If both source and target are floating points. 9803 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint()) 9804 // Builtin FP kinds are ordered by increasing FP rank. 9805 if (ResultBT->getKind() < RBT->getKind()) 9806 // We don't want to warn for system macro. 9807 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 9808 // warn about dropping FP rank. 9809 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), 9810 E->getOperatorLoc(), 9811 diag::warn_impcast_float_result_precision); 9812 } 9813 9814 /// Diagnose an implicit cast from a floating point value to an integer value. 9815 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9816 SourceLocation CContext) { 9817 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9818 const bool PruneWarnings = S.inTemplateInstantiation(); 9819 9820 Expr *InnerE = E->IgnoreParenImpCasts(); 9821 // We also want to warn on, e.g., "int i = -1.234" 9822 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9823 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9824 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9825 9826 const bool IsLiteral = 9827 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9828 9829 llvm::APFloat Value(0.0); 9830 bool IsConstant = 9831 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9832 if (!IsConstant) { 9833 return DiagnoseImpCast(S, E, T, CContext, 9834 diag::warn_impcast_float_integer, PruneWarnings); 9835 } 9836 9837 bool isExact = false; 9838 9839 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9840 T->hasUnsignedIntegerRepresentation()); 9841 llvm::APFloat::opStatus Result = Value.convertToInteger( 9842 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 9843 9844 if (Result == llvm::APFloat::opOK && isExact) { 9845 if (IsLiteral) return; 9846 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9847 PruneWarnings); 9848 } 9849 9850 // Conversion of a floating-point value to a non-bool integer where the 9851 // integral part cannot be represented by the integer type is undefined. 9852 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 9853 return DiagnoseImpCast( 9854 S, E, T, CContext, 9855 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 9856 : diag::warn_impcast_float_to_integer_out_of_range, 9857 PruneWarnings); 9858 9859 unsigned DiagID = 0; 9860 if (IsLiteral) { 9861 // Warn on floating point literal to integer. 9862 DiagID = diag::warn_impcast_literal_float_to_integer; 9863 } else if (IntegerValue == 0) { 9864 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9865 return DiagnoseImpCast(S, E, T, CContext, 9866 diag::warn_impcast_float_integer, PruneWarnings); 9867 } 9868 // Warn on non-zero to zero conversion. 9869 DiagID = diag::warn_impcast_float_to_integer_zero; 9870 } else { 9871 if (IntegerValue.isUnsigned()) { 9872 if (!IntegerValue.isMaxValue()) { 9873 return DiagnoseImpCast(S, E, T, CContext, 9874 diag::warn_impcast_float_integer, PruneWarnings); 9875 } 9876 } else { // IntegerValue.isSigned() 9877 if (!IntegerValue.isMaxSignedValue() && 9878 !IntegerValue.isMinSignedValue()) { 9879 return DiagnoseImpCast(S, E, T, CContext, 9880 diag::warn_impcast_float_integer, PruneWarnings); 9881 } 9882 } 9883 // Warn on evaluatable floating point expression to integer conversion. 9884 DiagID = diag::warn_impcast_float_to_integer; 9885 } 9886 9887 // FIXME: Force the precision of the source value down so we don't print 9888 // digits which are usually useless (we don't really care here if we 9889 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9890 // would automatically print the shortest representation, but it's a bit 9891 // tricky to implement. 9892 SmallString<16> PrettySourceValue; 9893 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9894 precision = (precision * 59 + 195) / 196; 9895 Value.toString(PrettySourceValue, precision); 9896 9897 SmallString<16> PrettyTargetValue; 9898 if (IsBool) 9899 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9900 else 9901 IntegerValue.toString(PrettyTargetValue); 9902 9903 if (PruneWarnings) { 9904 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9905 S.PDiag(DiagID) 9906 << E->getType() << T.getUnqualifiedType() 9907 << PrettySourceValue << PrettyTargetValue 9908 << E->getSourceRange() << SourceRange(CContext)); 9909 } else { 9910 S.Diag(E->getExprLoc(), DiagID) 9911 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9912 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9913 } 9914 } 9915 9916 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 9917 IntRange Range) { 9918 if (!Range.Width) return "0"; 9919 9920 llvm::APSInt ValueInRange = Value; 9921 ValueInRange.setIsSigned(!Range.NonNegative); 9922 ValueInRange = ValueInRange.trunc(Range.Width); 9923 return ValueInRange.toString(10); 9924 } 9925 9926 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9927 if (!isa<ImplicitCastExpr>(Ex)) 9928 return false; 9929 9930 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9931 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9932 const Type *Source = 9933 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9934 if (Target->isDependentType()) 9935 return false; 9936 9937 const BuiltinType *FloatCandidateBT = 9938 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9939 const Type *BoolCandidateType = ToBool ? Target : Source; 9940 9941 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9942 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9943 } 9944 9945 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9946 SourceLocation CC) { 9947 unsigned NumArgs = TheCall->getNumArgs(); 9948 for (unsigned i = 0; i < NumArgs; ++i) { 9949 Expr *CurrA = TheCall->getArg(i); 9950 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9951 continue; 9952 9953 bool IsSwapped = ((i > 0) && 9954 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9955 IsSwapped |= ((i < (NumArgs - 1)) && 9956 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9957 if (IsSwapped) { 9958 // Warn on this floating-point to bool conversion. 9959 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9960 CurrA->getType(), CC, 9961 diag::warn_impcast_floating_point_to_bool); 9962 } 9963 } 9964 } 9965 9966 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 9967 SourceLocation CC) { 9968 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9969 E->getExprLoc())) 9970 return; 9971 9972 // Don't warn on functions which have return type nullptr_t. 9973 if (isa<CallExpr>(E)) 9974 return; 9975 9976 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 9977 const Expr::NullPointerConstantKind NullKind = 9978 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 9979 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 9980 return; 9981 9982 // Return if target type is a safe conversion. 9983 if (T->isAnyPointerType() || T->isBlockPointerType() || 9984 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 9985 return; 9986 9987 SourceLocation Loc = E->getSourceRange().getBegin(); 9988 9989 // Venture through the macro stacks to get to the source of macro arguments. 9990 // The new location is a better location than the complete location that was 9991 // passed in. 9992 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 9993 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 9994 9995 // __null is usually wrapped in a macro. Go up a macro if that is the case. 9996 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 9997 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 9998 Loc, S.SourceMgr, S.getLangOpts()); 9999 if (MacroName == "NULL") 10000 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10001 } 10002 10003 // Only warn if the null and context location are in the same macro expansion. 10004 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10005 return; 10006 10007 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10008 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10009 << FixItHint::CreateReplacement(Loc, 10010 S.getFixItZeroLiteralForType(T, Loc)); 10011 } 10012 10013 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10014 ObjCArrayLiteral *ArrayLiteral); 10015 10016 static void 10017 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10018 ObjCDictionaryLiteral *DictionaryLiteral); 10019 10020 /// Check a single element within a collection literal against the 10021 /// target element type. 10022 static void checkObjCCollectionLiteralElement(Sema &S, 10023 QualType TargetElementType, 10024 Expr *Element, 10025 unsigned ElementKind) { 10026 // Skip a bitcast to 'id' or qualified 'id'. 10027 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10028 if (ICE->getCastKind() == CK_BitCast && 10029 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10030 Element = ICE->getSubExpr(); 10031 } 10032 10033 QualType ElementType = Element->getType(); 10034 ExprResult ElementResult(Element); 10035 if (ElementType->getAs<ObjCObjectPointerType>() && 10036 S.CheckSingleAssignmentConstraints(TargetElementType, 10037 ElementResult, 10038 false, false) 10039 != Sema::Compatible) { 10040 S.Diag(Element->getLocStart(), 10041 diag::warn_objc_collection_literal_element) 10042 << ElementType << ElementKind << TargetElementType 10043 << Element->getSourceRange(); 10044 } 10045 10046 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10047 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10048 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10049 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10050 } 10051 10052 /// Check an Objective-C array literal being converted to the given 10053 /// target type. 10054 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10055 ObjCArrayLiteral *ArrayLiteral) { 10056 if (!S.NSArrayDecl) 10057 return; 10058 10059 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10060 if (!TargetObjCPtr) 10061 return; 10062 10063 if (TargetObjCPtr->isUnspecialized() || 10064 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10065 != S.NSArrayDecl->getCanonicalDecl()) 10066 return; 10067 10068 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10069 if (TypeArgs.size() != 1) 10070 return; 10071 10072 QualType TargetElementType = TypeArgs[0]; 10073 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10074 checkObjCCollectionLiteralElement(S, TargetElementType, 10075 ArrayLiteral->getElement(I), 10076 0); 10077 } 10078 } 10079 10080 /// Check an Objective-C dictionary literal being converted to the given 10081 /// target type. 10082 static void 10083 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10084 ObjCDictionaryLiteral *DictionaryLiteral) { 10085 if (!S.NSDictionaryDecl) 10086 return; 10087 10088 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10089 if (!TargetObjCPtr) 10090 return; 10091 10092 if (TargetObjCPtr->isUnspecialized() || 10093 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10094 != S.NSDictionaryDecl->getCanonicalDecl()) 10095 return; 10096 10097 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10098 if (TypeArgs.size() != 2) 10099 return; 10100 10101 QualType TargetKeyType = TypeArgs[0]; 10102 QualType TargetObjectType = TypeArgs[1]; 10103 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10104 auto Element = DictionaryLiteral->getKeyValueElement(I); 10105 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10106 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10107 } 10108 } 10109 10110 // Helper function to filter out cases for constant width constant conversion. 10111 // Don't warn on char array initialization or for non-decimal values. 10112 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10113 SourceLocation CC) { 10114 // If initializing from a constant, and the constant starts with '0', 10115 // then it is a binary, octal, or hexadecimal. Allow these constants 10116 // to fill all the bits, even if there is a sign change. 10117 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10118 const char FirstLiteralCharacter = 10119 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 10120 if (FirstLiteralCharacter == '0') 10121 return false; 10122 } 10123 10124 // If the CC location points to a '{', and the type is char, then assume 10125 // assume it is an array initialization. 10126 if (CC.isValid() && T->isCharType()) { 10127 const char FirstContextCharacter = 10128 S.getSourceManager().getCharacterData(CC)[0]; 10129 if (FirstContextCharacter == '{') 10130 return false; 10131 } 10132 10133 return true; 10134 } 10135 10136 static void 10137 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10138 bool *ICContext = nullptr) { 10139 if (E->isTypeDependent() || E->isValueDependent()) return; 10140 10141 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10142 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10143 if (Source == Target) return; 10144 if (Target->isDependentType()) return; 10145 10146 // If the conversion context location is invalid don't complain. We also 10147 // don't want to emit a warning if the issue occurs from the expansion of 10148 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10149 // delay this check as long as possible. Once we detect we are in that 10150 // scenario, we just return. 10151 if (CC.isInvalid()) 10152 return; 10153 10154 // Diagnose implicit casts to bool. 10155 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10156 if (isa<StringLiteral>(E)) 10157 // Warn on string literal to bool. Checks for string literals in logical 10158 // and expressions, for instance, assert(0 && "error here"), are 10159 // prevented by a check in AnalyzeImplicitConversions(). 10160 return DiagnoseImpCast(S, E, T, CC, 10161 diag::warn_impcast_string_literal_to_bool); 10162 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10163 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10164 // This covers the literal expressions that evaluate to Objective-C 10165 // objects. 10166 return DiagnoseImpCast(S, E, T, CC, 10167 diag::warn_impcast_objective_c_literal_to_bool); 10168 } 10169 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10170 // Warn on pointer to bool conversion that is always true. 10171 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10172 SourceRange(CC)); 10173 } 10174 } 10175 10176 // Check implicit casts from Objective-C collection literals to specialized 10177 // collection types, e.g., NSArray<NSString *> *. 10178 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10179 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10180 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10181 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10182 10183 // Strip vector types. 10184 if (isa<VectorType>(Source)) { 10185 if (!isa<VectorType>(Target)) { 10186 if (S.SourceMgr.isInSystemMacro(CC)) 10187 return; 10188 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10189 } 10190 10191 // If the vector cast is cast between two vectors of the same size, it is 10192 // a bitcast, not a conversion. 10193 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10194 return; 10195 10196 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10197 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10198 } 10199 if (auto VecTy = dyn_cast<VectorType>(Target)) 10200 Target = VecTy->getElementType().getTypePtr(); 10201 10202 // Strip complex types. 10203 if (isa<ComplexType>(Source)) { 10204 if (!isa<ComplexType>(Target)) { 10205 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10206 return; 10207 10208 return DiagnoseImpCast(S, E, T, CC, 10209 S.getLangOpts().CPlusPlus 10210 ? diag::err_impcast_complex_scalar 10211 : diag::warn_impcast_complex_scalar); 10212 } 10213 10214 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10215 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10216 } 10217 10218 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10219 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10220 10221 // If the source is floating point... 10222 if (SourceBT && SourceBT->isFloatingPoint()) { 10223 // ...and the target is floating point... 10224 if (TargetBT && TargetBT->isFloatingPoint()) { 10225 // ...then warn if we're dropping FP rank. 10226 10227 // Builtin FP kinds are ordered by increasing FP rank. 10228 if (SourceBT->getKind() > TargetBT->getKind()) { 10229 // Don't warn about float constants that are precisely 10230 // representable in the target type. 10231 Expr::EvalResult result; 10232 if (E->EvaluateAsRValue(result, S.Context)) { 10233 // Value might be a float, a float vector, or a float complex. 10234 if (IsSameFloatAfterCast(result.Val, 10235 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10236 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10237 return; 10238 } 10239 10240 if (S.SourceMgr.isInSystemMacro(CC)) 10241 return; 10242 10243 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10244 } 10245 // ... or possibly if we're increasing rank, too 10246 else if (TargetBT->getKind() > SourceBT->getKind()) { 10247 if (S.SourceMgr.isInSystemMacro(CC)) 10248 return; 10249 10250 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10251 } 10252 return; 10253 } 10254 10255 // If the target is integral, always warn. 10256 if (TargetBT && TargetBT->isInteger()) { 10257 if (S.SourceMgr.isInSystemMacro(CC)) 10258 return; 10259 10260 DiagnoseFloatingImpCast(S, E, T, CC); 10261 } 10262 10263 // Detect the case where a call result is converted from floating-point to 10264 // to bool, and the final argument to the call is converted from bool, to 10265 // discover this typo: 10266 // 10267 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10268 // 10269 // FIXME: This is an incredibly special case; is there some more general 10270 // way to detect this class of misplaced-parentheses bug? 10271 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10272 // Check last argument of function call to see if it is an 10273 // implicit cast from a type matching the type the result 10274 // is being cast to. 10275 CallExpr *CEx = cast<CallExpr>(E); 10276 if (unsigned NumArgs = CEx->getNumArgs()) { 10277 Expr *LastA = CEx->getArg(NumArgs - 1); 10278 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10279 if (isa<ImplicitCastExpr>(LastA) && 10280 InnerE->getType()->isBooleanType()) { 10281 // Warn on this floating-point to bool conversion 10282 DiagnoseImpCast(S, E, T, CC, 10283 diag::warn_impcast_floating_point_to_bool); 10284 } 10285 } 10286 } 10287 return; 10288 } 10289 10290 DiagnoseNullConversion(S, E, T, CC); 10291 10292 S.DiscardMisalignedMemberAddress(Target, E); 10293 10294 if (!Source->isIntegerType() || !Target->isIntegerType()) 10295 return; 10296 10297 // TODO: remove this early return once the false positives for constant->bool 10298 // in templates, macros, etc, are reduced or removed. 10299 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10300 return; 10301 10302 IntRange SourceRange = GetExprRange(S.Context, E); 10303 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10304 10305 if (SourceRange.Width > TargetRange.Width) { 10306 // If the source is a constant, use a default-on diagnostic. 10307 // TODO: this should happen for bitfield stores, too. 10308 llvm::APSInt Value(32); 10309 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10310 if (S.SourceMgr.isInSystemMacro(CC)) 10311 return; 10312 10313 std::string PrettySourceValue = Value.toString(10); 10314 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10315 10316 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10317 S.PDiag(diag::warn_impcast_integer_precision_constant) 10318 << PrettySourceValue << PrettyTargetValue 10319 << E->getType() << T << E->getSourceRange() 10320 << clang::SourceRange(CC)); 10321 return; 10322 } 10323 10324 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10325 if (S.SourceMgr.isInSystemMacro(CC)) 10326 return; 10327 10328 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10329 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10330 /* pruneControlFlow */ true); 10331 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10332 } 10333 10334 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10335 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10336 // Warn when doing a signed to signed conversion, warn if the positive 10337 // source value is exactly the width of the target type, which will 10338 // cause a negative value to be stored. 10339 10340 llvm::APSInt Value; 10341 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10342 !S.SourceMgr.isInSystemMacro(CC)) { 10343 if (isSameWidthConstantConversion(S, E, T, CC)) { 10344 std::string PrettySourceValue = Value.toString(10); 10345 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10346 10347 S.DiagRuntimeBehavior( 10348 E->getExprLoc(), E, 10349 S.PDiag(diag::warn_impcast_integer_precision_constant) 10350 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10351 << E->getSourceRange() << clang::SourceRange(CC)); 10352 return; 10353 } 10354 } 10355 10356 // Fall through for non-constants to give a sign conversion warning. 10357 } 10358 10359 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10360 (!TargetRange.NonNegative && SourceRange.NonNegative && 10361 SourceRange.Width == TargetRange.Width)) { 10362 if (S.SourceMgr.isInSystemMacro(CC)) 10363 return; 10364 10365 unsigned DiagID = diag::warn_impcast_integer_sign; 10366 10367 // Traditionally, gcc has warned about this under -Wsign-compare. 10368 // We also want to warn about it in -Wconversion. 10369 // So if -Wconversion is off, use a completely identical diagnostic 10370 // in the sign-compare group. 10371 // The conditional-checking code will 10372 if (ICContext) { 10373 DiagID = diag::warn_impcast_integer_sign_conditional; 10374 *ICContext = true; 10375 } 10376 10377 return DiagnoseImpCast(S, E, T, CC, DiagID); 10378 } 10379 10380 // Diagnose conversions between different enumeration types. 10381 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10382 // type, to give us better diagnostics. 10383 QualType SourceType = E->getType(); 10384 if (!S.getLangOpts().CPlusPlus) { 10385 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10386 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10387 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10388 SourceType = S.Context.getTypeDeclType(Enum); 10389 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10390 } 10391 } 10392 10393 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10394 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10395 if (SourceEnum->getDecl()->hasNameForLinkage() && 10396 TargetEnum->getDecl()->hasNameForLinkage() && 10397 SourceEnum != TargetEnum) { 10398 if (S.SourceMgr.isInSystemMacro(CC)) 10399 return; 10400 10401 return DiagnoseImpCast(S, E, SourceType, T, CC, 10402 diag::warn_impcast_different_enum_types); 10403 } 10404 } 10405 10406 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10407 SourceLocation CC, QualType T); 10408 10409 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10410 SourceLocation CC, bool &ICContext) { 10411 E = E->IgnoreParenImpCasts(); 10412 10413 if (isa<ConditionalOperator>(E)) 10414 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10415 10416 AnalyzeImplicitConversions(S, E, CC); 10417 if (E->getType() != T) 10418 return CheckImplicitConversion(S, E, T, CC, &ICContext); 10419 } 10420 10421 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10422 SourceLocation CC, QualType T) { 10423 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 10424 10425 bool Suspicious = false; 10426 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 10427 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 10428 10429 // If -Wconversion would have warned about either of the candidates 10430 // for a signedness conversion to the context type... 10431 if (!Suspicious) return; 10432 10433 // ...but it's currently ignored... 10434 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 10435 return; 10436 10437 // ...then check whether it would have warned about either of the 10438 // candidates for a signedness conversion to the condition type. 10439 if (E->getType() == T) return; 10440 10441 Suspicious = false; 10442 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 10443 E->getType(), CC, &Suspicious); 10444 if (!Suspicious) 10445 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 10446 E->getType(), CC, &Suspicious); 10447 } 10448 10449 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10450 /// Input argument E is a logical expression. 10451 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 10452 if (S.getLangOpts().Bool) 10453 return; 10454 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 10455 } 10456 10457 /// AnalyzeImplicitConversions - Find and report any interesting 10458 /// implicit conversions in the given expression. There are a couple 10459 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 10460 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 10461 SourceLocation CC) { 10462 QualType T = OrigE->getType(); 10463 Expr *E = OrigE->IgnoreParenImpCasts(); 10464 10465 if (E->isTypeDependent() || E->isValueDependent()) 10466 return; 10467 10468 // For conditional operators, we analyze the arguments as if they 10469 // were being fed directly into the output. 10470 if (isa<ConditionalOperator>(E)) { 10471 ConditionalOperator *CO = cast<ConditionalOperator>(E); 10472 CheckConditionalOperator(S, CO, CC, T); 10473 return; 10474 } 10475 10476 // Check implicit argument conversions for function calls. 10477 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 10478 CheckImplicitArgumentConversions(S, Call, CC); 10479 10480 // Go ahead and check any implicit conversions we might have skipped. 10481 // The non-canonical typecheck is just an optimization; 10482 // CheckImplicitConversion will filter out dead implicit conversions. 10483 if (E->getType() != T) 10484 CheckImplicitConversion(S, E, T, CC); 10485 10486 // Now continue drilling into this expression. 10487 10488 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 10489 // The bound subexpressions in a PseudoObjectExpr are not reachable 10490 // as transitive children. 10491 // FIXME: Use a more uniform representation for this. 10492 for (auto *SE : POE->semantics()) 10493 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 10494 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 10495 } 10496 10497 // Skip past explicit casts. 10498 if (isa<ExplicitCastExpr>(E)) { 10499 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 10500 return AnalyzeImplicitConversions(S, E, CC); 10501 } 10502 10503 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10504 // Do a somewhat different check with comparison operators. 10505 if (BO->isComparisonOp()) 10506 return AnalyzeComparison(S, BO); 10507 10508 // And with simple assignments. 10509 if (BO->getOpcode() == BO_Assign) 10510 return AnalyzeAssignment(S, BO); 10511 // And with compound assignments. 10512 if (BO->isAssignmentOp()) 10513 return AnalyzeCompoundAssignment(S, BO); 10514 } 10515 10516 // These break the otherwise-useful invariant below. Fortunately, 10517 // we don't really need to recurse into them, because any internal 10518 // expressions should have been analyzed already when they were 10519 // built into statements. 10520 if (isa<StmtExpr>(E)) return; 10521 10522 // Don't descend into unevaluated contexts. 10523 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 10524 10525 // Now just recurse over the expression's children. 10526 CC = E->getExprLoc(); 10527 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 10528 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 10529 for (Stmt *SubStmt : E->children()) { 10530 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 10531 if (!ChildExpr) 10532 continue; 10533 10534 if (IsLogicalAndOperator && 10535 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 10536 // Ignore checking string literals that are in logical and operators. 10537 // This is a common pattern for asserts. 10538 continue; 10539 AnalyzeImplicitConversions(S, ChildExpr, CC); 10540 } 10541 10542 if (BO && BO->isLogicalOp()) { 10543 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 10544 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10545 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10546 10547 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 10548 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10549 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10550 } 10551 10552 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 10553 if (U->getOpcode() == UO_LNot) 10554 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 10555 } 10556 10557 /// Diagnose integer type and any valid implicit conversion to it. 10558 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 10559 // Taking into account implicit conversions, 10560 // allow any integer. 10561 if (!E->getType()->isIntegerType()) { 10562 S.Diag(E->getLocStart(), 10563 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 10564 return true; 10565 } 10566 // Potentially emit standard warnings for implicit conversions if enabled 10567 // using -Wconversion. 10568 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 10569 return false; 10570 } 10571 10572 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 10573 // Returns true when emitting a warning about taking the address of a reference. 10574 static bool CheckForReference(Sema &SemaRef, const Expr *E, 10575 const PartialDiagnostic &PD) { 10576 E = E->IgnoreParenImpCasts(); 10577 10578 const FunctionDecl *FD = nullptr; 10579 10580 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10581 if (!DRE->getDecl()->getType()->isReferenceType()) 10582 return false; 10583 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10584 if (!M->getMemberDecl()->getType()->isReferenceType()) 10585 return false; 10586 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 10587 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 10588 return false; 10589 FD = Call->getDirectCallee(); 10590 } else { 10591 return false; 10592 } 10593 10594 SemaRef.Diag(E->getExprLoc(), PD); 10595 10596 // If possible, point to location of function. 10597 if (FD) { 10598 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 10599 } 10600 10601 return true; 10602 } 10603 10604 // Returns true if the SourceLocation is expanded from any macro body. 10605 // Returns false if the SourceLocation is invalid, is from not in a macro 10606 // expansion, or is from expanded from a top-level macro argument. 10607 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 10608 if (Loc.isInvalid()) 10609 return false; 10610 10611 while (Loc.isMacroID()) { 10612 if (SM.isMacroBodyExpansion(Loc)) 10613 return true; 10614 Loc = SM.getImmediateMacroCallerLoc(Loc); 10615 } 10616 10617 return false; 10618 } 10619 10620 /// Diagnose pointers that are always non-null. 10621 /// \param E the expression containing the pointer 10622 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 10623 /// compared to a null pointer 10624 /// \param IsEqual True when the comparison is equal to a null pointer 10625 /// \param Range Extra SourceRange to highlight in the diagnostic 10626 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 10627 Expr::NullPointerConstantKind NullKind, 10628 bool IsEqual, SourceRange Range) { 10629 if (!E) 10630 return; 10631 10632 // Don't warn inside macros. 10633 if (E->getExprLoc().isMacroID()) { 10634 const SourceManager &SM = getSourceManager(); 10635 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 10636 IsInAnyMacroBody(SM, Range.getBegin())) 10637 return; 10638 } 10639 E = E->IgnoreImpCasts(); 10640 10641 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 10642 10643 if (isa<CXXThisExpr>(E)) { 10644 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 10645 : diag::warn_this_bool_conversion; 10646 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 10647 return; 10648 } 10649 10650 bool IsAddressOf = false; 10651 10652 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10653 if (UO->getOpcode() != UO_AddrOf) 10654 return; 10655 IsAddressOf = true; 10656 E = UO->getSubExpr(); 10657 } 10658 10659 if (IsAddressOf) { 10660 unsigned DiagID = IsCompare 10661 ? diag::warn_address_of_reference_null_compare 10662 : diag::warn_address_of_reference_bool_conversion; 10663 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10664 << IsEqual; 10665 if (CheckForReference(*this, E, PD)) { 10666 return; 10667 } 10668 } 10669 10670 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10671 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10672 std::string Str; 10673 llvm::raw_string_ostream S(Str); 10674 E->printPretty(S, nullptr, getPrintingPolicy()); 10675 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10676 : diag::warn_cast_nonnull_to_bool; 10677 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10678 << E->getSourceRange() << Range << IsEqual; 10679 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10680 }; 10681 10682 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10683 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10684 if (auto *Callee = Call->getDirectCallee()) { 10685 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10686 ComplainAboutNonnullParamOrCall(A); 10687 return; 10688 } 10689 } 10690 } 10691 10692 // Expect to find a single Decl. Skip anything more complicated. 10693 ValueDecl *D = nullptr; 10694 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10695 D = R->getDecl(); 10696 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10697 D = M->getMemberDecl(); 10698 } 10699 10700 // Weak Decls can be null. 10701 if (!D || D->isWeak()) 10702 return; 10703 10704 // Check for parameter decl with nonnull attribute 10705 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10706 if (getCurFunction() && 10707 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10708 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10709 ComplainAboutNonnullParamOrCall(A); 10710 return; 10711 } 10712 10713 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10714 auto ParamIter = llvm::find(FD->parameters(), PV); 10715 assert(ParamIter != FD->param_end()); 10716 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10717 10718 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10719 if (!NonNull->args_size()) { 10720 ComplainAboutNonnullParamOrCall(NonNull); 10721 return; 10722 } 10723 10724 for (const ParamIdx &ArgNo : NonNull->args()) { 10725 if (ArgNo.getASTIndex() == ParamNo) { 10726 ComplainAboutNonnullParamOrCall(NonNull); 10727 return; 10728 } 10729 } 10730 } 10731 } 10732 } 10733 } 10734 10735 QualType T = D->getType(); 10736 const bool IsArray = T->isArrayType(); 10737 const bool IsFunction = T->isFunctionType(); 10738 10739 // Address of function is used to silence the function warning. 10740 if (IsAddressOf && IsFunction) { 10741 return; 10742 } 10743 10744 // Found nothing. 10745 if (!IsAddressOf && !IsFunction && !IsArray) 10746 return; 10747 10748 // Pretty print the expression for the diagnostic. 10749 std::string Str; 10750 llvm::raw_string_ostream S(Str); 10751 E->printPretty(S, nullptr, getPrintingPolicy()); 10752 10753 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10754 : diag::warn_impcast_pointer_to_bool; 10755 enum { 10756 AddressOf, 10757 FunctionPointer, 10758 ArrayPointer 10759 } DiagType; 10760 if (IsAddressOf) 10761 DiagType = AddressOf; 10762 else if (IsFunction) 10763 DiagType = FunctionPointer; 10764 else if (IsArray) 10765 DiagType = ArrayPointer; 10766 else 10767 llvm_unreachable("Could not determine diagnostic."); 10768 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10769 << Range << IsEqual; 10770 10771 if (!IsFunction) 10772 return; 10773 10774 // Suggest '&' to silence the function warning. 10775 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10776 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10777 10778 // Check to see if '()' fixit should be emitted. 10779 QualType ReturnType; 10780 UnresolvedSet<4> NonTemplateOverloads; 10781 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10782 if (ReturnType.isNull()) 10783 return; 10784 10785 if (IsCompare) { 10786 // There are two cases here. If there is null constant, the only suggest 10787 // for a pointer return type. If the null is 0, then suggest if the return 10788 // type is a pointer or an integer type. 10789 if (!ReturnType->isPointerType()) { 10790 if (NullKind == Expr::NPCK_ZeroExpression || 10791 NullKind == Expr::NPCK_ZeroLiteral) { 10792 if (!ReturnType->isIntegerType()) 10793 return; 10794 } else { 10795 return; 10796 } 10797 } 10798 } else { // !IsCompare 10799 // For function to bool, only suggest if the function pointer has bool 10800 // return type. 10801 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10802 return; 10803 } 10804 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10805 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10806 } 10807 10808 /// Diagnoses "dangerous" implicit conversions within the given 10809 /// expression (which is a full expression). Implements -Wconversion 10810 /// and -Wsign-compare. 10811 /// 10812 /// \param CC the "context" location of the implicit conversion, i.e. 10813 /// the most location of the syntactic entity requiring the implicit 10814 /// conversion 10815 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10816 // Don't diagnose in unevaluated contexts. 10817 if (isUnevaluatedContext()) 10818 return; 10819 10820 // Don't diagnose for value- or type-dependent expressions. 10821 if (E->isTypeDependent() || E->isValueDependent()) 10822 return; 10823 10824 // Check for array bounds violations in cases where the check isn't triggered 10825 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10826 // ArraySubscriptExpr is on the RHS of a variable initialization. 10827 CheckArrayAccess(E); 10828 10829 // This is not the right CC for (e.g.) a variable initialization. 10830 AnalyzeImplicitConversions(*this, E, CC); 10831 } 10832 10833 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10834 /// Input argument E is a logical expression. 10835 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10836 ::CheckBoolLikeConversion(*this, E, CC); 10837 } 10838 10839 /// Diagnose when expression is an integer constant expression and its evaluation 10840 /// results in integer overflow 10841 void Sema::CheckForIntOverflow (Expr *E) { 10842 // Use a work list to deal with nested struct initializers. 10843 SmallVector<Expr *, 2> Exprs(1, E); 10844 10845 do { 10846 Expr *OriginalE = Exprs.pop_back_val(); 10847 Expr *E = OriginalE->IgnoreParenCasts(); 10848 10849 if (isa<BinaryOperator>(E)) { 10850 E->EvaluateForOverflow(Context); 10851 continue; 10852 } 10853 10854 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 10855 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10856 else if (isa<ObjCBoxedExpr>(OriginalE)) 10857 E->EvaluateForOverflow(Context); 10858 else if (auto Call = dyn_cast<CallExpr>(E)) 10859 Exprs.append(Call->arg_begin(), Call->arg_end()); 10860 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 10861 Exprs.append(Message->arg_begin(), Message->arg_end()); 10862 } while (!Exprs.empty()); 10863 } 10864 10865 namespace { 10866 10867 /// Visitor for expressions which looks for unsequenced operations on the 10868 /// same object. 10869 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10870 using Base = EvaluatedExprVisitor<SequenceChecker>; 10871 10872 /// A tree of sequenced regions within an expression. Two regions are 10873 /// unsequenced if one is an ancestor or a descendent of the other. When we 10874 /// finish processing an expression with sequencing, such as a comma 10875 /// expression, we fold its tree nodes into its parent, since they are 10876 /// unsequenced with respect to nodes we will visit later. 10877 class SequenceTree { 10878 struct Value { 10879 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10880 unsigned Parent : 31; 10881 unsigned Merged : 1; 10882 }; 10883 SmallVector<Value, 8> Values; 10884 10885 public: 10886 /// A region within an expression which may be sequenced with respect 10887 /// to some other region. 10888 class Seq { 10889 friend class SequenceTree; 10890 10891 unsigned Index = 0; 10892 10893 explicit Seq(unsigned N) : Index(N) {} 10894 10895 public: 10896 Seq() = default; 10897 }; 10898 10899 SequenceTree() { Values.push_back(Value(0)); } 10900 Seq root() const { return Seq(0); } 10901 10902 /// Create a new sequence of operations, which is an unsequenced 10903 /// subset of \p Parent. This sequence of operations is sequenced with 10904 /// respect to other children of \p Parent. 10905 Seq allocate(Seq Parent) { 10906 Values.push_back(Value(Parent.Index)); 10907 return Seq(Values.size() - 1); 10908 } 10909 10910 /// Merge a sequence of operations into its parent. 10911 void merge(Seq S) { 10912 Values[S.Index].Merged = true; 10913 } 10914 10915 /// Determine whether two operations are unsequenced. This operation 10916 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10917 /// should have been merged into its parent as appropriate. 10918 bool isUnsequenced(Seq Cur, Seq Old) { 10919 unsigned C = representative(Cur.Index); 10920 unsigned Target = representative(Old.Index); 10921 while (C >= Target) { 10922 if (C == Target) 10923 return true; 10924 C = Values[C].Parent; 10925 } 10926 return false; 10927 } 10928 10929 private: 10930 /// Pick a representative for a sequence. 10931 unsigned representative(unsigned K) { 10932 if (Values[K].Merged) 10933 // Perform path compression as we go. 10934 return Values[K].Parent = representative(Values[K].Parent); 10935 return K; 10936 } 10937 }; 10938 10939 /// An object for which we can track unsequenced uses. 10940 using Object = NamedDecl *; 10941 10942 /// Different flavors of object usage which we track. We only track the 10943 /// least-sequenced usage of each kind. 10944 enum UsageKind { 10945 /// A read of an object. Multiple unsequenced reads are OK. 10946 UK_Use, 10947 10948 /// A modification of an object which is sequenced before the value 10949 /// computation of the expression, such as ++n in C++. 10950 UK_ModAsValue, 10951 10952 /// A modification of an object which is not sequenced before the value 10953 /// computation of the expression, such as n++. 10954 UK_ModAsSideEffect, 10955 10956 UK_Count = UK_ModAsSideEffect + 1 10957 }; 10958 10959 struct Usage { 10960 Expr *Use = nullptr; 10961 SequenceTree::Seq Seq; 10962 10963 Usage() = default; 10964 }; 10965 10966 struct UsageInfo { 10967 Usage Uses[UK_Count]; 10968 10969 /// Have we issued a diagnostic for this variable already? 10970 bool Diagnosed = false; 10971 10972 UsageInfo() = default; 10973 }; 10974 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 10975 10976 Sema &SemaRef; 10977 10978 /// Sequenced regions within the expression. 10979 SequenceTree Tree; 10980 10981 /// Declaration modifications and references which we have seen. 10982 UsageInfoMap UsageMap; 10983 10984 /// The region we are currently within. 10985 SequenceTree::Seq Region; 10986 10987 /// Filled in with declarations which were modified as a side-effect 10988 /// (that is, post-increment operations). 10989 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 10990 10991 /// Expressions to check later. We defer checking these to reduce 10992 /// stack usage. 10993 SmallVectorImpl<Expr *> &WorkList; 10994 10995 /// RAII object wrapping the visitation of a sequenced subexpression of an 10996 /// expression. At the end of this process, the side-effects of the evaluation 10997 /// become sequenced with respect to the value computation of the result, so 10998 /// we downgrade any UK_ModAsSideEffect within the evaluation to 10999 /// UK_ModAsValue. 11000 struct SequencedSubexpression { 11001 SequencedSubexpression(SequenceChecker &Self) 11002 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11003 Self.ModAsSideEffect = &ModAsSideEffect; 11004 } 11005 11006 ~SequencedSubexpression() { 11007 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11008 UsageInfo &U = Self.UsageMap[M.first]; 11009 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11010 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11011 SideEffectUsage = M.second; 11012 } 11013 Self.ModAsSideEffect = OldModAsSideEffect; 11014 } 11015 11016 SequenceChecker &Self; 11017 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11018 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11019 }; 11020 11021 /// RAII object wrapping the visitation of a subexpression which we might 11022 /// choose to evaluate as a constant. If any subexpression is evaluated and 11023 /// found to be non-constant, this allows us to suppress the evaluation of 11024 /// the outer expression. 11025 class EvaluationTracker { 11026 public: 11027 EvaluationTracker(SequenceChecker &Self) 11028 : Self(Self), Prev(Self.EvalTracker) { 11029 Self.EvalTracker = this; 11030 } 11031 11032 ~EvaluationTracker() { 11033 Self.EvalTracker = Prev; 11034 if (Prev) 11035 Prev->EvalOK &= EvalOK; 11036 } 11037 11038 bool evaluate(const Expr *E, bool &Result) { 11039 if (!EvalOK || E->isValueDependent()) 11040 return false; 11041 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11042 return EvalOK; 11043 } 11044 11045 private: 11046 SequenceChecker &Self; 11047 EvaluationTracker *Prev; 11048 bool EvalOK = true; 11049 } *EvalTracker = nullptr; 11050 11051 /// Find the object which is produced by the specified expression, 11052 /// if any. 11053 Object getObject(Expr *E, bool Mod) const { 11054 E = E->IgnoreParenCasts(); 11055 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11056 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11057 return getObject(UO->getSubExpr(), Mod); 11058 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11059 if (BO->getOpcode() == BO_Comma) 11060 return getObject(BO->getRHS(), Mod); 11061 if (Mod && BO->isAssignmentOp()) 11062 return getObject(BO->getLHS(), Mod); 11063 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11064 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11065 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11066 return ME->getMemberDecl(); 11067 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11068 // FIXME: If this is a reference, map through to its value. 11069 return DRE->getDecl(); 11070 return nullptr; 11071 } 11072 11073 /// Note that an object was modified or used by an expression. 11074 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11075 Usage &U = UI.Uses[UK]; 11076 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11077 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11078 ModAsSideEffect->push_back(std::make_pair(O, U)); 11079 U.Use = Ref; 11080 U.Seq = Region; 11081 } 11082 } 11083 11084 /// Check whether a modification or use conflicts with a prior usage. 11085 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11086 bool IsModMod) { 11087 if (UI.Diagnosed) 11088 return; 11089 11090 const Usage &U = UI.Uses[OtherKind]; 11091 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11092 return; 11093 11094 Expr *Mod = U.Use; 11095 Expr *ModOrUse = Ref; 11096 if (OtherKind == UK_Use) 11097 std::swap(Mod, ModOrUse); 11098 11099 SemaRef.Diag(Mod->getExprLoc(), 11100 IsModMod ? diag::warn_unsequenced_mod_mod 11101 : diag::warn_unsequenced_mod_use) 11102 << O << SourceRange(ModOrUse->getExprLoc()); 11103 UI.Diagnosed = true; 11104 } 11105 11106 void notePreUse(Object O, Expr *Use) { 11107 UsageInfo &U = UsageMap[O]; 11108 // Uses conflict with other modifications. 11109 checkUsage(O, U, Use, UK_ModAsValue, false); 11110 } 11111 11112 void notePostUse(Object O, Expr *Use) { 11113 UsageInfo &U = UsageMap[O]; 11114 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11115 addUsage(U, O, Use, UK_Use); 11116 } 11117 11118 void notePreMod(Object O, Expr *Mod) { 11119 UsageInfo &U = UsageMap[O]; 11120 // Modifications conflict with other modifications and with uses. 11121 checkUsage(O, U, Mod, UK_ModAsValue, true); 11122 checkUsage(O, U, Mod, UK_Use, false); 11123 } 11124 11125 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11126 UsageInfo &U = UsageMap[O]; 11127 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11128 addUsage(U, O, Use, UK); 11129 } 11130 11131 public: 11132 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11133 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11134 Visit(E); 11135 } 11136 11137 void VisitStmt(Stmt *S) { 11138 // Skip all statements which aren't expressions for now. 11139 } 11140 11141 void VisitExpr(Expr *E) { 11142 // By default, just recurse to evaluated subexpressions. 11143 Base::VisitStmt(E); 11144 } 11145 11146 void VisitCastExpr(CastExpr *E) { 11147 Object O = Object(); 11148 if (E->getCastKind() == CK_LValueToRValue) 11149 O = getObject(E->getSubExpr(), false); 11150 11151 if (O) 11152 notePreUse(O, E); 11153 VisitExpr(E); 11154 if (O) 11155 notePostUse(O, E); 11156 } 11157 11158 void VisitBinComma(BinaryOperator *BO) { 11159 // C++11 [expr.comma]p1: 11160 // Every value computation and side effect associated with the left 11161 // expression is sequenced before every value computation and side 11162 // effect associated with the right expression. 11163 SequenceTree::Seq LHS = Tree.allocate(Region); 11164 SequenceTree::Seq RHS = Tree.allocate(Region); 11165 SequenceTree::Seq OldRegion = Region; 11166 11167 { 11168 SequencedSubexpression SeqLHS(*this); 11169 Region = LHS; 11170 Visit(BO->getLHS()); 11171 } 11172 11173 Region = RHS; 11174 Visit(BO->getRHS()); 11175 11176 Region = OldRegion; 11177 11178 // Forget that LHS and RHS are sequenced. They are both unsequenced 11179 // with respect to other stuff. 11180 Tree.merge(LHS); 11181 Tree.merge(RHS); 11182 } 11183 11184 void VisitBinAssign(BinaryOperator *BO) { 11185 // The modification is sequenced after the value computation of the LHS 11186 // and RHS, so check it before inspecting the operands and update the 11187 // map afterwards. 11188 Object O = getObject(BO->getLHS(), true); 11189 if (!O) 11190 return VisitExpr(BO); 11191 11192 notePreMod(O, BO); 11193 11194 // C++11 [expr.ass]p7: 11195 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11196 // only once. 11197 // 11198 // Therefore, for a compound assignment operator, O is considered used 11199 // everywhere except within the evaluation of E1 itself. 11200 if (isa<CompoundAssignOperator>(BO)) 11201 notePreUse(O, BO); 11202 11203 Visit(BO->getLHS()); 11204 11205 if (isa<CompoundAssignOperator>(BO)) 11206 notePostUse(O, BO); 11207 11208 Visit(BO->getRHS()); 11209 11210 // C++11 [expr.ass]p1: 11211 // the assignment is sequenced [...] before the value computation of the 11212 // assignment expression. 11213 // C11 6.5.16/3 has no such rule. 11214 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11215 : UK_ModAsSideEffect); 11216 } 11217 11218 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11219 VisitBinAssign(CAO); 11220 } 11221 11222 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11223 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11224 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11225 Object O = getObject(UO->getSubExpr(), true); 11226 if (!O) 11227 return VisitExpr(UO); 11228 11229 notePreMod(O, UO); 11230 Visit(UO->getSubExpr()); 11231 // C++11 [expr.pre.incr]p1: 11232 // the expression ++x is equivalent to x+=1 11233 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11234 : UK_ModAsSideEffect); 11235 } 11236 11237 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11238 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11239 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11240 Object O = getObject(UO->getSubExpr(), true); 11241 if (!O) 11242 return VisitExpr(UO); 11243 11244 notePreMod(O, UO); 11245 Visit(UO->getSubExpr()); 11246 notePostMod(O, UO, UK_ModAsSideEffect); 11247 } 11248 11249 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11250 void VisitBinLOr(BinaryOperator *BO) { 11251 // The side-effects of the LHS of an '&&' are sequenced before the 11252 // value computation of the RHS, and hence before the value computation 11253 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11254 // as if they were unconditionally sequenced. 11255 EvaluationTracker Eval(*this); 11256 { 11257 SequencedSubexpression Sequenced(*this); 11258 Visit(BO->getLHS()); 11259 } 11260 11261 bool Result; 11262 if (Eval.evaluate(BO->getLHS(), Result)) { 11263 if (!Result) 11264 Visit(BO->getRHS()); 11265 } else { 11266 // Check for unsequenced operations in the RHS, treating it as an 11267 // entirely separate evaluation. 11268 // 11269 // FIXME: If there are operations in the RHS which are unsequenced 11270 // with respect to operations outside the RHS, and those operations 11271 // are unconditionally evaluated, diagnose them. 11272 WorkList.push_back(BO->getRHS()); 11273 } 11274 } 11275 void VisitBinLAnd(BinaryOperator *BO) { 11276 EvaluationTracker Eval(*this); 11277 { 11278 SequencedSubexpression Sequenced(*this); 11279 Visit(BO->getLHS()); 11280 } 11281 11282 bool Result; 11283 if (Eval.evaluate(BO->getLHS(), Result)) { 11284 if (Result) 11285 Visit(BO->getRHS()); 11286 } else { 11287 WorkList.push_back(BO->getRHS()); 11288 } 11289 } 11290 11291 // Only visit the condition, unless we can be sure which subexpression will 11292 // be chosen. 11293 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11294 EvaluationTracker Eval(*this); 11295 { 11296 SequencedSubexpression Sequenced(*this); 11297 Visit(CO->getCond()); 11298 } 11299 11300 bool Result; 11301 if (Eval.evaluate(CO->getCond(), Result)) 11302 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11303 else { 11304 WorkList.push_back(CO->getTrueExpr()); 11305 WorkList.push_back(CO->getFalseExpr()); 11306 } 11307 } 11308 11309 void VisitCallExpr(CallExpr *CE) { 11310 // C++11 [intro.execution]p15: 11311 // When calling a function [...], every value computation and side effect 11312 // associated with any argument expression, or with the postfix expression 11313 // designating the called function, is sequenced before execution of every 11314 // expression or statement in the body of the function [and thus before 11315 // the value computation of its result]. 11316 SequencedSubexpression Sequenced(*this); 11317 Base::VisitCallExpr(CE); 11318 11319 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11320 } 11321 11322 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11323 // This is a call, so all subexpressions are sequenced before the result. 11324 SequencedSubexpression Sequenced(*this); 11325 11326 if (!CCE->isListInitialization()) 11327 return VisitExpr(CCE); 11328 11329 // In C++11, list initializations are sequenced. 11330 SmallVector<SequenceTree::Seq, 32> Elts; 11331 SequenceTree::Seq Parent = Region; 11332 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11333 E = CCE->arg_end(); 11334 I != E; ++I) { 11335 Region = Tree.allocate(Parent); 11336 Elts.push_back(Region); 11337 Visit(*I); 11338 } 11339 11340 // Forget that the initializers are sequenced. 11341 Region = Parent; 11342 for (unsigned I = 0; I < Elts.size(); ++I) 11343 Tree.merge(Elts[I]); 11344 } 11345 11346 void VisitInitListExpr(InitListExpr *ILE) { 11347 if (!SemaRef.getLangOpts().CPlusPlus11) 11348 return VisitExpr(ILE); 11349 11350 // In C++11, list initializations are sequenced. 11351 SmallVector<SequenceTree::Seq, 32> Elts; 11352 SequenceTree::Seq Parent = Region; 11353 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11354 Expr *E = ILE->getInit(I); 11355 if (!E) continue; 11356 Region = Tree.allocate(Parent); 11357 Elts.push_back(Region); 11358 Visit(E); 11359 } 11360 11361 // Forget that the initializers are sequenced. 11362 Region = Parent; 11363 for (unsigned I = 0; I < Elts.size(); ++I) 11364 Tree.merge(Elts[I]); 11365 } 11366 }; 11367 11368 } // namespace 11369 11370 void Sema::CheckUnsequencedOperations(Expr *E) { 11371 SmallVector<Expr *, 8> WorkList; 11372 WorkList.push_back(E); 11373 while (!WorkList.empty()) { 11374 Expr *Item = WorkList.pop_back_val(); 11375 SequenceChecker(*this, Item, WorkList); 11376 } 11377 } 11378 11379 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11380 bool IsConstexpr) { 11381 CheckImplicitConversions(E, CheckLoc); 11382 if (!E->isInstantiationDependent()) 11383 CheckUnsequencedOperations(E); 11384 if (!IsConstexpr && !E->isValueDependent()) 11385 CheckForIntOverflow(E); 11386 DiagnoseMisalignedMembers(); 11387 } 11388 11389 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11390 FieldDecl *BitField, 11391 Expr *Init) { 11392 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11393 } 11394 11395 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11396 SourceLocation Loc) { 11397 if (!PType->isVariablyModifiedType()) 11398 return; 11399 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11400 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11401 return; 11402 } 11403 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 11404 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 11405 return; 11406 } 11407 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 11408 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 11409 return; 11410 } 11411 11412 const ArrayType *AT = S.Context.getAsArrayType(PType); 11413 if (!AT) 11414 return; 11415 11416 if (AT->getSizeModifier() != ArrayType::Star) { 11417 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 11418 return; 11419 } 11420 11421 S.Diag(Loc, diag::err_array_star_in_function_definition); 11422 } 11423 11424 /// CheckParmsForFunctionDef - Check that the parameters of the given 11425 /// function are appropriate for the definition of a function. This 11426 /// takes care of any checks that cannot be performed on the 11427 /// declaration itself, e.g., that the types of each of the function 11428 /// parameters are complete. 11429 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 11430 bool CheckParameterNames) { 11431 bool HasInvalidParm = false; 11432 for (ParmVarDecl *Param : Parameters) { 11433 // C99 6.7.5.3p4: the parameters in a parameter type list in a 11434 // function declarator that is part of a function definition of 11435 // that function shall not have incomplete type. 11436 // 11437 // This is also C++ [dcl.fct]p6. 11438 if (!Param->isInvalidDecl() && 11439 RequireCompleteType(Param->getLocation(), Param->getType(), 11440 diag::err_typecheck_decl_incomplete_type)) { 11441 Param->setInvalidDecl(); 11442 HasInvalidParm = true; 11443 } 11444 11445 // C99 6.9.1p5: If the declarator includes a parameter type list, the 11446 // declaration of each parameter shall include an identifier. 11447 if (CheckParameterNames && 11448 Param->getIdentifier() == nullptr && 11449 !Param->isImplicit() && 11450 !getLangOpts().CPlusPlus) 11451 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11452 11453 // C99 6.7.5.3p12: 11454 // If the function declarator is not part of a definition of that 11455 // function, parameters may have incomplete type and may use the [*] 11456 // notation in their sequences of declarator specifiers to specify 11457 // variable length array types. 11458 QualType PType = Param->getOriginalType(); 11459 // FIXME: This diagnostic should point the '[*]' if source-location 11460 // information is added for it. 11461 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 11462 11463 // If the parameter is a c++ class type and it has to be destructed in the 11464 // callee function, declare the destructor so that it can be called by the 11465 // callee function. Do not perform any direct access check on the dtor here. 11466 if (!Param->isInvalidDecl()) { 11467 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 11468 if (!ClassDecl->isInvalidDecl() && 11469 !ClassDecl->hasIrrelevantDestructor() && 11470 !ClassDecl->isDependentContext() && 11471 ClassDecl->isParamDestroyedInCallee()) { 11472 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11473 MarkFunctionReferenced(Param->getLocation(), Destructor); 11474 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 11475 } 11476 } 11477 } 11478 11479 // Parameters with the pass_object_size attribute only need to be marked 11480 // constant at function definitions. Because we lack information about 11481 // whether we're on a declaration or definition when we're instantiating the 11482 // attribute, we need to check for constness here. 11483 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 11484 if (!Param->getType().isConstQualified()) 11485 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 11486 << Attr->getSpelling() << 1; 11487 } 11488 11489 return HasInvalidParm; 11490 } 11491 11492 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 11493 /// or MemberExpr. 11494 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 11495 ASTContext &Context) { 11496 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 11497 return Context.getDeclAlign(DRE->getDecl()); 11498 11499 if (const auto *ME = dyn_cast<MemberExpr>(E)) 11500 return Context.getDeclAlign(ME->getMemberDecl()); 11501 11502 return TypeAlign; 11503 } 11504 11505 /// CheckCastAlign - Implements -Wcast-align, which warns when a 11506 /// pointer cast increases the alignment requirements. 11507 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 11508 // This is actually a lot of work to potentially be doing on every 11509 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 11510 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 11511 return; 11512 11513 // Ignore dependent types. 11514 if (T->isDependentType() || Op->getType()->isDependentType()) 11515 return; 11516 11517 // Require that the destination be a pointer type. 11518 const PointerType *DestPtr = T->getAs<PointerType>(); 11519 if (!DestPtr) return; 11520 11521 // If the destination has alignment 1, we're done. 11522 QualType DestPointee = DestPtr->getPointeeType(); 11523 if (DestPointee->isIncompleteType()) return; 11524 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 11525 if (DestAlign.isOne()) return; 11526 11527 // Require that the source be a pointer type. 11528 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 11529 if (!SrcPtr) return; 11530 QualType SrcPointee = SrcPtr->getPointeeType(); 11531 11532 // Whitelist casts from cv void*. We already implicitly 11533 // whitelisted casts to cv void*, since they have alignment 1. 11534 // Also whitelist casts involving incomplete types, which implicitly 11535 // includes 'void'. 11536 if (SrcPointee->isIncompleteType()) return; 11537 11538 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 11539 11540 if (auto *CE = dyn_cast<CastExpr>(Op)) { 11541 if (CE->getCastKind() == CK_ArrayToPointerDecay) 11542 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 11543 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 11544 if (UO->getOpcode() == UO_AddrOf) 11545 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 11546 } 11547 11548 if (SrcAlign >= DestAlign) return; 11549 11550 Diag(TRange.getBegin(), diag::warn_cast_align) 11551 << Op->getType() << T 11552 << static_cast<unsigned>(SrcAlign.getQuantity()) 11553 << static_cast<unsigned>(DestAlign.getQuantity()) 11554 << TRange << Op->getSourceRange(); 11555 } 11556 11557 /// Check whether this array fits the idiom of a size-one tail padded 11558 /// array member of a struct. 11559 /// 11560 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 11561 /// commonly used to emulate flexible arrays in C89 code. 11562 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 11563 const NamedDecl *ND) { 11564 if (Size != 1 || !ND) return false; 11565 11566 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 11567 if (!FD) return false; 11568 11569 // Don't consider sizes resulting from macro expansions or template argument 11570 // substitution to form C89 tail-padded arrays. 11571 11572 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 11573 while (TInfo) { 11574 TypeLoc TL = TInfo->getTypeLoc(); 11575 // Look through typedefs. 11576 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 11577 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 11578 TInfo = TDL->getTypeSourceInfo(); 11579 continue; 11580 } 11581 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 11582 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 11583 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 11584 return false; 11585 } 11586 break; 11587 } 11588 11589 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 11590 if (!RD) return false; 11591 if (RD->isUnion()) return false; 11592 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11593 if (!CRD->isStandardLayout()) return false; 11594 } 11595 11596 // See if this is the last field decl in the record. 11597 const Decl *D = FD; 11598 while ((D = D->getNextDeclInContext())) 11599 if (isa<FieldDecl>(D)) 11600 return false; 11601 return true; 11602 } 11603 11604 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 11605 const ArraySubscriptExpr *ASE, 11606 bool AllowOnePastEnd, bool IndexNegated) { 11607 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 11608 if (IndexExpr->isValueDependent()) 11609 return; 11610 11611 const Type *EffectiveType = 11612 BaseExpr->getType()->getPointeeOrArrayElementType(); 11613 BaseExpr = BaseExpr->IgnoreParenCasts(); 11614 const ConstantArrayType *ArrayTy = 11615 Context.getAsConstantArrayType(BaseExpr->getType()); 11616 if (!ArrayTy) 11617 return; 11618 11619 llvm::APSInt index; 11620 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 11621 return; 11622 if (IndexNegated) 11623 index = -index; 11624 11625 const NamedDecl *ND = nullptr; 11626 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11627 ND = DRE->getDecl(); 11628 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11629 ND = ME->getMemberDecl(); 11630 11631 if (index.isUnsigned() || !index.isNegative()) { 11632 llvm::APInt size = ArrayTy->getSize(); 11633 if (!size.isStrictlyPositive()) 11634 return; 11635 11636 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 11637 if (BaseType != EffectiveType) { 11638 // Make sure we're comparing apples to apples when comparing index to size 11639 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 11640 uint64_t array_typesize = Context.getTypeSize(BaseType); 11641 // Handle ptrarith_typesize being zero, such as when casting to void* 11642 if (!ptrarith_typesize) ptrarith_typesize = 1; 11643 if (ptrarith_typesize != array_typesize) { 11644 // There's a cast to a different size type involved 11645 uint64_t ratio = array_typesize / ptrarith_typesize; 11646 // TODO: Be smarter about handling cases where array_typesize is not a 11647 // multiple of ptrarith_typesize 11648 if (ptrarith_typesize * ratio == array_typesize) 11649 size *= llvm::APInt(size.getBitWidth(), ratio); 11650 } 11651 } 11652 11653 if (size.getBitWidth() > index.getBitWidth()) 11654 index = index.zext(size.getBitWidth()); 11655 else if (size.getBitWidth() < index.getBitWidth()) 11656 size = size.zext(index.getBitWidth()); 11657 11658 // For array subscripting the index must be less than size, but for pointer 11659 // arithmetic also allow the index (offset) to be equal to size since 11660 // computing the next address after the end of the array is legal and 11661 // commonly done e.g. in C++ iterators and range-based for loops. 11662 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 11663 return; 11664 11665 // Also don't warn for arrays of size 1 which are members of some 11666 // structure. These are often used to approximate flexible arrays in C89 11667 // code. 11668 if (IsTailPaddedMemberArray(*this, size, ND)) 11669 return; 11670 11671 // Suppress the warning if the subscript expression (as identified by the 11672 // ']' location) and the index expression are both from macro expansions 11673 // within a system header. 11674 if (ASE) { 11675 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11676 ASE->getRBracketLoc()); 11677 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11678 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11679 IndexExpr->getLocStart()); 11680 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11681 return; 11682 } 11683 } 11684 11685 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11686 if (ASE) 11687 DiagID = diag::warn_array_index_exceeds_bounds; 11688 11689 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11690 PDiag(DiagID) << index.toString(10, true) 11691 << size.toString(10, true) 11692 << (unsigned)size.getLimitedValue(~0U) 11693 << IndexExpr->getSourceRange()); 11694 } else { 11695 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11696 if (!ASE) { 11697 DiagID = diag::warn_ptr_arith_precedes_bounds; 11698 if (index.isNegative()) index = -index; 11699 } 11700 11701 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11702 PDiag(DiagID) << index.toString(10, true) 11703 << IndexExpr->getSourceRange()); 11704 } 11705 11706 if (!ND) { 11707 // Try harder to find a NamedDecl to point at in the note. 11708 while (const ArraySubscriptExpr *ASE = 11709 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11710 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11711 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11712 ND = DRE->getDecl(); 11713 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11714 ND = ME->getMemberDecl(); 11715 } 11716 11717 if (ND) 11718 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11719 PDiag(diag::note_array_index_out_of_bounds) 11720 << ND->getDeclName()); 11721 } 11722 11723 void Sema::CheckArrayAccess(const Expr *expr) { 11724 int AllowOnePastEnd = 0; 11725 while (expr) { 11726 expr = expr->IgnoreParenImpCasts(); 11727 switch (expr->getStmtClass()) { 11728 case Stmt::ArraySubscriptExprClass: { 11729 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11730 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11731 AllowOnePastEnd > 0); 11732 expr = ASE->getBase(); 11733 break; 11734 } 11735 case Stmt::MemberExprClass: { 11736 expr = cast<MemberExpr>(expr)->getBase(); 11737 break; 11738 } 11739 case Stmt::OMPArraySectionExprClass: { 11740 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11741 if (ASE->getLowerBound()) 11742 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11743 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11744 return; 11745 } 11746 case Stmt::UnaryOperatorClass: { 11747 // Only unwrap the * and & unary operators 11748 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11749 expr = UO->getSubExpr(); 11750 switch (UO->getOpcode()) { 11751 case UO_AddrOf: 11752 AllowOnePastEnd++; 11753 break; 11754 case UO_Deref: 11755 AllowOnePastEnd--; 11756 break; 11757 default: 11758 return; 11759 } 11760 break; 11761 } 11762 case Stmt::ConditionalOperatorClass: { 11763 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11764 if (const Expr *lhs = cond->getLHS()) 11765 CheckArrayAccess(lhs); 11766 if (const Expr *rhs = cond->getRHS()) 11767 CheckArrayAccess(rhs); 11768 return; 11769 } 11770 case Stmt::CXXOperatorCallExprClass: { 11771 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11772 for (const auto *Arg : OCE->arguments()) 11773 CheckArrayAccess(Arg); 11774 return; 11775 } 11776 default: 11777 return; 11778 } 11779 } 11780 } 11781 11782 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11783 11784 namespace { 11785 11786 struct RetainCycleOwner { 11787 VarDecl *Variable = nullptr; 11788 SourceRange Range; 11789 SourceLocation Loc; 11790 bool Indirect = false; 11791 11792 RetainCycleOwner() = default; 11793 11794 void setLocsFrom(Expr *e) { 11795 Loc = e->getExprLoc(); 11796 Range = e->getSourceRange(); 11797 } 11798 }; 11799 11800 } // namespace 11801 11802 /// Consider whether capturing the given variable can possibly lead to 11803 /// a retain cycle. 11804 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11805 // In ARC, it's captured strongly iff the variable has __strong 11806 // lifetime. In MRR, it's captured strongly if the variable is 11807 // __block and has an appropriate type. 11808 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11809 return false; 11810 11811 owner.Variable = var; 11812 if (ref) 11813 owner.setLocsFrom(ref); 11814 return true; 11815 } 11816 11817 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11818 while (true) { 11819 e = e->IgnoreParens(); 11820 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11821 switch (cast->getCastKind()) { 11822 case CK_BitCast: 11823 case CK_LValueBitCast: 11824 case CK_LValueToRValue: 11825 case CK_ARCReclaimReturnedObject: 11826 e = cast->getSubExpr(); 11827 continue; 11828 11829 default: 11830 return false; 11831 } 11832 } 11833 11834 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11835 ObjCIvarDecl *ivar = ref->getDecl(); 11836 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11837 return false; 11838 11839 // Try to find a retain cycle in the base. 11840 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11841 return false; 11842 11843 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11844 owner.Indirect = true; 11845 return true; 11846 } 11847 11848 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11849 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11850 if (!var) return false; 11851 return considerVariable(var, ref, owner); 11852 } 11853 11854 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11855 if (member->isArrow()) return false; 11856 11857 // Don't count this as an indirect ownership. 11858 e = member->getBase(); 11859 continue; 11860 } 11861 11862 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11863 // Only pay attention to pseudo-objects on property references. 11864 ObjCPropertyRefExpr *pre 11865 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11866 ->IgnoreParens()); 11867 if (!pre) return false; 11868 if (pre->isImplicitProperty()) return false; 11869 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11870 if (!property->isRetaining() && 11871 !(property->getPropertyIvarDecl() && 11872 property->getPropertyIvarDecl()->getType() 11873 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11874 return false; 11875 11876 owner.Indirect = true; 11877 if (pre->isSuperReceiver()) { 11878 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11879 if (!owner.Variable) 11880 return false; 11881 owner.Loc = pre->getLocation(); 11882 owner.Range = pre->getSourceRange(); 11883 return true; 11884 } 11885 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11886 ->getSourceExpr()); 11887 continue; 11888 } 11889 11890 // Array ivars? 11891 11892 return false; 11893 } 11894 } 11895 11896 namespace { 11897 11898 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11899 ASTContext &Context; 11900 VarDecl *Variable; 11901 Expr *Capturer = nullptr; 11902 bool VarWillBeReased = false; 11903 11904 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11905 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11906 Context(Context), Variable(variable) {} 11907 11908 void VisitDeclRefExpr(DeclRefExpr *ref) { 11909 if (ref->getDecl() == Variable && !Capturer) 11910 Capturer = ref; 11911 } 11912 11913 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11914 if (Capturer) return; 11915 Visit(ref->getBase()); 11916 if (Capturer && ref->isFreeIvar()) 11917 Capturer = ref; 11918 } 11919 11920 void VisitBlockExpr(BlockExpr *block) { 11921 // Look inside nested blocks 11922 if (block->getBlockDecl()->capturesVariable(Variable)) 11923 Visit(block->getBlockDecl()->getBody()); 11924 } 11925 11926 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11927 if (Capturer) return; 11928 if (OVE->getSourceExpr()) 11929 Visit(OVE->getSourceExpr()); 11930 } 11931 11932 void VisitBinaryOperator(BinaryOperator *BinOp) { 11933 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11934 return; 11935 Expr *LHS = BinOp->getLHS(); 11936 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11937 if (DRE->getDecl() != Variable) 11938 return; 11939 if (Expr *RHS = BinOp->getRHS()) { 11940 RHS = RHS->IgnoreParenCasts(); 11941 llvm::APSInt Value; 11942 VarWillBeReased = 11943 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11944 } 11945 } 11946 } 11947 }; 11948 11949 } // namespace 11950 11951 /// Check whether the given argument is a block which captures a 11952 /// variable. 11953 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11954 assert(owner.Variable && owner.Loc.isValid()); 11955 11956 e = e->IgnoreParenCasts(); 11957 11958 // Look through [^{...} copy] and Block_copy(^{...}). 11959 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11960 Selector Cmd = ME->getSelector(); 11961 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11962 e = ME->getInstanceReceiver(); 11963 if (!e) 11964 return nullptr; 11965 e = e->IgnoreParenCasts(); 11966 } 11967 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11968 if (CE->getNumArgs() == 1) { 11969 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11970 if (Fn) { 11971 const IdentifierInfo *FnI = Fn->getIdentifier(); 11972 if (FnI && FnI->isStr("_Block_copy")) { 11973 e = CE->getArg(0)->IgnoreParenCasts(); 11974 } 11975 } 11976 } 11977 } 11978 11979 BlockExpr *block = dyn_cast<BlockExpr>(e); 11980 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 11981 return nullptr; 11982 11983 FindCaptureVisitor visitor(S.Context, owner.Variable); 11984 visitor.Visit(block->getBlockDecl()->getBody()); 11985 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 11986 } 11987 11988 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 11989 RetainCycleOwner &owner) { 11990 assert(capturer); 11991 assert(owner.Variable && owner.Loc.isValid()); 11992 11993 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 11994 << owner.Variable << capturer->getSourceRange(); 11995 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 11996 << owner.Indirect << owner.Range; 11997 } 11998 11999 /// Check for a keyword selector that starts with the word 'add' or 12000 /// 'set'. 12001 static bool isSetterLikeSelector(Selector sel) { 12002 if (sel.isUnarySelector()) return false; 12003 12004 StringRef str = sel.getNameForSlot(0); 12005 while (!str.empty() && str.front() == '_') str = str.substr(1); 12006 if (str.startswith("set")) 12007 str = str.substr(3); 12008 else if (str.startswith("add")) { 12009 // Specially whitelist 'addOperationWithBlock:'. 12010 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12011 return false; 12012 str = str.substr(3); 12013 } 12014 else 12015 return false; 12016 12017 if (str.empty()) return true; 12018 return !isLowercase(str.front()); 12019 } 12020 12021 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12022 ObjCMessageExpr *Message) { 12023 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12024 Message->getReceiverInterface(), 12025 NSAPI::ClassId_NSMutableArray); 12026 if (!IsMutableArray) { 12027 return None; 12028 } 12029 12030 Selector Sel = Message->getSelector(); 12031 12032 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12033 S.NSAPIObj->getNSArrayMethodKind(Sel); 12034 if (!MKOpt) { 12035 return None; 12036 } 12037 12038 NSAPI::NSArrayMethodKind MK = *MKOpt; 12039 12040 switch (MK) { 12041 case NSAPI::NSMutableArr_addObject: 12042 case NSAPI::NSMutableArr_insertObjectAtIndex: 12043 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12044 return 0; 12045 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12046 return 1; 12047 12048 default: 12049 return None; 12050 } 12051 12052 return None; 12053 } 12054 12055 static 12056 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12057 ObjCMessageExpr *Message) { 12058 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12059 Message->getReceiverInterface(), 12060 NSAPI::ClassId_NSMutableDictionary); 12061 if (!IsMutableDictionary) { 12062 return None; 12063 } 12064 12065 Selector Sel = Message->getSelector(); 12066 12067 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12068 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12069 if (!MKOpt) { 12070 return None; 12071 } 12072 12073 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12074 12075 switch (MK) { 12076 case NSAPI::NSMutableDict_setObjectForKey: 12077 case NSAPI::NSMutableDict_setValueForKey: 12078 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12079 return 0; 12080 12081 default: 12082 return None; 12083 } 12084 12085 return None; 12086 } 12087 12088 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12089 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12090 Message->getReceiverInterface(), 12091 NSAPI::ClassId_NSMutableSet); 12092 12093 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12094 Message->getReceiverInterface(), 12095 NSAPI::ClassId_NSMutableOrderedSet); 12096 if (!IsMutableSet && !IsMutableOrderedSet) { 12097 return None; 12098 } 12099 12100 Selector Sel = Message->getSelector(); 12101 12102 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12103 if (!MKOpt) { 12104 return None; 12105 } 12106 12107 NSAPI::NSSetMethodKind MK = *MKOpt; 12108 12109 switch (MK) { 12110 case NSAPI::NSMutableSet_addObject: 12111 case NSAPI::NSOrderedSet_setObjectAtIndex: 12112 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12113 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12114 return 0; 12115 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12116 return 1; 12117 } 12118 12119 return None; 12120 } 12121 12122 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12123 if (!Message->isInstanceMessage()) { 12124 return; 12125 } 12126 12127 Optional<int> ArgOpt; 12128 12129 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12130 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12131 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12132 return; 12133 } 12134 12135 int ArgIndex = *ArgOpt; 12136 12137 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12138 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12139 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12140 } 12141 12142 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12143 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12144 if (ArgRE->isObjCSelfExpr()) { 12145 Diag(Message->getSourceRange().getBegin(), 12146 diag::warn_objc_circular_container) 12147 << ArgRE->getDecl() << StringRef("'super'"); 12148 } 12149 } 12150 } else { 12151 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12152 12153 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12154 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12155 } 12156 12157 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12158 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12159 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12160 ValueDecl *Decl = ReceiverRE->getDecl(); 12161 Diag(Message->getSourceRange().getBegin(), 12162 diag::warn_objc_circular_container) 12163 << Decl << Decl; 12164 if (!ArgRE->isObjCSelfExpr()) { 12165 Diag(Decl->getLocation(), 12166 diag::note_objc_circular_container_declared_here) 12167 << Decl; 12168 } 12169 } 12170 } 12171 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12172 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12173 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12174 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12175 Diag(Message->getSourceRange().getBegin(), 12176 diag::warn_objc_circular_container) 12177 << Decl << Decl; 12178 Diag(Decl->getLocation(), 12179 diag::note_objc_circular_container_declared_here) 12180 << Decl; 12181 } 12182 } 12183 } 12184 } 12185 } 12186 12187 /// Check a message send to see if it's likely to cause a retain cycle. 12188 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12189 // Only check instance methods whose selector looks like a setter. 12190 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12191 return; 12192 12193 // Try to find a variable that the receiver is strongly owned by. 12194 RetainCycleOwner owner; 12195 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12196 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12197 return; 12198 } else { 12199 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12200 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12201 owner.Loc = msg->getSuperLoc(); 12202 owner.Range = msg->getSuperLoc(); 12203 } 12204 12205 // Check whether the receiver is captured by any of the arguments. 12206 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12207 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12208 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12209 // noescape blocks should not be retained by the method. 12210 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12211 continue; 12212 return diagnoseRetainCycle(*this, capturer, owner); 12213 } 12214 } 12215 } 12216 12217 /// Check a property assign to see if it's likely to cause a retain cycle. 12218 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12219 RetainCycleOwner owner; 12220 if (!findRetainCycleOwner(*this, receiver, owner)) 12221 return; 12222 12223 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12224 diagnoseRetainCycle(*this, capturer, owner); 12225 } 12226 12227 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12228 RetainCycleOwner Owner; 12229 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12230 return; 12231 12232 // Because we don't have an expression for the variable, we have to set the 12233 // location explicitly here. 12234 Owner.Loc = Var->getLocation(); 12235 Owner.Range = Var->getSourceRange(); 12236 12237 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12238 diagnoseRetainCycle(*this, Capturer, Owner); 12239 } 12240 12241 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12242 Expr *RHS, bool isProperty) { 12243 // Check if RHS is an Objective-C object literal, which also can get 12244 // immediately zapped in a weak reference. Note that we explicitly 12245 // allow ObjCStringLiterals, since those are designed to never really die. 12246 RHS = RHS->IgnoreParenImpCasts(); 12247 12248 // This enum needs to match with the 'select' in 12249 // warn_objc_arc_literal_assign (off-by-1). 12250 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12251 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12252 return false; 12253 12254 S.Diag(Loc, diag::warn_arc_literal_assign) 12255 << (unsigned) Kind 12256 << (isProperty ? 0 : 1) 12257 << RHS->getSourceRange(); 12258 12259 return true; 12260 } 12261 12262 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12263 Qualifiers::ObjCLifetime LT, 12264 Expr *RHS, bool isProperty) { 12265 // Strip off any implicit cast added to get to the one ARC-specific. 12266 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12267 if (cast->getCastKind() == CK_ARCConsumeObject) { 12268 S.Diag(Loc, diag::warn_arc_retained_assign) 12269 << (LT == Qualifiers::OCL_ExplicitNone) 12270 << (isProperty ? 0 : 1) 12271 << RHS->getSourceRange(); 12272 return true; 12273 } 12274 RHS = cast->getSubExpr(); 12275 } 12276 12277 if (LT == Qualifiers::OCL_Weak && 12278 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12279 return true; 12280 12281 return false; 12282 } 12283 12284 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12285 QualType LHS, Expr *RHS) { 12286 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12287 12288 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12289 return false; 12290 12291 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12292 return true; 12293 12294 return false; 12295 } 12296 12297 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12298 Expr *LHS, Expr *RHS) { 12299 QualType LHSType; 12300 // PropertyRef on LHS type need be directly obtained from 12301 // its declaration as it has a PseudoType. 12302 ObjCPropertyRefExpr *PRE 12303 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12304 if (PRE && !PRE->isImplicitProperty()) { 12305 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12306 if (PD) 12307 LHSType = PD->getType(); 12308 } 12309 12310 if (LHSType.isNull()) 12311 LHSType = LHS->getType(); 12312 12313 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12314 12315 if (LT == Qualifiers::OCL_Weak) { 12316 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12317 getCurFunction()->markSafeWeakUse(LHS); 12318 } 12319 12320 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12321 return; 12322 12323 // FIXME. Check for other life times. 12324 if (LT != Qualifiers::OCL_None) 12325 return; 12326 12327 if (PRE) { 12328 if (PRE->isImplicitProperty()) 12329 return; 12330 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12331 if (!PD) 12332 return; 12333 12334 unsigned Attributes = PD->getPropertyAttributes(); 12335 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12336 // when 'assign' attribute was not explicitly specified 12337 // by user, ignore it and rely on property type itself 12338 // for lifetime info. 12339 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12340 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12341 LHSType->isObjCRetainableType()) 12342 return; 12343 12344 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12345 if (cast->getCastKind() == CK_ARCConsumeObject) { 12346 Diag(Loc, diag::warn_arc_retained_property_assign) 12347 << RHS->getSourceRange(); 12348 return; 12349 } 12350 RHS = cast->getSubExpr(); 12351 } 12352 } 12353 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12354 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12355 return; 12356 } 12357 } 12358 } 12359 12360 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12361 12362 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12363 SourceLocation StmtLoc, 12364 const NullStmt *Body) { 12365 // Do not warn if the body is a macro that expands to nothing, e.g: 12366 // 12367 // #define CALL(x) 12368 // if (condition) 12369 // CALL(0); 12370 if (Body->hasLeadingEmptyMacro()) 12371 return false; 12372 12373 // Get line numbers of statement and body. 12374 bool StmtLineInvalid; 12375 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12376 &StmtLineInvalid); 12377 if (StmtLineInvalid) 12378 return false; 12379 12380 bool BodyLineInvalid; 12381 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12382 &BodyLineInvalid); 12383 if (BodyLineInvalid) 12384 return false; 12385 12386 // Warn if null statement and body are on the same line. 12387 if (StmtLine != BodyLine) 12388 return false; 12389 12390 return true; 12391 } 12392 12393 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12394 const Stmt *Body, 12395 unsigned DiagID) { 12396 // Since this is a syntactic check, don't emit diagnostic for template 12397 // instantiations, this just adds noise. 12398 if (CurrentInstantiationScope) 12399 return; 12400 12401 // The body should be a null statement. 12402 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12403 if (!NBody) 12404 return; 12405 12406 // Do the usual checks. 12407 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12408 return; 12409 12410 Diag(NBody->getSemiLoc(), DiagID); 12411 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12412 } 12413 12414 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 12415 const Stmt *PossibleBody) { 12416 assert(!CurrentInstantiationScope); // Ensured by caller 12417 12418 SourceLocation StmtLoc; 12419 const Stmt *Body; 12420 unsigned DiagID; 12421 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 12422 StmtLoc = FS->getRParenLoc(); 12423 Body = FS->getBody(); 12424 DiagID = diag::warn_empty_for_body; 12425 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 12426 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 12427 Body = WS->getBody(); 12428 DiagID = diag::warn_empty_while_body; 12429 } else 12430 return; // Neither `for' nor `while'. 12431 12432 // The body should be a null statement. 12433 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12434 if (!NBody) 12435 return; 12436 12437 // Skip expensive checks if diagnostic is disabled. 12438 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 12439 return; 12440 12441 // Do the usual checks. 12442 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12443 return; 12444 12445 // `for(...);' and `while(...);' are popular idioms, so in order to keep 12446 // noise level low, emit diagnostics only if for/while is followed by a 12447 // CompoundStmt, e.g.: 12448 // for (int i = 0; i < n; i++); 12449 // { 12450 // a(i); 12451 // } 12452 // or if for/while is followed by a statement with more indentation 12453 // than for/while itself: 12454 // for (int i = 0; i < n; i++); 12455 // a(i); 12456 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 12457 if (!ProbableTypo) { 12458 bool BodyColInvalid; 12459 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 12460 PossibleBody->getLocStart(), 12461 &BodyColInvalid); 12462 if (BodyColInvalid) 12463 return; 12464 12465 bool StmtColInvalid; 12466 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 12467 S->getLocStart(), 12468 &StmtColInvalid); 12469 if (StmtColInvalid) 12470 return; 12471 12472 if (BodyCol > StmtCol) 12473 ProbableTypo = true; 12474 } 12475 12476 if (ProbableTypo) { 12477 Diag(NBody->getSemiLoc(), DiagID); 12478 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12479 } 12480 } 12481 12482 //===--- CHECK: Warn on self move with std::move. -------------------------===// 12483 12484 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 12485 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 12486 SourceLocation OpLoc) { 12487 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 12488 return; 12489 12490 if (inTemplateInstantiation()) 12491 return; 12492 12493 // Strip parens and casts away. 12494 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12495 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12496 12497 // Check for a call expression 12498 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 12499 if (!CE || CE->getNumArgs() != 1) 12500 return; 12501 12502 // Check for a call to std::move 12503 if (!CE->isCallToStdMove()) 12504 return; 12505 12506 // Get argument from std::move 12507 RHSExpr = CE->getArg(0); 12508 12509 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12510 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12511 12512 // Two DeclRefExpr's, check that the decls are the same. 12513 if (LHSDeclRef && RHSDeclRef) { 12514 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12515 return; 12516 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12517 RHSDeclRef->getDecl()->getCanonicalDecl()) 12518 return; 12519 12520 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12521 << LHSExpr->getSourceRange() 12522 << RHSExpr->getSourceRange(); 12523 return; 12524 } 12525 12526 // Member variables require a different approach to check for self moves. 12527 // MemberExpr's are the same if every nested MemberExpr refers to the same 12528 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 12529 // the base Expr's are CXXThisExpr's. 12530 const Expr *LHSBase = LHSExpr; 12531 const Expr *RHSBase = RHSExpr; 12532 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 12533 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 12534 if (!LHSME || !RHSME) 12535 return; 12536 12537 while (LHSME && RHSME) { 12538 if (LHSME->getMemberDecl()->getCanonicalDecl() != 12539 RHSME->getMemberDecl()->getCanonicalDecl()) 12540 return; 12541 12542 LHSBase = LHSME->getBase(); 12543 RHSBase = RHSME->getBase(); 12544 LHSME = dyn_cast<MemberExpr>(LHSBase); 12545 RHSME = dyn_cast<MemberExpr>(RHSBase); 12546 } 12547 12548 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 12549 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 12550 if (LHSDeclRef && RHSDeclRef) { 12551 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12552 return; 12553 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12554 RHSDeclRef->getDecl()->getCanonicalDecl()) 12555 return; 12556 12557 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12558 << LHSExpr->getSourceRange() 12559 << RHSExpr->getSourceRange(); 12560 return; 12561 } 12562 12563 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 12564 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12565 << LHSExpr->getSourceRange() 12566 << RHSExpr->getSourceRange(); 12567 } 12568 12569 //===--- Layout compatibility ----------------------------------------------// 12570 12571 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 12572 12573 /// Check if two enumeration types are layout-compatible. 12574 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 12575 // C++11 [dcl.enum] p8: 12576 // Two enumeration types are layout-compatible if they have the same 12577 // underlying type. 12578 return ED1->isComplete() && ED2->isComplete() && 12579 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 12580 } 12581 12582 /// Check if two fields are layout-compatible. 12583 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 12584 FieldDecl *Field2) { 12585 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 12586 return false; 12587 12588 if (Field1->isBitField() != Field2->isBitField()) 12589 return false; 12590 12591 if (Field1->isBitField()) { 12592 // Make sure that the bit-fields are the same length. 12593 unsigned Bits1 = Field1->getBitWidthValue(C); 12594 unsigned Bits2 = Field2->getBitWidthValue(C); 12595 12596 if (Bits1 != Bits2) 12597 return false; 12598 } 12599 12600 return true; 12601 } 12602 12603 /// Check if two standard-layout structs are layout-compatible. 12604 /// (C++11 [class.mem] p17) 12605 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 12606 RecordDecl *RD2) { 12607 // If both records are C++ classes, check that base classes match. 12608 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 12609 // If one of records is a CXXRecordDecl we are in C++ mode, 12610 // thus the other one is a CXXRecordDecl, too. 12611 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 12612 // Check number of base classes. 12613 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 12614 return false; 12615 12616 // Check the base classes. 12617 for (CXXRecordDecl::base_class_const_iterator 12618 Base1 = D1CXX->bases_begin(), 12619 BaseEnd1 = D1CXX->bases_end(), 12620 Base2 = D2CXX->bases_begin(); 12621 Base1 != BaseEnd1; 12622 ++Base1, ++Base2) { 12623 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 12624 return false; 12625 } 12626 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 12627 // If only RD2 is a C++ class, it should have zero base classes. 12628 if (D2CXX->getNumBases() > 0) 12629 return false; 12630 } 12631 12632 // Check the fields. 12633 RecordDecl::field_iterator Field2 = RD2->field_begin(), 12634 Field2End = RD2->field_end(), 12635 Field1 = RD1->field_begin(), 12636 Field1End = RD1->field_end(); 12637 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 12638 if (!isLayoutCompatible(C, *Field1, *Field2)) 12639 return false; 12640 } 12641 if (Field1 != Field1End || Field2 != Field2End) 12642 return false; 12643 12644 return true; 12645 } 12646 12647 /// Check if two standard-layout unions are layout-compatible. 12648 /// (C++11 [class.mem] p18) 12649 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 12650 RecordDecl *RD2) { 12651 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 12652 for (auto *Field2 : RD2->fields()) 12653 UnmatchedFields.insert(Field2); 12654 12655 for (auto *Field1 : RD1->fields()) { 12656 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 12657 I = UnmatchedFields.begin(), 12658 E = UnmatchedFields.end(); 12659 12660 for ( ; I != E; ++I) { 12661 if (isLayoutCompatible(C, Field1, *I)) { 12662 bool Result = UnmatchedFields.erase(*I); 12663 (void) Result; 12664 assert(Result); 12665 break; 12666 } 12667 } 12668 if (I == E) 12669 return false; 12670 } 12671 12672 return UnmatchedFields.empty(); 12673 } 12674 12675 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 12676 RecordDecl *RD2) { 12677 if (RD1->isUnion() != RD2->isUnion()) 12678 return false; 12679 12680 if (RD1->isUnion()) 12681 return isLayoutCompatibleUnion(C, RD1, RD2); 12682 else 12683 return isLayoutCompatibleStruct(C, RD1, RD2); 12684 } 12685 12686 /// Check if two types are layout-compatible in C++11 sense. 12687 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12688 if (T1.isNull() || T2.isNull()) 12689 return false; 12690 12691 // C++11 [basic.types] p11: 12692 // If two types T1 and T2 are the same type, then T1 and T2 are 12693 // layout-compatible types. 12694 if (C.hasSameType(T1, T2)) 12695 return true; 12696 12697 T1 = T1.getCanonicalType().getUnqualifiedType(); 12698 T2 = T2.getCanonicalType().getUnqualifiedType(); 12699 12700 const Type::TypeClass TC1 = T1->getTypeClass(); 12701 const Type::TypeClass TC2 = T2->getTypeClass(); 12702 12703 if (TC1 != TC2) 12704 return false; 12705 12706 if (TC1 == Type::Enum) { 12707 return isLayoutCompatible(C, 12708 cast<EnumType>(T1)->getDecl(), 12709 cast<EnumType>(T2)->getDecl()); 12710 } else if (TC1 == Type::Record) { 12711 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12712 return false; 12713 12714 return isLayoutCompatible(C, 12715 cast<RecordType>(T1)->getDecl(), 12716 cast<RecordType>(T2)->getDecl()); 12717 } 12718 12719 return false; 12720 } 12721 12722 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12723 12724 /// Given a type tag expression find the type tag itself. 12725 /// 12726 /// \param TypeExpr Type tag expression, as it appears in user's code. 12727 /// 12728 /// \param VD Declaration of an identifier that appears in a type tag. 12729 /// 12730 /// \param MagicValue Type tag magic value. 12731 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12732 const ValueDecl **VD, uint64_t *MagicValue) { 12733 while(true) { 12734 if (!TypeExpr) 12735 return false; 12736 12737 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12738 12739 switch (TypeExpr->getStmtClass()) { 12740 case Stmt::UnaryOperatorClass: { 12741 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12742 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12743 TypeExpr = UO->getSubExpr(); 12744 continue; 12745 } 12746 return false; 12747 } 12748 12749 case Stmt::DeclRefExprClass: { 12750 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12751 *VD = DRE->getDecl(); 12752 return true; 12753 } 12754 12755 case Stmt::IntegerLiteralClass: { 12756 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12757 llvm::APInt MagicValueAPInt = IL->getValue(); 12758 if (MagicValueAPInt.getActiveBits() <= 64) { 12759 *MagicValue = MagicValueAPInt.getZExtValue(); 12760 return true; 12761 } else 12762 return false; 12763 } 12764 12765 case Stmt::BinaryConditionalOperatorClass: 12766 case Stmt::ConditionalOperatorClass: { 12767 const AbstractConditionalOperator *ACO = 12768 cast<AbstractConditionalOperator>(TypeExpr); 12769 bool Result; 12770 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12771 if (Result) 12772 TypeExpr = ACO->getTrueExpr(); 12773 else 12774 TypeExpr = ACO->getFalseExpr(); 12775 continue; 12776 } 12777 return false; 12778 } 12779 12780 case Stmt::BinaryOperatorClass: { 12781 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12782 if (BO->getOpcode() == BO_Comma) { 12783 TypeExpr = BO->getRHS(); 12784 continue; 12785 } 12786 return false; 12787 } 12788 12789 default: 12790 return false; 12791 } 12792 } 12793 } 12794 12795 /// Retrieve the C type corresponding to type tag TypeExpr. 12796 /// 12797 /// \param TypeExpr Expression that specifies a type tag. 12798 /// 12799 /// \param MagicValues Registered magic values. 12800 /// 12801 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12802 /// kind. 12803 /// 12804 /// \param TypeInfo Information about the corresponding C type. 12805 /// 12806 /// \returns true if the corresponding C type was found. 12807 static bool GetMatchingCType( 12808 const IdentifierInfo *ArgumentKind, 12809 const Expr *TypeExpr, const ASTContext &Ctx, 12810 const llvm::DenseMap<Sema::TypeTagMagicValue, 12811 Sema::TypeTagData> *MagicValues, 12812 bool &FoundWrongKind, 12813 Sema::TypeTagData &TypeInfo) { 12814 FoundWrongKind = false; 12815 12816 // Variable declaration that has type_tag_for_datatype attribute. 12817 const ValueDecl *VD = nullptr; 12818 12819 uint64_t MagicValue; 12820 12821 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12822 return false; 12823 12824 if (VD) { 12825 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12826 if (I->getArgumentKind() != ArgumentKind) { 12827 FoundWrongKind = true; 12828 return false; 12829 } 12830 TypeInfo.Type = I->getMatchingCType(); 12831 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12832 TypeInfo.MustBeNull = I->getMustBeNull(); 12833 return true; 12834 } 12835 return false; 12836 } 12837 12838 if (!MagicValues) 12839 return false; 12840 12841 llvm::DenseMap<Sema::TypeTagMagicValue, 12842 Sema::TypeTagData>::const_iterator I = 12843 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12844 if (I == MagicValues->end()) 12845 return false; 12846 12847 TypeInfo = I->second; 12848 return true; 12849 } 12850 12851 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12852 uint64_t MagicValue, QualType Type, 12853 bool LayoutCompatible, 12854 bool MustBeNull) { 12855 if (!TypeTagForDatatypeMagicValues) 12856 TypeTagForDatatypeMagicValues.reset( 12857 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12858 12859 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12860 (*TypeTagForDatatypeMagicValues)[Magic] = 12861 TypeTagData(Type, LayoutCompatible, MustBeNull); 12862 } 12863 12864 static bool IsSameCharType(QualType T1, QualType T2) { 12865 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12866 if (!BT1) 12867 return false; 12868 12869 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12870 if (!BT2) 12871 return false; 12872 12873 BuiltinType::Kind T1Kind = BT1->getKind(); 12874 BuiltinType::Kind T2Kind = BT2->getKind(); 12875 12876 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12877 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12878 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12879 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12880 } 12881 12882 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12883 const ArrayRef<const Expr *> ExprArgs, 12884 SourceLocation CallSiteLoc) { 12885 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12886 bool IsPointerAttr = Attr->getIsPointer(); 12887 12888 // Retrieve the argument representing the 'type_tag'. 12889 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 12890 if (TypeTagIdxAST >= ExprArgs.size()) { 12891 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12892 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 12893 return; 12894 } 12895 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 12896 bool FoundWrongKind; 12897 TypeTagData TypeInfo; 12898 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12899 TypeTagForDatatypeMagicValues.get(), 12900 FoundWrongKind, TypeInfo)) { 12901 if (FoundWrongKind) 12902 Diag(TypeTagExpr->getExprLoc(), 12903 diag::warn_type_tag_for_datatype_wrong_kind) 12904 << TypeTagExpr->getSourceRange(); 12905 return; 12906 } 12907 12908 // Retrieve the argument representing the 'arg_idx'. 12909 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 12910 if (ArgumentIdxAST >= ExprArgs.size()) { 12911 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12912 << 1 << Attr->getArgumentIdx().getSourceIndex(); 12913 return; 12914 } 12915 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 12916 if (IsPointerAttr) { 12917 // Skip implicit cast of pointer to `void *' (as a function argument). 12918 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12919 if (ICE->getType()->isVoidPointerType() && 12920 ICE->getCastKind() == CK_BitCast) 12921 ArgumentExpr = ICE->getSubExpr(); 12922 } 12923 QualType ArgumentType = ArgumentExpr->getType(); 12924 12925 // Passing a `void*' pointer shouldn't trigger a warning. 12926 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12927 return; 12928 12929 if (TypeInfo.MustBeNull) { 12930 // Type tag with matching void type requires a null pointer. 12931 if (!ArgumentExpr->isNullPointerConstant(Context, 12932 Expr::NPC_ValueDependentIsNotNull)) { 12933 Diag(ArgumentExpr->getExprLoc(), 12934 diag::warn_type_safety_null_pointer_required) 12935 << ArgumentKind->getName() 12936 << ArgumentExpr->getSourceRange() 12937 << TypeTagExpr->getSourceRange(); 12938 } 12939 return; 12940 } 12941 12942 QualType RequiredType = TypeInfo.Type; 12943 if (IsPointerAttr) 12944 RequiredType = Context.getPointerType(RequiredType); 12945 12946 bool mismatch = false; 12947 if (!TypeInfo.LayoutCompatible) { 12948 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12949 12950 // C++11 [basic.fundamental] p1: 12951 // Plain char, signed char, and unsigned char are three distinct types. 12952 // 12953 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12954 // char' depending on the current char signedness mode. 12955 if (mismatch) 12956 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12957 RequiredType->getPointeeType())) || 12958 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12959 mismatch = false; 12960 } else 12961 if (IsPointerAttr) 12962 mismatch = !isLayoutCompatible(Context, 12963 ArgumentType->getPointeeType(), 12964 RequiredType->getPointeeType()); 12965 else 12966 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12967 12968 if (mismatch) 12969 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12970 << ArgumentType << ArgumentKind 12971 << TypeInfo.LayoutCompatible << RequiredType 12972 << ArgumentExpr->getSourceRange() 12973 << TypeTagExpr->getSourceRange(); 12974 } 12975 12976 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12977 CharUnits Alignment) { 12978 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 12979 } 12980 12981 void Sema::DiagnoseMisalignedMembers() { 12982 for (MisalignedMember &m : MisalignedMembers) { 12983 const NamedDecl *ND = m.RD; 12984 if (ND->getName().empty()) { 12985 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 12986 ND = TD; 12987 } 12988 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 12989 << m.MD << ND << m.E->getSourceRange(); 12990 } 12991 MisalignedMembers.clear(); 12992 } 12993 12994 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 12995 E = E->IgnoreParens(); 12996 if (!T->isPointerType() && !T->isIntegerType()) 12997 return; 12998 if (isa<UnaryOperator>(E) && 12999 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13000 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13001 if (isa<MemberExpr>(Op)) { 13002 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13003 MisalignedMember(Op)); 13004 if (MA != MisalignedMembers.end() && 13005 (T->isIntegerType() || 13006 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13007 Context.getTypeAlignInChars( 13008 T->getPointeeType()) <= MA->Alignment)))) 13009 MisalignedMembers.erase(MA); 13010 } 13011 } 13012 } 13013 13014 void Sema::RefersToMemberWithReducedAlignment( 13015 Expr *E, 13016 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13017 Action) { 13018 const auto *ME = dyn_cast<MemberExpr>(E); 13019 if (!ME) 13020 return; 13021 13022 // No need to check expressions with an __unaligned-qualified type. 13023 if (E->getType().getQualifiers().hasUnaligned()) 13024 return; 13025 13026 // For a chain of MemberExpr like "a.b.c.d" this list 13027 // will keep FieldDecl's like [d, c, b]. 13028 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13029 const MemberExpr *TopME = nullptr; 13030 bool AnyIsPacked = false; 13031 do { 13032 QualType BaseType = ME->getBase()->getType(); 13033 if (ME->isArrow()) 13034 BaseType = BaseType->getPointeeType(); 13035 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13036 if (RD->isInvalidDecl()) 13037 return; 13038 13039 ValueDecl *MD = ME->getMemberDecl(); 13040 auto *FD = dyn_cast<FieldDecl>(MD); 13041 // We do not care about non-data members. 13042 if (!FD || FD->isInvalidDecl()) 13043 return; 13044 13045 AnyIsPacked = 13046 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13047 ReverseMemberChain.push_back(FD); 13048 13049 TopME = ME; 13050 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13051 } while (ME); 13052 assert(TopME && "We did not compute a topmost MemberExpr!"); 13053 13054 // Not the scope of this diagnostic. 13055 if (!AnyIsPacked) 13056 return; 13057 13058 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13059 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13060 // TODO: The innermost base of the member expression may be too complicated. 13061 // For now, just disregard these cases. This is left for future 13062 // improvement. 13063 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13064 return; 13065 13066 // Alignment expected by the whole expression. 13067 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13068 13069 // No need to do anything else with this case. 13070 if (ExpectedAlignment.isOne()) 13071 return; 13072 13073 // Synthesize offset of the whole access. 13074 CharUnits Offset; 13075 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13076 I++) { 13077 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13078 } 13079 13080 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13081 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13082 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13083 13084 // The base expression of the innermost MemberExpr may give 13085 // stronger guarantees than the class containing the member. 13086 if (DRE && !TopME->isArrow()) { 13087 const ValueDecl *VD = DRE->getDecl(); 13088 if (!VD->getType()->isReferenceType()) 13089 CompleteObjectAlignment = 13090 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13091 } 13092 13093 // Check if the synthesized offset fulfills the alignment. 13094 if (Offset % ExpectedAlignment != 0 || 13095 // It may fulfill the offset it but the effective alignment may still be 13096 // lower than the expected expression alignment. 13097 CompleteObjectAlignment < ExpectedAlignment) { 13098 // If this happens, we want to determine a sensible culprit of this. 13099 // Intuitively, watching the chain of member expressions from right to 13100 // left, we start with the required alignment (as required by the field 13101 // type) but some packed attribute in that chain has reduced the alignment. 13102 // It may happen that another packed structure increases it again. But if 13103 // we are here such increase has not been enough. So pointing the first 13104 // FieldDecl that either is packed or else its RecordDecl is, 13105 // seems reasonable. 13106 FieldDecl *FD = nullptr; 13107 CharUnits Alignment; 13108 for (FieldDecl *FDI : ReverseMemberChain) { 13109 if (FDI->hasAttr<PackedAttr>() || 13110 FDI->getParent()->hasAttr<PackedAttr>()) { 13111 FD = FDI; 13112 Alignment = std::min( 13113 Context.getTypeAlignInChars(FD->getType()), 13114 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13115 break; 13116 } 13117 } 13118 assert(FD && "We did not find a packed FieldDecl!"); 13119 Action(E, FD->getParent(), FD, Alignment); 13120 } 13121 } 13122 13123 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13124 using namespace std::placeholders; 13125 13126 RefersToMemberWithReducedAlignment( 13127 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13128 _2, _3, _4)); 13129 } 13130