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 case Builtin::BI__builtin_signbit: 976 case Builtin::BI__builtin_signbitf: 977 case Builtin::BI__builtin_signbitl: 978 if (SemaBuiltinFPClassification(TheCall, 1)) 979 return ExprError(); 980 break; 981 case Builtin::BI__builtin_shufflevector: 982 return SemaBuiltinShuffleVector(TheCall); 983 // TheCall will be freed by the smart pointer here, but that's fine, since 984 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 985 case Builtin::BI__builtin_prefetch: 986 if (SemaBuiltinPrefetch(TheCall)) 987 return ExprError(); 988 break; 989 case Builtin::BI__builtin_alloca_with_align: 990 if (SemaBuiltinAllocaWithAlign(TheCall)) 991 return ExprError(); 992 break; 993 case Builtin::BI__assume: 994 case Builtin::BI__builtin_assume: 995 if (SemaBuiltinAssume(TheCall)) 996 return ExprError(); 997 break; 998 case Builtin::BI__builtin_assume_aligned: 999 if (SemaBuiltinAssumeAligned(TheCall)) 1000 return ExprError(); 1001 break; 1002 case Builtin::BI__builtin_object_size: 1003 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1004 return ExprError(); 1005 break; 1006 case Builtin::BI__builtin_longjmp: 1007 if (SemaBuiltinLongjmp(TheCall)) 1008 return ExprError(); 1009 break; 1010 case Builtin::BI__builtin_setjmp: 1011 if (SemaBuiltinSetjmp(TheCall)) 1012 return ExprError(); 1013 break; 1014 case Builtin::BI_setjmp: 1015 case Builtin::BI_setjmpex: 1016 if (checkArgCount(*this, TheCall, 1)) 1017 return true; 1018 break; 1019 case Builtin::BI__builtin_classify_type: 1020 if (checkArgCount(*this, TheCall, 1)) return true; 1021 TheCall->setType(Context.IntTy); 1022 break; 1023 case Builtin::BI__builtin_constant_p: 1024 if (checkArgCount(*this, TheCall, 1)) return true; 1025 TheCall->setType(Context.IntTy); 1026 break; 1027 case Builtin::BI__sync_fetch_and_add: 1028 case Builtin::BI__sync_fetch_and_add_1: 1029 case Builtin::BI__sync_fetch_and_add_2: 1030 case Builtin::BI__sync_fetch_and_add_4: 1031 case Builtin::BI__sync_fetch_and_add_8: 1032 case Builtin::BI__sync_fetch_and_add_16: 1033 case Builtin::BI__sync_fetch_and_sub: 1034 case Builtin::BI__sync_fetch_and_sub_1: 1035 case Builtin::BI__sync_fetch_and_sub_2: 1036 case Builtin::BI__sync_fetch_and_sub_4: 1037 case Builtin::BI__sync_fetch_and_sub_8: 1038 case Builtin::BI__sync_fetch_and_sub_16: 1039 case Builtin::BI__sync_fetch_and_or: 1040 case Builtin::BI__sync_fetch_and_or_1: 1041 case Builtin::BI__sync_fetch_and_or_2: 1042 case Builtin::BI__sync_fetch_and_or_4: 1043 case Builtin::BI__sync_fetch_and_or_8: 1044 case Builtin::BI__sync_fetch_and_or_16: 1045 case Builtin::BI__sync_fetch_and_and: 1046 case Builtin::BI__sync_fetch_and_and_1: 1047 case Builtin::BI__sync_fetch_and_and_2: 1048 case Builtin::BI__sync_fetch_and_and_4: 1049 case Builtin::BI__sync_fetch_and_and_8: 1050 case Builtin::BI__sync_fetch_and_and_16: 1051 case Builtin::BI__sync_fetch_and_xor: 1052 case Builtin::BI__sync_fetch_and_xor_1: 1053 case Builtin::BI__sync_fetch_and_xor_2: 1054 case Builtin::BI__sync_fetch_and_xor_4: 1055 case Builtin::BI__sync_fetch_and_xor_8: 1056 case Builtin::BI__sync_fetch_and_xor_16: 1057 case Builtin::BI__sync_fetch_and_nand: 1058 case Builtin::BI__sync_fetch_and_nand_1: 1059 case Builtin::BI__sync_fetch_and_nand_2: 1060 case Builtin::BI__sync_fetch_and_nand_4: 1061 case Builtin::BI__sync_fetch_and_nand_8: 1062 case Builtin::BI__sync_fetch_and_nand_16: 1063 case Builtin::BI__sync_add_and_fetch: 1064 case Builtin::BI__sync_add_and_fetch_1: 1065 case Builtin::BI__sync_add_and_fetch_2: 1066 case Builtin::BI__sync_add_and_fetch_4: 1067 case Builtin::BI__sync_add_and_fetch_8: 1068 case Builtin::BI__sync_add_and_fetch_16: 1069 case Builtin::BI__sync_sub_and_fetch: 1070 case Builtin::BI__sync_sub_and_fetch_1: 1071 case Builtin::BI__sync_sub_and_fetch_2: 1072 case Builtin::BI__sync_sub_and_fetch_4: 1073 case Builtin::BI__sync_sub_and_fetch_8: 1074 case Builtin::BI__sync_sub_and_fetch_16: 1075 case Builtin::BI__sync_and_and_fetch: 1076 case Builtin::BI__sync_and_and_fetch_1: 1077 case Builtin::BI__sync_and_and_fetch_2: 1078 case Builtin::BI__sync_and_and_fetch_4: 1079 case Builtin::BI__sync_and_and_fetch_8: 1080 case Builtin::BI__sync_and_and_fetch_16: 1081 case Builtin::BI__sync_or_and_fetch: 1082 case Builtin::BI__sync_or_and_fetch_1: 1083 case Builtin::BI__sync_or_and_fetch_2: 1084 case Builtin::BI__sync_or_and_fetch_4: 1085 case Builtin::BI__sync_or_and_fetch_8: 1086 case Builtin::BI__sync_or_and_fetch_16: 1087 case Builtin::BI__sync_xor_and_fetch: 1088 case Builtin::BI__sync_xor_and_fetch_1: 1089 case Builtin::BI__sync_xor_and_fetch_2: 1090 case Builtin::BI__sync_xor_and_fetch_4: 1091 case Builtin::BI__sync_xor_and_fetch_8: 1092 case Builtin::BI__sync_xor_and_fetch_16: 1093 case Builtin::BI__sync_nand_and_fetch: 1094 case Builtin::BI__sync_nand_and_fetch_1: 1095 case Builtin::BI__sync_nand_and_fetch_2: 1096 case Builtin::BI__sync_nand_and_fetch_4: 1097 case Builtin::BI__sync_nand_and_fetch_8: 1098 case Builtin::BI__sync_nand_and_fetch_16: 1099 case Builtin::BI__sync_val_compare_and_swap: 1100 case Builtin::BI__sync_val_compare_and_swap_1: 1101 case Builtin::BI__sync_val_compare_and_swap_2: 1102 case Builtin::BI__sync_val_compare_and_swap_4: 1103 case Builtin::BI__sync_val_compare_and_swap_8: 1104 case Builtin::BI__sync_val_compare_and_swap_16: 1105 case Builtin::BI__sync_bool_compare_and_swap: 1106 case Builtin::BI__sync_bool_compare_and_swap_1: 1107 case Builtin::BI__sync_bool_compare_and_swap_2: 1108 case Builtin::BI__sync_bool_compare_and_swap_4: 1109 case Builtin::BI__sync_bool_compare_and_swap_8: 1110 case Builtin::BI__sync_bool_compare_and_swap_16: 1111 case Builtin::BI__sync_lock_test_and_set: 1112 case Builtin::BI__sync_lock_test_and_set_1: 1113 case Builtin::BI__sync_lock_test_and_set_2: 1114 case Builtin::BI__sync_lock_test_and_set_4: 1115 case Builtin::BI__sync_lock_test_and_set_8: 1116 case Builtin::BI__sync_lock_test_and_set_16: 1117 case Builtin::BI__sync_lock_release: 1118 case Builtin::BI__sync_lock_release_1: 1119 case Builtin::BI__sync_lock_release_2: 1120 case Builtin::BI__sync_lock_release_4: 1121 case Builtin::BI__sync_lock_release_8: 1122 case Builtin::BI__sync_lock_release_16: 1123 case Builtin::BI__sync_swap: 1124 case Builtin::BI__sync_swap_1: 1125 case Builtin::BI__sync_swap_2: 1126 case Builtin::BI__sync_swap_4: 1127 case Builtin::BI__sync_swap_8: 1128 case Builtin::BI__sync_swap_16: 1129 return SemaBuiltinAtomicOverloaded(TheCallResult); 1130 case Builtin::BI__builtin_nontemporal_load: 1131 case Builtin::BI__builtin_nontemporal_store: 1132 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1133 #define BUILTIN(ID, TYPE, ATTRS) 1134 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1135 case Builtin::BI##ID: \ 1136 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1137 #include "clang/Basic/Builtins.def" 1138 case Builtin::BI__annotation: 1139 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1140 return ExprError(); 1141 break; 1142 case Builtin::BI__builtin_annotation: 1143 if (SemaBuiltinAnnotation(*this, TheCall)) 1144 return ExprError(); 1145 break; 1146 case Builtin::BI__builtin_addressof: 1147 if (SemaBuiltinAddressof(*this, TheCall)) 1148 return ExprError(); 1149 break; 1150 case Builtin::BI__builtin_add_overflow: 1151 case Builtin::BI__builtin_sub_overflow: 1152 case Builtin::BI__builtin_mul_overflow: 1153 if (SemaBuiltinOverflow(*this, TheCall)) 1154 return ExprError(); 1155 break; 1156 case Builtin::BI__builtin_operator_new: 1157 case Builtin::BI__builtin_operator_delete: { 1158 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1159 ExprResult Res = 1160 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1161 if (Res.isInvalid()) 1162 CorrectDelayedTyposInExpr(TheCallResult.get()); 1163 return Res; 1164 } 1165 case Builtin::BI__builtin_dump_struct: { 1166 // We first want to ensure we are called with 2 arguments 1167 if (checkArgCount(*this, TheCall, 2)) 1168 return ExprError(); 1169 // Ensure that the first argument is of type 'struct XX *' 1170 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1171 const QualType PtrArgType = PtrArg->getType(); 1172 if (!PtrArgType->isPointerType() || 1173 !PtrArgType->getPointeeType()->isRecordType()) { 1174 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1175 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1176 << "structure pointer"; 1177 return ExprError(); 1178 } 1179 1180 // Ensure that the second argument is of type 'FunctionType' 1181 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1182 const QualType FnPtrArgType = FnPtrArg->getType(); 1183 if (!FnPtrArgType->isPointerType()) { 1184 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1185 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1186 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1187 return ExprError(); 1188 } 1189 1190 const auto *FuncType = 1191 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1192 1193 if (!FuncType) { 1194 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1195 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1196 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1197 return ExprError(); 1198 } 1199 1200 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1201 if (!FT->getNumParams()) { 1202 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1203 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1204 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1205 return ExprError(); 1206 } 1207 QualType PT = FT->getParamType(0); 1208 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1209 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1210 !PT->getPointeeType().isConstQualified()) { 1211 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible) 1212 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1213 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1214 return ExprError(); 1215 } 1216 } 1217 1218 TheCall->setType(Context.IntTy); 1219 break; 1220 } 1221 1222 // check secure string manipulation functions where overflows 1223 // are detectable at compile time 1224 case Builtin::BI__builtin___memcpy_chk: 1225 case Builtin::BI__builtin___memmove_chk: 1226 case Builtin::BI__builtin___memset_chk: 1227 case Builtin::BI__builtin___strlcat_chk: 1228 case Builtin::BI__builtin___strlcpy_chk: 1229 case Builtin::BI__builtin___strncat_chk: 1230 case Builtin::BI__builtin___strncpy_chk: 1231 case Builtin::BI__builtin___stpncpy_chk: 1232 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3); 1233 break; 1234 case Builtin::BI__builtin___memccpy_chk: 1235 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4); 1236 break; 1237 case Builtin::BI__builtin___snprintf_chk: 1238 case Builtin::BI__builtin___vsnprintf_chk: 1239 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3); 1240 break; 1241 case Builtin::BI__builtin_call_with_static_chain: 1242 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1243 return ExprError(); 1244 break; 1245 case Builtin::BI__exception_code: 1246 case Builtin::BI_exception_code: 1247 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1248 diag::err_seh___except_block)) 1249 return ExprError(); 1250 break; 1251 case Builtin::BI__exception_info: 1252 case Builtin::BI_exception_info: 1253 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1254 diag::err_seh___except_filter)) 1255 return ExprError(); 1256 break; 1257 case Builtin::BI__GetExceptionInfo: 1258 if (checkArgCount(*this, TheCall, 1)) 1259 return ExprError(); 1260 1261 if (CheckCXXThrowOperand( 1262 TheCall->getLocStart(), 1263 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1264 TheCall)) 1265 return ExprError(); 1266 1267 TheCall->setType(Context.VoidPtrTy); 1268 break; 1269 // OpenCL v2.0, s6.13.16 - Pipe functions 1270 case Builtin::BIread_pipe: 1271 case Builtin::BIwrite_pipe: 1272 // Since those two functions are declared with var args, we need a semantic 1273 // check for the argument. 1274 if (SemaBuiltinRWPipe(*this, TheCall)) 1275 return ExprError(); 1276 TheCall->setType(Context.IntTy); 1277 break; 1278 case Builtin::BIreserve_read_pipe: 1279 case Builtin::BIreserve_write_pipe: 1280 case Builtin::BIwork_group_reserve_read_pipe: 1281 case Builtin::BIwork_group_reserve_write_pipe: 1282 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1283 return ExprError(); 1284 break; 1285 case Builtin::BIsub_group_reserve_read_pipe: 1286 case Builtin::BIsub_group_reserve_write_pipe: 1287 if (checkOpenCLSubgroupExt(*this, TheCall) || 1288 SemaBuiltinReserveRWPipe(*this, TheCall)) 1289 return ExprError(); 1290 break; 1291 case Builtin::BIcommit_read_pipe: 1292 case Builtin::BIcommit_write_pipe: 1293 case Builtin::BIwork_group_commit_read_pipe: 1294 case Builtin::BIwork_group_commit_write_pipe: 1295 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1296 return ExprError(); 1297 break; 1298 case Builtin::BIsub_group_commit_read_pipe: 1299 case Builtin::BIsub_group_commit_write_pipe: 1300 if (checkOpenCLSubgroupExt(*this, TheCall) || 1301 SemaBuiltinCommitRWPipe(*this, TheCall)) 1302 return ExprError(); 1303 break; 1304 case Builtin::BIget_pipe_num_packets: 1305 case Builtin::BIget_pipe_max_packets: 1306 if (SemaBuiltinPipePackets(*this, TheCall)) 1307 return ExprError(); 1308 TheCall->setType(Context.UnsignedIntTy); 1309 break; 1310 case Builtin::BIto_global: 1311 case Builtin::BIto_local: 1312 case Builtin::BIto_private: 1313 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1314 return ExprError(); 1315 break; 1316 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1317 case Builtin::BIenqueue_kernel: 1318 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1319 return ExprError(); 1320 break; 1321 case Builtin::BIget_kernel_work_group_size: 1322 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1323 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1324 return ExprError(); 1325 break; 1326 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1327 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1328 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1329 return ExprError(); 1330 break; 1331 case Builtin::BI__builtin_os_log_format: 1332 case Builtin::BI__builtin_os_log_format_buffer_size: 1333 if (SemaBuiltinOSLogFormat(TheCall)) 1334 return ExprError(); 1335 break; 1336 } 1337 1338 // Since the target specific builtins for each arch overlap, only check those 1339 // of the arch we are compiling for. 1340 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1341 switch (Context.getTargetInfo().getTriple().getArch()) { 1342 case llvm::Triple::arm: 1343 case llvm::Triple::armeb: 1344 case llvm::Triple::thumb: 1345 case llvm::Triple::thumbeb: 1346 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1347 return ExprError(); 1348 break; 1349 case llvm::Triple::aarch64: 1350 case llvm::Triple::aarch64_be: 1351 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1352 return ExprError(); 1353 break; 1354 case llvm::Triple::hexagon: 1355 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1356 return ExprError(); 1357 break; 1358 case llvm::Triple::mips: 1359 case llvm::Triple::mipsel: 1360 case llvm::Triple::mips64: 1361 case llvm::Triple::mips64el: 1362 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1363 return ExprError(); 1364 break; 1365 case llvm::Triple::systemz: 1366 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1367 return ExprError(); 1368 break; 1369 case llvm::Triple::x86: 1370 case llvm::Triple::x86_64: 1371 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1372 return ExprError(); 1373 break; 1374 case llvm::Triple::ppc: 1375 case llvm::Triple::ppc64: 1376 case llvm::Triple::ppc64le: 1377 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1378 return ExprError(); 1379 break; 1380 default: 1381 break; 1382 } 1383 } 1384 1385 return TheCallResult; 1386 } 1387 1388 // Get the valid immediate range for the specified NEON type code. 1389 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1390 NeonTypeFlags Type(t); 1391 int IsQuad = ForceQuad ? true : Type.isQuad(); 1392 switch (Type.getEltType()) { 1393 case NeonTypeFlags::Int8: 1394 case NeonTypeFlags::Poly8: 1395 return shift ? 7 : (8 << IsQuad) - 1; 1396 case NeonTypeFlags::Int16: 1397 case NeonTypeFlags::Poly16: 1398 return shift ? 15 : (4 << IsQuad) - 1; 1399 case NeonTypeFlags::Int32: 1400 return shift ? 31 : (2 << IsQuad) - 1; 1401 case NeonTypeFlags::Int64: 1402 case NeonTypeFlags::Poly64: 1403 return shift ? 63 : (1 << IsQuad) - 1; 1404 case NeonTypeFlags::Poly128: 1405 return shift ? 127 : (1 << IsQuad) - 1; 1406 case NeonTypeFlags::Float16: 1407 assert(!shift && "cannot shift float types!"); 1408 return (4 << IsQuad) - 1; 1409 case NeonTypeFlags::Float32: 1410 assert(!shift && "cannot shift float types!"); 1411 return (2 << IsQuad) - 1; 1412 case NeonTypeFlags::Float64: 1413 assert(!shift && "cannot shift float types!"); 1414 return (1 << IsQuad) - 1; 1415 } 1416 llvm_unreachable("Invalid NeonTypeFlag!"); 1417 } 1418 1419 /// getNeonEltType - Return the QualType corresponding to the elements of 1420 /// the vector type specified by the NeonTypeFlags. This is used to check 1421 /// the pointer arguments for Neon load/store intrinsics. 1422 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1423 bool IsPolyUnsigned, bool IsInt64Long) { 1424 switch (Flags.getEltType()) { 1425 case NeonTypeFlags::Int8: 1426 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1427 case NeonTypeFlags::Int16: 1428 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1429 case NeonTypeFlags::Int32: 1430 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1431 case NeonTypeFlags::Int64: 1432 if (IsInt64Long) 1433 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1434 else 1435 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1436 : Context.LongLongTy; 1437 case NeonTypeFlags::Poly8: 1438 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1439 case NeonTypeFlags::Poly16: 1440 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1441 case NeonTypeFlags::Poly64: 1442 if (IsInt64Long) 1443 return Context.UnsignedLongTy; 1444 else 1445 return Context.UnsignedLongLongTy; 1446 case NeonTypeFlags::Poly128: 1447 break; 1448 case NeonTypeFlags::Float16: 1449 return Context.HalfTy; 1450 case NeonTypeFlags::Float32: 1451 return Context.FloatTy; 1452 case NeonTypeFlags::Float64: 1453 return Context.DoubleTy; 1454 } 1455 llvm_unreachable("Invalid NeonTypeFlag!"); 1456 } 1457 1458 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1459 llvm::APSInt Result; 1460 uint64_t mask = 0; 1461 unsigned TV = 0; 1462 int PtrArgNum = -1; 1463 bool HasConstPtr = false; 1464 switch (BuiltinID) { 1465 #define GET_NEON_OVERLOAD_CHECK 1466 #include "clang/Basic/arm_neon.inc" 1467 #include "clang/Basic/arm_fp16.inc" 1468 #undef GET_NEON_OVERLOAD_CHECK 1469 } 1470 1471 // For NEON intrinsics which are overloaded on vector element type, validate 1472 // the immediate which specifies which variant to emit. 1473 unsigned ImmArg = TheCall->getNumArgs()-1; 1474 if (mask) { 1475 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1476 return true; 1477 1478 TV = Result.getLimitedValue(64); 1479 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1480 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code) 1481 << TheCall->getArg(ImmArg)->getSourceRange(); 1482 } 1483 1484 if (PtrArgNum >= 0) { 1485 // Check that pointer arguments have the specified type. 1486 Expr *Arg = TheCall->getArg(PtrArgNum); 1487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1488 Arg = ICE->getSubExpr(); 1489 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1490 QualType RHSTy = RHS.get()->getType(); 1491 1492 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1493 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1494 Arch == llvm::Triple::aarch64_be; 1495 bool IsInt64Long = 1496 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1497 QualType EltTy = 1498 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1499 if (HasConstPtr) 1500 EltTy = EltTy.withConst(); 1501 QualType LHSTy = Context.getPointerType(EltTy); 1502 AssignConvertType ConvTy; 1503 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1504 if (RHS.isInvalid()) 1505 return true; 1506 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy, 1507 RHS.get(), AA_Assigning)) 1508 return true; 1509 } 1510 1511 // For NEON intrinsics which take an immediate value as part of the 1512 // instruction, range check them here. 1513 unsigned i = 0, l = 0, u = 0; 1514 switch (BuiltinID) { 1515 default: 1516 return false; 1517 #define GET_NEON_IMMEDIATE_CHECK 1518 #include "clang/Basic/arm_neon.inc" 1519 #include "clang/Basic/arm_fp16.inc" 1520 #undef GET_NEON_IMMEDIATE_CHECK 1521 } 1522 1523 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1524 } 1525 1526 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1527 unsigned MaxWidth) { 1528 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1529 BuiltinID == ARM::BI__builtin_arm_ldaex || 1530 BuiltinID == ARM::BI__builtin_arm_strex || 1531 BuiltinID == ARM::BI__builtin_arm_stlex || 1532 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1533 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1534 BuiltinID == AArch64::BI__builtin_arm_strex || 1535 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1536 "unexpected ARM builtin"); 1537 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1538 BuiltinID == ARM::BI__builtin_arm_ldaex || 1539 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1540 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1541 1542 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1543 1544 // Ensure that we have the proper number of arguments. 1545 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1546 return true; 1547 1548 // Inspect the pointer argument of the atomic builtin. This should always be 1549 // a pointer type, whose element is an integral scalar or pointer type. 1550 // Because it is a pointer type, we don't have to worry about any implicit 1551 // casts here. 1552 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1553 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1554 if (PointerArgRes.isInvalid()) 1555 return true; 1556 PointerArg = PointerArgRes.get(); 1557 1558 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1559 if (!pointerType) { 1560 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 1561 << PointerArg->getType() << PointerArg->getSourceRange(); 1562 return true; 1563 } 1564 1565 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1566 // task is to insert the appropriate casts into the AST. First work out just 1567 // what the appropriate type is. 1568 QualType ValType = pointerType->getPointeeType(); 1569 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1570 if (IsLdrex) 1571 AddrType.addConst(); 1572 1573 // Issue a warning if the cast is dodgy. 1574 CastKind CastNeeded = CK_NoOp; 1575 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1576 CastNeeded = CK_BitCast; 1577 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers) 1578 << PointerArg->getType() 1579 << Context.getPointerType(AddrType) 1580 << AA_Passing << PointerArg->getSourceRange(); 1581 } 1582 1583 // Finally, do the cast and replace the argument with the corrected version. 1584 AddrType = Context.getPointerType(AddrType); 1585 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1586 if (PointerArgRes.isInvalid()) 1587 return true; 1588 PointerArg = PointerArgRes.get(); 1589 1590 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1591 1592 // In general, we allow ints, floats and pointers to be loaded and stored. 1593 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1594 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1595 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1596 << PointerArg->getType() << PointerArg->getSourceRange(); 1597 return true; 1598 } 1599 1600 // But ARM doesn't have instructions to deal with 128-bit versions. 1601 if (Context.getTypeSize(ValType) > MaxWidth) { 1602 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1603 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size) 1604 << PointerArg->getType() << PointerArg->getSourceRange(); 1605 return true; 1606 } 1607 1608 switch (ValType.getObjCLifetime()) { 1609 case Qualifiers::OCL_None: 1610 case Qualifiers::OCL_ExplicitNone: 1611 // okay 1612 break; 1613 1614 case Qualifiers::OCL_Weak: 1615 case Qualifiers::OCL_Strong: 1616 case Qualifiers::OCL_Autoreleasing: 1617 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 1618 << ValType << PointerArg->getSourceRange(); 1619 return true; 1620 } 1621 1622 if (IsLdrex) { 1623 TheCall->setType(ValType); 1624 return false; 1625 } 1626 1627 // Initialize the argument to be stored. 1628 ExprResult ValArg = TheCall->getArg(0); 1629 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1630 Context, ValType, /*consume*/ false); 1631 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1632 if (ValArg.isInvalid()) 1633 return true; 1634 TheCall->setArg(0, ValArg.get()); 1635 1636 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1637 // but the custom checker bypasses all default analysis. 1638 TheCall->setType(Context.IntTy); 1639 return false; 1640 } 1641 1642 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1643 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1644 BuiltinID == ARM::BI__builtin_arm_ldaex || 1645 BuiltinID == ARM::BI__builtin_arm_strex || 1646 BuiltinID == ARM::BI__builtin_arm_stlex) { 1647 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1648 } 1649 1650 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1651 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1652 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1653 } 1654 1655 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1656 BuiltinID == ARM::BI__builtin_arm_wsr64) 1657 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1658 1659 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1660 BuiltinID == ARM::BI__builtin_arm_rsrp || 1661 BuiltinID == ARM::BI__builtin_arm_wsr || 1662 BuiltinID == ARM::BI__builtin_arm_wsrp) 1663 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1664 1665 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1666 return true; 1667 1668 // For intrinsics which take an immediate value as part of the instruction, 1669 // range check them here. 1670 // FIXME: VFP Intrinsics should error if VFP not present. 1671 switch (BuiltinID) { 1672 default: return false; 1673 case ARM::BI__builtin_arm_ssat: 1674 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1675 case ARM::BI__builtin_arm_usat: 1676 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1677 case ARM::BI__builtin_arm_ssat16: 1678 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1679 case ARM::BI__builtin_arm_usat16: 1680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1681 case ARM::BI__builtin_arm_vcvtr_f: 1682 case ARM::BI__builtin_arm_vcvtr_d: 1683 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1684 case ARM::BI__builtin_arm_dmb: 1685 case ARM::BI__builtin_arm_dsb: 1686 case ARM::BI__builtin_arm_isb: 1687 case ARM::BI__builtin_arm_dbg: 1688 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1689 } 1690 } 1691 1692 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1693 CallExpr *TheCall) { 1694 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1695 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1696 BuiltinID == AArch64::BI__builtin_arm_strex || 1697 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1698 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1699 } 1700 1701 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1702 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1703 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1704 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1705 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1706 } 1707 1708 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1709 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1710 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1711 1712 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1713 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1714 BuiltinID == AArch64::BI__builtin_arm_wsr || 1715 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1716 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1717 1718 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1719 return true; 1720 1721 // For intrinsics which take an immediate value as part of the instruction, 1722 // range check them here. 1723 unsigned i = 0, l = 0, u = 0; 1724 switch (BuiltinID) { 1725 default: return false; 1726 case AArch64::BI__builtin_arm_dmb: 1727 case AArch64::BI__builtin_arm_dsb: 1728 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1729 } 1730 1731 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1732 } 1733 1734 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 1735 CallExpr *TheCall) { 1736 struct ArgInfo { 1737 ArgInfo(unsigned O, bool S, unsigned W, unsigned A) 1738 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {} 1739 unsigned OpNum = 0; 1740 bool IsSigned = false; 1741 unsigned BitWidth = 0; 1742 unsigned Align = 0; 1743 }; 1744 1745 static const std::map<unsigned, std::vector<ArgInfo>> Infos = { 1746 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 1747 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 1748 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 1749 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 1750 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 1751 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 1752 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 1753 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 1754 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 1755 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 1756 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 1757 1758 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 1759 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 1760 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 1761 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 1762 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 1763 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 1764 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 1765 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 1766 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 1767 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 1768 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 1769 1770 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 1771 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 1772 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 1773 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 1774 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 1775 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 1776 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 1777 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 1778 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 1779 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 1780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 1781 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 1782 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 1783 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 1784 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 1785 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 1786 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 1787 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 1788 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 1789 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 1790 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 1791 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 1792 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 1793 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 1794 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 1795 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 1796 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 1797 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 1798 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 1799 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 1800 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 1801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 1802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 1803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 1804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 1805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 1806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 1807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 1808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 1809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 1810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 1811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 1812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 1813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 1814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 1815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 1819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 1820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 1821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 1822 {{ 1, false, 6, 0 }} }, 1823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 1824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 1825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 1826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 1827 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 1828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 1829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 1830 {{ 1, false, 5, 0 }} }, 1831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 1832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 1833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 1834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 1835 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 1836 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 1837 { 2, false, 5, 0 }} }, 1838 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 1839 { 2, false, 6, 0 }} }, 1840 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 1841 { 3, false, 5, 0 }} }, 1842 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 1843 { 3, false, 6, 0 }} }, 1844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 1845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 1846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 1847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 1848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 1849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 1850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 1851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 1852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 1853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 1854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 1855 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 1856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 1857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 1858 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 1859 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 1860 {{ 2, false, 4, 0 }, 1861 { 3, false, 5, 0 }} }, 1862 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 1863 {{ 2, false, 4, 0 }, 1864 { 3, false, 5, 0 }} }, 1865 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 1866 {{ 2, false, 4, 0 }, 1867 { 3, false, 5, 0 }} }, 1868 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 1869 {{ 2, false, 4, 0 }, 1870 { 3, false, 5, 0 }} }, 1871 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 1872 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 1873 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 1874 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 1875 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 1876 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 1877 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 1878 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 1879 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 1880 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 1881 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 1882 { 2, false, 5, 0 }} }, 1883 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 1884 { 2, false, 6, 0 }} }, 1885 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 1886 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 1887 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 1888 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 1889 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 1890 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 1891 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 1892 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 1893 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 1894 {{ 1, false, 4, 0 }} }, 1895 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 1896 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 1897 {{ 1, false, 4, 0 }} }, 1898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 1899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 1900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 1901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 1902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 1903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 1904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 1905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 1906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 1907 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 1908 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 1909 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 1918 {{ 3, false, 1, 0 }} }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 1923 {{ 3, false, 1, 0 }} }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 1928 {{ 3, false, 1, 0 }} }, 1929 }; 1930 1931 auto F = Infos.find(BuiltinID); 1932 if (F == Infos.end()) 1933 return false; 1934 1935 bool Error = false; 1936 1937 for (const ArgInfo &A : F->second) { 1938 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0; 1939 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1; 1940 if (!A.Align) { 1941 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 1942 } else { 1943 unsigned M = 1 << A.Align; 1944 Min *= M; 1945 Max *= M; 1946 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 1947 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 1948 } 1949 } 1950 return Error; 1951 } 1952 1953 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 1954 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 1955 // ordering for DSP is unspecified. MSA is ordered by the data format used 1956 // by the underlying instruction i.e., df/m, df/n and then by size. 1957 // 1958 // FIXME: The size tests here should instead be tablegen'd along with the 1959 // definitions from include/clang/Basic/BuiltinsMips.def. 1960 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 1961 // be too. 1962 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1963 unsigned i = 0, l = 0, u = 0, m = 0; 1964 switch (BuiltinID) { 1965 default: return false; 1966 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 1967 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 1968 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 1969 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 1970 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 1971 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 1972 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 1973 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 1974 // df/m field. 1975 // These intrinsics take an unsigned 3 bit immediate. 1976 case Mips::BI__builtin_msa_bclri_b: 1977 case Mips::BI__builtin_msa_bnegi_b: 1978 case Mips::BI__builtin_msa_bseti_b: 1979 case Mips::BI__builtin_msa_sat_s_b: 1980 case Mips::BI__builtin_msa_sat_u_b: 1981 case Mips::BI__builtin_msa_slli_b: 1982 case Mips::BI__builtin_msa_srai_b: 1983 case Mips::BI__builtin_msa_srari_b: 1984 case Mips::BI__builtin_msa_srli_b: 1985 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 1986 case Mips::BI__builtin_msa_binsli_b: 1987 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 1988 // These intrinsics take an unsigned 4 bit immediate. 1989 case Mips::BI__builtin_msa_bclri_h: 1990 case Mips::BI__builtin_msa_bnegi_h: 1991 case Mips::BI__builtin_msa_bseti_h: 1992 case Mips::BI__builtin_msa_sat_s_h: 1993 case Mips::BI__builtin_msa_sat_u_h: 1994 case Mips::BI__builtin_msa_slli_h: 1995 case Mips::BI__builtin_msa_srai_h: 1996 case Mips::BI__builtin_msa_srari_h: 1997 case Mips::BI__builtin_msa_srli_h: 1998 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 1999 case Mips::BI__builtin_msa_binsli_h: 2000 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2001 // These intrinsics take an unsigned 5 bit immediate. 2002 // The first block of intrinsics actually have an unsigned 5 bit field, 2003 // not a df/n field. 2004 case Mips::BI__builtin_msa_clei_u_b: 2005 case Mips::BI__builtin_msa_clei_u_h: 2006 case Mips::BI__builtin_msa_clei_u_w: 2007 case Mips::BI__builtin_msa_clei_u_d: 2008 case Mips::BI__builtin_msa_clti_u_b: 2009 case Mips::BI__builtin_msa_clti_u_h: 2010 case Mips::BI__builtin_msa_clti_u_w: 2011 case Mips::BI__builtin_msa_clti_u_d: 2012 case Mips::BI__builtin_msa_maxi_u_b: 2013 case Mips::BI__builtin_msa_maxi_u_h: 2014 case Mips::BI__builtin_msa_maxi_u_w: 2015 case Mips::BI__builtin_msa_maxi_u_d: 2016 case Mips::BI__builtin_msa_mini_u_b: 2017 case Mips::BI__builtin_msa_mini_u_h: 2018 case Mips::BI__builtin_msa_mini_u_w: 2019 case Mips::BI__builtin_msa_mini_u_d: 2020 case Mips::BI__builtin_msa_addvi_b: 2021 case Mips::BI__builtin_msa_addvi_h: 2022 case Mips::BI__builtin_msa_addvi_w: 2023 case Mips::BI__builtin_msa_addvi_d: 2024 case Mips::BI__builtin_msa_bclri_w: 2025 case Mips::BI__builtin_msa_bnegi_w: 2026 case Mips::BI__builtin_msa_bseti_w: 2027 case Mips::BI__builtin_msa_sat_s_w: 2028 case Mips::BI__builtin_msa_sat_u_w: 2029 case Mips::BI__builtin_msa_slli_w: 2030 case Mips::BI__builtin_msa_srai_w: 2031 case Mips::BI__builtin_msa_srari_w: 2032 case Mips::BI__builtin_msa_srli_w: 2033 case Mips::BI__builtin_msa_srlri_w: 2034 case Mips::BI__builtin_msa_subvi_b: 2035 case Mips::BI__builtin_msa_subvi_h: 2036 case Mips::BI__builtin_msa_subvi_w: 2037 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2038 case Mips::BI__builtin_msa_binsli_w: 2039 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2040 // These intrinsics take an unsigned 6 bit immediate. 2041 case Mips::BI__builtin_msa_bclri_d: 2042 case Mips::BI__builtin_msa_bnegi_d: 2043 case Mips::BI__builtin_msa_bseti_d: 2044 case Mips::BI__builtin_msa_sat_s_d: 2045 case Mips::BI__builtin_msa_sat_u_d: 2046 case Mips::BI__builtin_msa_slli_d: 2047 case Mips::BI__builtin_msa_srai_d: 2048 case Mips::BI__builtin_msa_srari_d: 2049 case Mips::BI__builtin_msa_srli_d: 2050 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2051 case Mips::BI__builtin_msa_binsli_d: 2052 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2053 // These intrinsics take a signed 5 bit immediate. 2054 case Mips::BI__builtin_msa_ceqi_b: 2055 case Mips::BI__builtin_msa_ceqi_h: 2056 case Mips::BI__builtin_msa_ceqi_w: 2057 case Mips::BI__builtin_msa_ceqi_d: 2058 case Mips::BI__builtin_msa_clti_s_b: 2059 case Mips::BI__builtin_msa_clti_s_h: 2060 case Mips::BI__builtin_msa_clti_s_w: 2061 case Mips::BI__builtin_msa_clti_s_d: 2062 case Mips::BI__builtin_msa_clei_s_b: 2063 case Mips::BI__builtin_msa_clei_s_h: 2064 case Mips::BI__builtin_msa_clei_s_w: 2065 case Mips::BI__builtin_msa_clei_s_d: 2066 case Mips::BI__builtin_msa_maxi_s_b: 2067 case Mips::BI__builtin_msa_maxi_s_h: 2068 case Mips::BI__builtin_msa_maxi_s_w: 2069 case Mips::BI__builtin_msa_maxi_s_d: 2070 case Mips::BI__builtin_msa_mini_s_b: 2071 case Mips::BI__builtin_msa_mini_s_h: 2072 case Mips::BI__builtin_msa_mini_s_w: 2073 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2074 // These intrinsics take an unsigned 8 bit immediate. 2075 case Mips::BI__builtin_msa_andi_b: 2076 case Mips::BI__builtin_msa_nori_b: 2077 case Mips::BI__builtin_msa_ori_b: 2078 case Mips::BI__builtin_msa_shf_b: 2079 case Mips::BI__builtin_msa_shf_h: 2080 case Mips::BI__builtin_msa_shf_w: 2081 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2082 case Mips::BI__builtin_msa_bseli_b: 2083 case Mips::BI__builtin_msa_bmnzi_b: 2084 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2085 // df/n format 2086 // These intrinsics take an unsigned 4 bit immediate. 2087 case Mips::BI__builtin_msa_copy_s_b: 2088 case Mips::BI__builtin_msa_copy_u_b: 2089 case Mips::BI__builtin_msa_insve_b: 2090 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2091 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2092 // These intrinsics take an unsigned 3 bit immediate. 2093 case Mips::BI__builtin_msa_copy_s_h: 2094 case Mips::BI__builtin_msa_copy_u_h: 2095 case Mips::BI__builtin_msa_insve_h: 2096 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2097 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2098 // These intrinsics take an unsigned 2 bit immediate. 2099 case Mips::BI__builtin_msa_copy_s_w: 2100 case Mips::BI__builtin_msa_copy_u_w: 2101 case Mips::BI__builtin_msa_insve_w: 2102 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2103 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2104 // These intrinsics take an unsigned 1 bit immediate. 2105 case Mips::BI__builtin_msa_copy_s_d: 2106 case Mips::BI__builtin_msa_copy_u_d: 2107 case Mips::BI__builtin_msa_insve_d: 2108 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2109 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2110 // Memory offsets and immediate loads. 2111 // These intrinsics take a signed 10 bit immediate. 2112 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2113 case Mips::BI__builtin_msa_ldi_h: 2114 case Mips::BI__builtin_msa_ldi_w: 2115 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2116 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 2117 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 2118 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 2119 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 2120 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 2121 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 2122 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 2123 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 2124 } 2125 2126 if (!m) 2127 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2128 2129 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2130 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2131 } 2132 2133 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2134 unsigned i = 0, l = 0, u = 0; 2135 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2136 BuiltinID == PPC::BI__builtin_divdeu || 2137 BuiltinID == PPC::BI__builtin_bpermd; 2138 bool IsTarget64Bit = Context.getTargetInfo() 2139 .getTypeWidth(Context 2140 .getTargetInfo() 2141 .getIntPtrType()) == 64; 2142 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2143 BuiltinID == PPC::BI__builtin_divweu || 2144 BuiltinID == PPC::BI__builtin_divde || 2145 BuiltinID == PPC::BI__builtin_divdeu; 2146 2147 if (Is64BitBltin && !IsTarget64Bit) 2148 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt) 2149 << TheCall->getSourceRange(); 2150 2151 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2152 (BuiltinID == PPC::BI__builtin_bpermd && 2153 !Context.getTargetInfo().hasFeature("bpermd"))) 2154 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7) 2155 << TheCall->getSourceRange(); 2156 2157 switch (BuiltinID) { 2158 default: return false; 2159 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2160 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2161 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2162 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2163 case PPC::BI__builtin_tbegin: 2164 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2165 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2166 case PPC::BI__builtin_tabortwc: 2167 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2168 case PPC::BI__builtin_tabortwci: 2169 case PPC::BI__builtin_tabortdci: 2170 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2171 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2172 case PPC::BI__builtin_vsx_xxpermdi: 2173 case PPC::BI__builtin_vsx_xxsldwi: 2174 return SemaBuiltinVSX(TheCall); 2175 } 2176 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2177 } 2178 2179 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2180 CallExpr *TheCall) { 2181 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2182 Expr *Arg = TheCall->getArg(0); 2183 llvm::APSInt AbortCode(32); 2184 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2185 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2186 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code) 2187 << Arg->getSourceRange(); 2188 } 2189 2190 // For intrinsics which take an immediate value as part of the instruction, 2191 // range check them here. 2192 unsigned i = 0, l = 0, u = 0; 2193 switch (BuiltinID) { 2194 default: return false; 2195 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2196 case SystemZ::BI__builtin_s390_verimb: 2197 case SystemZ::BI__builtin_s390_verimh: 2198 case SystemZ::BI__builtin_s390_verimf: 2199 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2200 case SystemZ::BI__builtin_s390_vfaeb: 2201 case SystemZ::BI__builtin_s390_vfaeh: 2202 case SystemZ::BI__builtin_s390_vfaef: 2203 case SystemZ::BI__builtin_s390_vfaebs: 2204 case SystemZ::BI__builtin_s390_vfaehs: 2205 case SystemZ::BI__builtin_s390_vfaefs: 2206 case SystemZ::BI__builtin_s390_vfaezb: 2207 case SystemZ::BI__builtin_s390_vfaezh: 2208 case SystemZ::BI__builtin_s390_vfaezf: 2209 case SystemZ::BI__builtin_s390_vfaezbs: 2210 case SystemZ::BI__builtin_s390_vfaezhs: 2211 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2212 case SystemZ::BI__builtin_s390_vfisb: 2213 case SystemZ::BI__builtin_s390_vfidb: 2214 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 2215 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2216 case SystemZ::BI__builtin_s390_vftcisb: 2217 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 2218 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 2219 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 2220 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 2221 case SystemZ::BI__builtin_s390_vstrcb: 2222 case SystemZ::BI__builtin_s390_vstrch: 2223 case SystemZ::BI__builtin_s390_vstrcf: 2224 case SystemZ::BI__builtin_s390_vstrczb: 2225 case SystemZ::BI__builtin_s390_vstrczh: 2226 case SystemZ::BI__builtin_s390_vstrczf: 2227 case SystemZ::BI__builtin_s390_vstrcbs: 2228 case SystemZ::BI__builtin_s390_vstrchs: 2229 case SystemZ::BI__builtin_s390_vstrcfs: 2230 case SystemZ::BI__builtin_s390_vstrczbs: 2231 case SystemZ::BI__builtin_s390_vstrczhs: 2232 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 2233 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 2234 case SystemZ::BI__builtin_s390_vfminsb: 2235 case SystemZ::BI__builtin_s390_vfmaxsb: 2236 case SystemZ::BI__builtin_s390_vfmindb: 2237 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 2238 } 2239 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2240 } 2241 2242 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 2243 /// This checks that the target supports __builtin_cpu_supports and 2244 /// that the string argument is constant and valid. 2245 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 2246 Expr *Arg = TheCall->getArg(0); 2247 2248 // Check if the argument is a string literal. 2249 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2250 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2251 << Arg->getSourceRange(); 2252 2253 // Check the contents of the string. 2254 StringRef Feature = 2255 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2256 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 2257 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports) 2258 << Arg->getSourceRange(); 2259 return false; 2260 } 2261 2262 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 2263 /// This checks that the target supports __builtin_cpu_is and 2264 /// that the string argument is constant and valid. 2265 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 2266 Expr *Arg = TheCall->getArg(0); 2267 2268 // Check if the argument is a string literal. 2269 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2270 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 2271 << Arg->getSourceRange(); 2272 2273 // Check the contents of the string. 2274 StringRef Feature = 2275 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2276 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 2277 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is) 2278 << Arg->getSourceRange(); 2279 return false; 2280 } 2281 2282 // Check if the rounding mode is legal. 2283 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 2284 // Indicates if this instruction has rounding control or just SAE. 2285 bool HasRC = false; 2286 2287 unsigned ArgNum = 0; 2288 switch (BuiltinID) { 2289 default: 2290 return false; 2291 case X86::BI__builtin_ia32_vcvttsd2si32: 2292 case X86::BI__builtin_ia32_vcvttsd2si64: 2293 case X86::BI__builtin_ia32_vcvttsd2usi32: 2294 case X86::BI__builtin_ia32_vcvttsd2usi64: 2295 case X86::BI__builtin_ia32_vcvttss2si32: 2296 case X86::BI__builtin_ia32_vcvttss2si64: 2297 case X86::BI__builtin_ia32_vcvttss2usi32: 2298 case X86::BI__builtin_ia32_vcvttss2usi64: 2299 ArgNum = 1; 2300 break; 2301 case X86::BI__builtin_ia32_maxpd512: 2302 case X86::BI__builtin_ia32_maxps512: 2303 case X86::BI__builtin_ia32_minpd512: 2304 case X86::BI__builtin_ia32_minps512: 2305 ArgNum = 2; 2306 break; 2307 case X86::BI__builtin_ia32_cvtps2pd512_mask: 2308 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 2309 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 2310 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 2311 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 2312 case X86::BI__builtin_ia32_cvttps2dq512_mask: 2313 case X86::BI__builtin_ia32_cvttps2qq512_mask: 2314 case X86::BI__builtin_ia32_cvttps2udq512_mask: 2315 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 2316 case X86::BI__builtin_ia32_exp2pd_mask: 2317 case X86::BI__builtin_ia32_exp2ps_mask: 2318 case X86::BI__builtin_ia32_getexppd512_mask: 2319 case X86::BI__builtin_ia32_getexpps512_mask: 2320 case X86::BI__builtin_ia32_rcp28pd_mask: 2321 case X86::BI__builtin_ia32_rcp28ps_mask: 2322 case X86::BI__builtin_ia32_rsqrt28pd_mask: 2323 case X86::BI__builtin_ia32_rsqrt28ps_mask: 2324 case X86::BI__builtin_ia32_vcomisd: 2325 case X86::BI__builtin_ia32_vcomiss: 2326 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 2327 ArgNum = 3; 2328 break; 2329 case X86::BI__builtin_ia32_cmppd512_mask: 2330 case X86::BI__builtin_ia32_cmpps512_mask: 2331 case X86::BI__builtin_ia32_cmpsd_mask: 2332 case X86::BI__builtin_ia32_cmpss_mask: 2333 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 2334 case X86::BI__builtin_ia32_getexpsd128_round_mask: 2335 case X86::BI__builtin_ia32_getexpss128_round_mask: 2336 case X86::BI__builtin_ia32_maxsd_round_mask: 2337 case X86::BI__builtin_ia32_maxss_round_mask: 2338 case X86::BI__builtin_ia32_minsd_round_mask: 2339 case X86::BI__builtin_ia32_minss_round_mask: 2340 case X86::BI__builtin_ia32_rcp28sd_round_mask: 2341 case X86::BI__builtin_ia32_rcp28ss_round_mask: 2342 case X86::BI__builtin_ia32_reducepd512_mask: 2343 case X86::BI__builtin_ia32_reduceps512_mask: 2344 case X86::BI__builtin_ia32_rndscalepd_mask: 2345 case X86::BI__builtin_ia32_rndscaleps_mask: 2346 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 2347 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 2348 ArgNum = 4; 2349 break; 2350 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2351 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2352 case X86::BI__builtin_ia32_fixupimmps512_mask: 2353 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2354 case X86::BI__builtin_ia32_fixupimmsd_mask: 2355 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2356 case X86::BI__builtin_ia32_fixupimmss_mask: 2357 case X86::BI__builtin_ia32_fixupimmss_maskz: 2358 case X86::BI__builtin_ia32_rangepd512_mask: 2359 case X86::BI__builtin_ia32_rangeps512_mask: 2360 case X86::BI__builtin_ia32_rangesd128_round_mask: 2361 case X86::BI__builtin_ia32_rangess128_round_mask: 2362 case X86::BI__builtin_ia32_reducesd_mask: 2363 case X86::BI__builtin_ia32_reducess_mask: 2364 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2365 case X86::BI__builtin_ia32_rndscaless_round_mask: 2366 ArgNum = 5; 2367 break; 2368 case X86::BI__builtin_ia32_vcvtsd2si64: 2369 case X86::BI__builtin_ia32_vcvtsd2si32: 2370 case X86::BI__builtin_ia32_vcvtsd2usi32: 2371 case X86::BI__builtin_ia32_vcvtsd2usi64: 2372 case X86::BI__builtin_ia32_vcvtss2si32: 2373 case X86::BI__builtin_ia32_vcvtss2si64: 2374 case X86::BI__builtin_ia32_vcvtss2usi32: 2375 case X86::BI__builtin_ia32_vcvtss2usi64: 2376 case X86::BI__builtin_ia32_sqrtpd512: 2377 case X86::BI__builtin_ia32_sqrtps512: 2378 ArgNum = 1; 2379 HasRC = true; 2380 break; 2381 case X86::BI__builtin_ia32_addpd512: 2382 case X86::BI__builtin_ia32_addps512: 2383 case X86::BI__builtin_ia32_divpd512: 2384 case X86::BI__builtin_ia32_divps512: 2385 case X86::BI__builtin_ia32_mulpd512: 2386 case X86::BI__builtin_ia32_mulps512: 2387 case X86::BI__builtin_ia32_subpd512: 2388 case X86::BI__builtin_ia32_subps512: 2389 case X86::BI__builtin_ia32_cvtsi2sd64: 2390 case X86::BI__builtin_ia32_cvtsi2ss32: 2391 case X86::BI__builtin_ia32_cvtsi2ss64: 2392 case X86::BI__builtin_ia32_cvtusi2sd64: 2393 case X86::BI__builtin_ia32_cvtusi2ss32: 2394 case X86::BI__builtin_ia32_cvtusi2ss64: 2395 ArgNum = 2; 2396 HasRC = true; 2397 break; 2398 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 2399 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 2400 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 2401 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 2402 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 2403 case X86::BI__builtin_ia32_cvtps2qq512_mask: 2404 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 2405 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 2406 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 2407 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 2408 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 2409 ArgNum = 3; 2410 HasRC = true; 2411 break; 2412 case X86::BI__builtin_ia32_addss_round_mask: 2413 case X86::BI__builtin_ia32_addsd_round_mask: 2414 case X86::BI__builtin_ia32_divss_round_mask: 2415 case X86::BI__builtin_ia32_divsd_round_mask: 2416 case X86::BI__builtin_ia32_mulss_round_mask: 2417 case X86::BI__builtin_ia32_mulsd_round_mask: 2418 case X86::BI__builtin_ia32_subss_round_mask: 2419 case X86::BI__builtin_ia32_subsd_round_mask: 2420 case X86::BI__builtin_ia32_scalefpd512_mask: 2421 case X86::BI__builtin_ia32_scalefps512_mask: 2422 case X86::BI__builtin_ia32_scalefsd_round_mask: 2423 case X86::BI__builtin_ia32_scalefss_round_mask: 2424 case X86::BI__builtin_ia32_getmantpd512_mask: 2425 case X86::BI__builtin_ia32_getmantps512_mask: 2426 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 2427 case X86::BI__builtin_ia32_sqrtsd_round_mask: 2428 case X86::BI__builtin_ia32_sqrtss_round_mask: 2429 case X86::BI__builtin_ia32_vfmaddsd3_mask: 2430 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 2431 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 2432 case X86::BI__builtin_ia32_vfmaddss3_mask: 2433 case X86::BI__builtin_ia32_vfmaddss3_maskz: 2434 case X86::BI__builtin_ia32_vfmaddss3_mask3: 2435 case X86::BI__builtin_ia32_vfmaddpd512_mask: 2436 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 2437 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 2438 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 2439 case X86::BI__builtin_ia32_vfmaddps512_mask: 2440 case X86::BI__builtin_ia32_vfmaddps512_maskz: 2441 case X86::BI__builtin_ia32_vfmaddps512_mask3: 2442 case X86::BI__builtin_ia32_vfmsubps512_mask3: 2443 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 2444 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 2445 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 2446 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 2447 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 2448 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 2449 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 2450 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 2451 ArgNum = 4; 2452 HasRC = true; 2453 break; 2454 case X86::BI__builtin_ia32_getmantsd_round_mask: 2455 case X86::BI__builtin_ia32_getmantss_round_mask: 2456 ArgNum = 5; 2457 HasRC = true; 2458 break; 2459 } 2460 2461 llvm::APSInt Result; 2462 2463 // We can't check the value of a dependent argument. 2464 Expr *Arg = TheCall->getArg(ArgNum); 2465 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2466 return false; 2467 2468 // Check constant-ness first. 2469 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2470 return true; 2471 2472 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 2473 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 2474 // combined with ROUND_NO_EXC. 2475 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 2476 Result == 8/*ROUND_NO_EXC*/ || 2477 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 2478 return false; 2479 2480 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding) 2481 << Arg->getSourceRange(); 2482 } 2483 2484 // Check if the gather/scatter scale is legal. 2485 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 2486 CallExpr *TheCall) { 2487 unsigned ArgNum = 0; 2488 switch (BuiltinID) { 2489 default: 2490 return false; 2491 case X86::BI__builtin_ia32_gatherpfdpd: 2492 case X86::BI__builtin_ia32_gatherpfdps: 2493 case X86::BI__builtin_ia32_gatherpfqpd: 2494 case X86::BI__builtin_ia32_gatherpfqps: 2495 case X86::BI__builtin_ia32_scatterpfdpd: 2496 case X86::BI__builtin_ia32_scatterpfdps: 2497 case X86::BI__builtin_ia32_scatterpfqpd: 2498 case X86::BI__builtin_ia32_scatterpfqps: 2499 ArgNum = 3; 2500 break; 2501 case X86::BI__builtin_ia32_gatherd_pd: 2502 case X86::BI__builtin_ia32_gatherd_pd256: 2503 case X86::BI__builtin_ia32_gatherq_pd: 2504 case X86::BI__builtin_ia32_gatherq_pd256: 2505 case X86::BI__builtin_ia32_gatherd_ps: 2506 case X86::BI__builtin_ia32_gatherd_ps256: 2507 case X86::BI__builtin_ia32_gatherq_ps: 2508 case X86::BI__builtin_ia32_gatherq_ps256: 2509 case X86::BI__builtin_ia32_gatherd_q: 2510 case X86::BI__builtin_ia32_gatherd_q256: 2511 case X86::BI__builtin_ia32_gatherq_q: 2512 case X86::BI__builtin_ia32_gatherq_q256: 2513 case X86::BI__builtin_ia32_gatherd_d: 2514 case X86::BI__builtin_ia32_gatherd_d256: 2515 case X86::BI__builtin_ia32_gatherq_d: 2516 case X86::BI__builtin_ia32_gatherq_d256: 2517 case X86::BI__builtin_ia32_gather3div2df: 2518 case X86::BI__builtin_ia32_gather3div2di: 2519 case X86::BI__builtin_ia32_gather3div4df: 2520 case X86::BI__builtin_ia32_gather3div4di: 2521 case X86::BI__builtin_ia32_gather3div4sf: 2522 case X86::BI__builtin_ia32_gather3div4si: 2523 case X86::BI__builtin_ia32_gather3div8sf: 2524 case X86::BI__builtin_ia32_gather3div8si: 2525 case X86::BI__builtin_ia32_gather3siv2df: 2526 case X86::BI__builtin_ia32_gather3siv2di: 2527 case X86::BI__builtin_ia32_gather3siv4df: 2528 case X86::BI__builtin_ia32_gather3siv4di: 2529 case X86::BI__builtin_ia32_gather3siv4sf: 2530 case X86::BI__builtin_ia32_gather3siv4si: 2531 case X86::BI__builtin_ia32_gather3siv8sf: 2532 case X86::BI__builtin_ia32_gather3siv8si: 2533 case X86::BI__builtin_ia32_gathersiv8df: 2534 case X86::BI__builtin_ia32_gathersiv16sf: 2535 case X86::BI__builtin_ia32_gatherdiv8df: 2536 case X86::BI__builtin_ia32_gatherdiv16sf: 2537 case X86::BI__builtin_ia32_gathersiv8di: 2538 case X86::BI__builtin_ia32_gathersiv16si: 2539 case X86::BI__builtin_ia32_gatherdiv8di: 2540 case X86::BI__builtin_ia32_gatherdiv16si: 2541 case X86::BI__builtin_ia32_scatterdiv2df: 2542 case X86::BI__builtin_ia32_scatterdiv2di: 2543 case X86::BI__builtin_ia32_scatterdiv4df: 2544 case X86::BI__builtin_ia32_scatterdiv4di: 2545 case X86::BI__builtin_ia32_scatterdiv4sf: 2546 case X86::BI__builtin_ia32_scatterdiv4si: 2547 case X86::BI__builtin_ia32_scatterdiv8sf: 2548 case X86::BI__builtin_ia32_scatterdiv8si: 2549 case X86::BI__builtin_ia32_scattersiv2df: 2550 case X86::BI__builtin_ia32_scattersiv2di: 2551 case X86::BI__builtin_ia32_scattersiv4df: 2552 case X86::BI__builtin_ia32_scattersiv4di: 2553 case X86::BI__builtin_ia32_scattersiv4sf: 2554 case X86::BI__builtin_ia32_scattersiv4si: 2555 case X86::BI__builtin_ia32_scattersiv8sf: 2556 case X86::BI__builtin_ia32_scattersiv8si: 2557 case X86::BI__builtin_ia32_scattersiv8df: 2558 case X86::BI__builtin_ia32_scattersiv16sf: 2559 case X86::BI__builtin_ia32_scatterdiv8df: 2560 case X86::BI__builtin_ia32_scatterdiv16sf: 2561 case X86::BI__builtin_ia32_scattersiv8di: 2562 case X86::BI__builtin_ia32_scattersiv16si: 2563 case X86::BI__builtin_ia32_scatterdiv8di: 2564 case X86::BI__builtin_ia32_scatterdiv16si: 2565 ArgNum = 4; 2566 break; 2567 } 2568 2569 llvm::APSInt Result; 2570 2571 // We can't check the value of a dependent argument. 2572 Expr *Arg = TheCall->getArg(ArgNum); 2573 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2574 return false; 2575 2576 // Check constant-ness first. 2577 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 2578 return true; 2579 2580 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 2581 return false; 2582 2583 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale) 2584 << Arg->getSourceRange(); 2585 } 2586 2587 static bool isX86_32Builtin(unsigned BuiltinID) { 2588 // These builtins only work on x86-32 targets. 2589 switch (BuiltinID) { 2590 case X86::BI__builtin_ia32_readeflags_u32: 2591 case X86::BI__builtin_ia32_writeeflags_u32: 2592 return true; 2593 } 2594 2595 return false; 2596 } 2597 2598 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2599 if (BuiltinID == X86::BI__builtin_cpu_supports) 2600 return SemaBuiltinCpuSupports(*this, TheCall); 2601 2602 if (BuiltinID == X86::BI__builtin_cpu_is) 2603 return SemaBuiltinCpuIs(*this, TheCall); 2604 2605 // Check for 32-bit only builtins on a 64-bit target. 2606 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 2607 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 2608 return Diag(TheCall->getCallee()->getLocStart(), 2609 diag::err_32_bit_builtin_64_bit_tgt); 2610 2611 // If the intrinsic has rounding or SAE make sure its valid. 2612 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 2613 return true; 2614 2615 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 2616 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 2617 return true; 2618 2619 // For intrinsics which take an immediate value as part of the instruction, 2620 // range check them here. 2621 int i = 0, l = 0, u = 0; 2622 switch (BuiltinID) { 2623 default: 2624 return false; 2625 case X86::BI__builtin_ia32_vec_ext_v2si: 2626 case X86::BI__builtin_ia32_vec_ext_v2di: 2627 case X86::BI__builtin_ia32_vextractf128_pd256: 2628 case X86::BI__builtin_ia32_vextractf128_ps256: 2629 case X86::BI__builtin_ia32_vextractf128_si256: 2630 case X86::BI__builtin_ia32_extract128i256: 2631 case X86::BI__builtin_ia32_extractf64x4_mask: 2632 case X86::BI__builtin_ia32_extracti64x4_mask: 2633 case X86::BI__builtin_ia32_extractf32x8_mask: 2634 case X86::BI__builtin_ia32_extracti32x8_mask: 2635 case X86::BI__builtin_ia32_extractf64x2_256_mask: 2636 case X86::BI__builtin_ia32_extracti64x2_256_mask: 2637 case X86::BI__builtin_ia32_extractf32x4_256_mask: 2638 case X86::BI__builtin_ia32_extracti32x4_256_mask: 2639 i = 1; l = 0; u = 1; 2640 break; 2641 case X86::BI__builtin_ia32_vec_set_v2di: 2642 case X86::BI__builtin_ia32_vinsertf128_pd256: 2643 case X86::BI__builtin_ia32_vinsertf128_ps256: 2644 case X86::BI__builtin_ia32_vinsertf128_si256: 2645 case X86::BI__builtin_ia32_insert128i256: 2646 case X86::BI__builtin_ia32_insertf32x8: 2647 case X86::BI__builtin_ia32_inserti32x8: 2648 case X86::BI__builtin_ia32_insertf64x4: 2649 case X86::BI__builtin_ia32_inserti64x4: 2650 case X86::BI__builtin_ia32_insertf64x2_256: 2651 case X86::BI__builtin_ia32_inserti64x2_256: 2652 case X86::BI__builtin_ia32_insertf32x4_256: 2653 case X86::BI__builtin_ia32_inserti32x4_256: 2654 i = 2; l = 0; u = 1; 2655 break; 2656 case X86::BI__builtin_ia32_vpermilpd: 2657 case X86::BI__builtin_ia32_vec_ext_v4hi: 2658 case X86::BI__builtin_ia32_vec_ext_v4si: 2659 case X86::BI__builtin_ia32_vec_ext_v4sf: 2660 case X86::BI__builtin_ia32_vec_ext_v4di: 2661 case X86::BI__builtin_ia32_extractf32x4_mask: 2662 case X86::BI__builtin_ia32_extracti32x4_mask: 2663 case X86::BI__builtin_ia32_extractf64x2_512_mask: 2664 case X86::BI__builtin_ia32_extracti64x2_512_mask: 2665 i = 1; l = 0; u = 3; 2666 break; 2667 case X86::BI_mm_prefetch: 2668 case X86::BI__builtin_ia32_vec_ext_v8hi: 2669 case X86::BI__builtin_ia32_vec_ext_v8si: 2670 i = 1; l = 0; u = 7; 2671 break; 2672 case X86::BI__builtin_ia32_sha1rnds4: 2673 case X86::BI__builtin_ia32_blendpd: 2674 case X86::BI__builtin_ia32_shufpd: 2675 case X86::BI__builtin_ia32_vec_set_v4hi: 2676 case X86::BI__builtin_ia32_vec_set_v4si: 2677 case X86::BI__builtin_ia32_vec_set_v4di: 2678 case X86::BI__builtin_ia32_shuf_f32x4_256: 2679 case X86::BI__builtin_ia32_shuf_f64x2_256: 2680 case X86::BI__builtin_ia32_shuf_i32x4_256: 2681 case X86::BI__builtin_ia32_shuf_i64x2_256: 2682 case X86::BI__builtin_ia32_insertf64x2_512: 2683 case X86::BI__builtin_ia32_inserti64x2_512: 2684 case X86::BI__builtin_ia32_insertf32x4: 2685 case X86::BI__builtin_ia32_inserti32x4: 2686 i = 2; l = 0; u = 3; 2687 break; 2688 case X86::BI__builtin_ia32_vpermil2pd: 2689 case X86::BI__builtin_ia32_vpermil2pd256: 2690 case X86::BI__builtin_ia32_vpermil2ps: 2691 case X86::BI__builtin_ia32_vpermil2ps256: 2692 i = 3; l = 0; u = 3; 2693 break; 2694 case X86::BI__builtin_ia32_cmpb128_mask: 2695 case X86::BI__builtin_ia32_cmpw128_mask: 2696 case X86::BI__builtin_ia32_cmpd128_mask: 2697 case X86::BI__builtin_ia32_cmpq128_mask: 2698 case X86::BI__builtin_ia32_cmpb256_mask: 2699 case X86::BI__builtin_ia32_cmpw256_mask: 2700 case X86::BI__builtin_ia32_cmpd256_mask: 2701 case X86::BI__builtin_ia32_cmpq256_mask: 2702 case X86::BI__builtin_ia32_cmpb512_mask: 2703 case X86::BI__builtin_ia32_cmpw512_mask: 2704 case X86::BI__builtin_ia32_cmpd512_mask: 2705 case X86::BI__builtin_ia32_cmpq512_mask: 2706 case X86::BI__builtin_ia32_ucmpb128_mask: 2707 case X86::BI__builtin_ia32_ucmpw128_mask: 2708 case X86::BI__builtin_ia32_ucmpd128_mask: 2709 case X86::BI__builtin_ia32_ucmpq128_mask: 2710 case X86::BI__builtin_ia32_ucmpb256_mask: 2711 case X86::BI__builtin_ia32_ucmpw256_mask: 2712 case X86::BI__builtin_ia32_ucmpd256_mask: 2713 case X86::BI__builtin_ia32_ucmpq256_mask: 2714 case X86::BI__builtin_ia32_ucmpb512_mask: 2715 case X86::BI__builtin_ia32_ucmpw512_mask: 2716 case X86::BI__builtin_ia32_ucmpd512_mask: 2717 case X86::BI__builtin_ia32_ucmpq512_mask: 2718 case X86::BI__builtin_ia32_vpcomub: 2719 case X86::BI__builtin_ia32_vpcomuw: 2720 case X86::BI__builtin_ia32_vpcomud: 2721 case X86::BI__builtin_ia32_vpcomuq: 2722 case X86::BI__builtin_ia32_vpcomb: 2723 case X86::BI__builtin_ia32_vpcomw: 2724 case X86::BI__builtin_ia32_vpcomd: 2725 case X86::BI__builtin_ia32_vpcomq: 2726 case X86::BI__builtin_ia32_vec_set_v8hi: 2727 case X86::BI__builtin_ia32_vec_set_v8si: 2728 i = 2; l = 0; u = 7; 2729 break; 2730 case X86::BI__builtin_ia32_vpermilpd256: 2731 case X86::BI__builtin_ia32_roundps: 2732 case X86::BI__builtin_ia32_roundpd: 2733 case X86::BI__builtin_ia32_roundps256: 2734 case X86::BI__builtin_ia32_roundpd256: 2735 case X86::BI__builtin_ia32_getmantpd128_mask: 2736 case X86::BI__builtin_ia32_getmantpd256_mask: 2737 case X86::BI__builtin_ia32_getmantps128_mask: 2738 case X86::BI__builtin_ia32_getmantps256_mask: 2739 case X86::BI__builtin_ia32_getmantpd512_mask: 2740 case X86::BI__builtin_ia32_getmantps512_mask: 2741 case X86::BI__builtin_ia32_vec_ext_v16qi: 2742 case X86::BI__builtin_ia32_vec_ext_v16hi: 2743 i = 1; l = 0; u = 15; 2744 break; 2745 case X86::BI__builtin_ia32_pblendd128: 2746 case X86::BI__builtin_ia32_blendps: 2747 case X86::BI__builtin_ia32_blendpd256: 2748 case X86::BI__builtin_ia32_shufpd256: 2749 case X86::BI__builtin_ia32_roundss: 2750 case X86::BI__builtin_ia32_roundsd: 2751 case X86::BI__builtin_ia32_rangepd128_mask: 2752 case X86::BI__builtin_ia32_rangepd256_mask: 2753 case X86::BI__builtin_ia32_rangepd512_mask: 2754 case X86::BI__builtin_ia32_rangeps128_mask: 2755 case X86::BI__builtin_ia32_rangeps256_mask: 2756 case X86::BI__builtin_ia32_rangeps512_mask: 2757 case X86::BI__builtin_ia32_getmantsd_round_mask: 2758 case X86::BI__builtin_ia32_getmantss_round_mask: 2759 case X86::BI__builtin_ia32_vec_set_v16qi: 2760 case X86::BI__builtin_ia32_vec_set_v16hi: 2761 i = 2; l = 0; u = 15; 2762 break; 2763 case X86::BI__builtin_ia32_vec_ext_v32qi: 2764 i = 1; l = 0; u = 31; 2765 break; 2766 case X86::BI__builtin_ia32_cmpps: 2767 case X86::BI__builtin_ia32_cmpss: 2768 case X86::BI__builtin_ia32_cmppd: 2769 case X86::BI__builtin_ia32_cmpsd: 2770 case X86::BI__builtin_ia32_cmpps256: 2771 case X86::BI__builtin_ia32_cmppd256: 2772 case X86::BI__builtin_ia32_cmpps128_mask: 2773 case X86::BI__builtin_ia32_cmppd128_mask: 2774 case X86::BI__builtin_ia32_cmpps256_mask: 2775 case X86::BI__builtin_ia32_cmppd256_mask: 2776 case X86::BI__builtin_ia32_cmpps512_mask: 2777 case X86::BI__builtin_ia32_cmppd512_mask: 2778 case X86::BI__builtin_ia32_cmpsd_mask: 2779 case X86::BI__builtin_ia32_cmpss_mask: 2780 case X86::BI__builtin_ia32_vec_set_v32qi: 2781 i = 2; l = 0; u = 31; 2782 break; 2783 case X86::BI__builtin_ia32_permdf256: 2784 case X86::BI__builtin_ia32_permdi256: 2785 case X86::BI__builtin_ia32_permdf512: 2786 case X86::BI__builtin_ia32_permdi512: 2787 case X86::BI__builtin_ia32_vpermilps: 2788 case X86::BI__builtin_ia32_vpermilps256: 2789 case X86::BI__builtin_ia32_vpermilpd512: 2790 case X86::BI__builtin_ia32_vpermilps512: 2791 case X86::BI__builtin_ia32_pshufd: 2792 case X86::BI__builtin_ia32_pshufd256: 2793 case X86::BI__builtin_ia32_pshufd512: 2794 case X86::BI__builtin_ia32_pshufhw: 2795 case X86::BI__builtin_ia32_pshufhw256: 2796 case X86::BI__builtin_ia32_pshufhw512: 2797 case X86::BI__builtin_ia32_pshuflw: 2798 case X86::BI__builtin_ia32_pshuflw256: 2799 case X86::BI__builtin_ia32_pshuflw512: 2800 case X86::BI__builtin_ia32_vcvtps2ph: 2801 case X86::BI__builtin_ia32_vcvtps2ph_mask: 2802 case X86::BI__builtin_ia32_vcvtps2ph256: 2803 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 2804 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 2805 case X86::BI__builtin_ia32_rndscaleps_128_mask: 2806 case X86::BI__builtin_ia32_rndscalepd_128_mask: 2807 case X86::BI__builtin_ia32_rndscaleps_256_mask: 2808 case X86::BI__builtin_ia32_rndscalepd_256_mask: 2809 case X86::BI__builtin_ia32_rndscaleps_mask: 2810 case X86::BI__builtin_ia32_rndscalepd_mask: 2811 case X86::BI__builtin_ia32_reducepd128_mask: 2812 case X86::BI__builtin_ia32_reducepd256_mask: 2813 case X86::BI__builtin_ia32_reducepd512_mask: 2814 case X86::BI__builtin_ia32_reduceps128_mask: 2815 case X86::BI__builtin_ia32_reduceps256_mask: 2816 case X86::BI__builtin_ia32_reduceps512_mask: 2817 case X86::BI__builtin_ia32_prold512_mask: 2818 case X86::BI__builtin_ia32_prolq512_mask: 2819 case X86::BI__builtin_ia32_prold128_mask: 2820 case X86::BI__builtin_ia32_prold256_mask: 2821 case X86::BI__builtin_ia32_prolq128_mask: 2822 case X86::BI__builtin_ia32_prolq256_mask: 2823 case X86::BI__builtin_ia32_prord512_mask: 2824 case X86::BI__builtin_ia32_prorq512_mask: 2825 case X86::BI__builtin_ia32_prord128_mask: 2826 case X86::BI__builtin_ia32_prord256_mask: 2827 case X86::BI__builtin_ia32_prorq128_mask: 2828 case X86::BI__builtin_ia32_prorq256_mask: 2829 case X86::BI__builtin_ia32_fpclasspd128_mask: 2830 case X86::BI__builtin_ia32_fpclasspd256_mask: 2831 case X86::BI__builtin_ia32_fpclassps128_mask: 2832 case X86::BI__builtin_ia32_fpclassps256_mask: 2833 case X86::BI__builtin_ia32_fpclassps512_mask: 2834 case X86::BI__builtin_ia32_fpclasspd512_mask: 2835 case X86::BI__builtin_ia32_fpclasssd_mask: 2836 case X86::BI__builtin_ia32_fpclassss_mask: 2837 case X86::BI__builtin_ia32_pslldqi128_byteshift: 2838 case X86::BI__builtin_ia32_pslldqi256_byteshift: 2839 case X86::BI__builtin_ia32_pslldqi512_byteshift: 2840 case X86::BI__builtin_ia32_psrldqi128_byteshift: 2841 case X86::BI__builtin_ia32_psrldqi256_byteshift: 2842 case X86::BI__builtin_ia32_psrldqi512_byteshift: 2843 i = 1; l = 0; u = 255; 2844 break; 2845 case X86::BI__builtin_ia32_vperm2f128_pd256: 2846 case X86::BI__builtin_ia32_vperm2f128_ps256: 2847 case X86::BI__builtin_ia32_vperm2f128_si256: 2848 case X86::BI__builtin_ia32_permti256: 2849 case X86::BI__builtin_ia32_pblendw128: 2850 case X86::BI__builtin_ia32_pblendw256: 2851 case X86::BI__builtin_ia32_blendps256: 2852 case X86::BI__builtin_ia32_pblendd256: 2853 case X86::BI__builtin_ia32_palignr128: 2854 case X86::BI__builtin_ia32_palignr256: 2855 case X86::BI__builtin_ia32_palignr512: 2856 case X86::BI__builtin_ia32_alignq512: 2857 case X86::BI__builtin_ia32_alignd512: 2858 case X86::BI__builtin_ia32_alignd128: 2859 case X86::BI__builtin_ia32_alignd256: 2860 case X86::BI__builtin_ia32_alignq128: 2861 case X86::BI__builtin_ia32_alignq256: 2862 case X86::BI__builtin_ia32_vcomisd: 2863 case X86::BI__builtin_ia32_vcomiss: 2864 case X86::BI__builtin_ia32_shuf_f32x4: 2865 case X86::BI__builtin_ia32_shuf_f64x2: 2866 case X86::BI__builtin_ia32_shuf_i32x4: 2867 case X86::BI__builtin_ia32_shuf_i64x2: 2868 case X86::BI__builtin_ia32_shufpd512: 2869 case X86::BI__builtin_ia32_shufps: 2870 case X86::BI__builtin_ia32_shufps256: 2871 case X86::BI__builtin_ia32_shufps512: 2872 case X86::BI__builtin_ia32_dbpsadbw128: 2873 case X86::BI__builtin_ia32_dbpsadbw256: 2874 case X86::BI__builtin_ia32_dbpsadbw512: 2875 case X86::BI__builtin_ia32_vpshldd128: 2876 case X86::BI__builtin_ia32_vpshldd256: 2877 case X86::BI__builtin_ia32_vpshldd512: 2878 case X86::BI__builtin_ia32_vpshldq128: 2879 case X86::BI__builtin_ia32_vpshldq256: 2880 case X86::BI__builtin_ia32_vpshldq512: 2881 case X86::BI__builtin_ia32_vpshldw128: 2882 case X86::BI__builtin_ia32_vpshldw256: 2883 case X86::BI__builtin_ia32_vpshldw512: 2884 case X86::BI__builtin_ia32_vpshrdd128: 2885 case X86::BI__builtin_ia32_vpshrdd256: 2886 case X86::BI__builtin_ia32_vpshrdd512: 2887 case X86::BI__builtin_ia32_vpshrdq128: 2888 case X86::BI__builtin_ia32_vpshrdq256: 2889 case X86::BI__builtin_ia32_vpshrdq512: 2890 case X86::BI__builtin_ia32_vpshrdw128: 2891 case X86::BI__builtin_ia32_vpshrdw256: 2892 case X86::BI__builtin_ia32_vpshrdw512: 2893 i = 2; l = 0; u = 255; 2894 break; 2895 case X86::BI__builtin_ia32_fixupimmpd512_mask: 2896 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 2897 case X86::BI__builtin_ia32_fixupimmps512_mask: 2898 case X86::BI__builtin_ia32_fixupimmps512_maskz: 2899 case X86::BI__builtin_ia32_fixupimmsd_mask: 2900 case X86::BI__builtin_ia32_fixupimmsd_maskz: 2901 case X86::BI__builtin_ia32_fixupimmss_mask: 2902 case X86::BI__builtin_ia32_fixupimmss_maskz: 2903 case X86::BI__builtin_ia32_fixupimmpd128_mask: 2904 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 2905 case X86::BI__builtin_ia32_fixupimmpd256_mask: 2906 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 2907 case X86::BI__builtin_ia32_fixupimmps128_mask: 2908 case X86::BI__builtin_ia32_fixupimmps128_maskz: 2909 case X86::BI__builtin_ia32_fixupimmps256_mask: 2910 case X86::BI__builtin_ia32_fixupimmps256_maskz: 2911 case X86::BI__builtin_ia32_pternlogd512_mask: 2912 case X86::BI__builtin_ia32_pternlogd512_maskz: 2913 case X86::BI__builtin_ia32_pternlogq512_mask: 2914 case X86::BI__builtin_ia32_pternlogq512_maskz: 2915 case X86::BI__builtin_ia32_pternlogd128_mask: 2916 case X86::BI__builtin_ia32_pternlogd128_maskz: 2917 case X86::BI__builtin_ia32_pternlogd256_mask: 2918 case X86::BI__builtin_ia32_pternlogd256_maskz: 2919 case X86::BI__builtin_ia32_pternlogq128_mask: 2920 case X86::BI__builtin_ia32_pternlogq128_maskz: 2921 case X86::BI__builtin_ia32_pternlogq256_mask: 2922 case X86::BI__builtin_ia32_pternlogq256_maskz: 2923 i = 3; l = 0; u = 255; 2924 break; 2925 case X86::BI__builtin_ia32_gatherpfdpd: 2926 case X86::BI__builtin_ia32_gatherpfdps: 2927 case X86::BI__builtin_ia32_gatherpfqpd: 2928 case X86::BI__builtin_ia32_gatherpfqps: 2929 case X86::BI__builtin_ia32_scatterpfdpd: 2930 case X86::BI__builtin_ia32_scatterpfdps: 2931 case X86::BI__builtin_ia32_scatterpfqpd: 2932 case X86::BI__builtin_ia32_scatterpfqps: 2933 i = 4; l = 2; u = 3; 2934 break; 2935 case X86::BI__builtin_ia32_rndscalesd_round_mask: 2936 case X86::BI__builtin_ia32_rndscaless_round_mask: 2937 i = 4; l = 0; u = 255; 2938 break; 2939 } 2940 2941 // Note that we don't force a hard error on the range check here, allowing 2942 // template-generated or macro-generated dead code to potentially have out-of- 2943 // range values. These need to code generate, but don't need to necessarily 2944 // make any sense. We use a warning that defaults to an error. 2945 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 2946 } 2947 2948 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 2949 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 2950 /// Returns true when the format fits the function and the FormatStringInfo has 2951 /// been populated. 2952 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2953 FormatStringInfo *FSI) { 2954 FSI->HasVAListArg = Format->getFirstArg() == 0; 2955 FSI->FormatIdx = Format->getFormatIdx() - 1; 2956 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 2957 2958 // The way the format attribute works in GCC, the implicit this argument 2959 // of member functions is counted. However, it doesn't appear in our own 2960 // lists, so decrement format_idx in that case. 2961 if (IsCXXMember) { 2962 if(FSI->FormatIdx == 0) 2963 return false; 2964 --FSI->FormatIdx; 2965 if (FSI->FirstDataArg != 0) 2966 --FSI->FirstDataArg; 2967 } 2968 return true; 2969 } 2970 2971 /// Checks if a the given expression evaluates to null. 2972 /// 2973 /// Returns true if the value evaluates to null. 2974 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 2975 // If the expression has non-null type, it doesn't evaluate to null. 2976 if (auto nullability 2977 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 2978 if (*nullability == NullabilityKind::NonNull) 2979 return false; 2980 } 2981 2982 // As a special case, transparent unions initialized with zero are 2983 // considered null for the purposes of the nonnull attribute. 2984 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 2985 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2986 if (const CompoundLiteralExpr *CLE = 2987 dyn_cast<CompoundLiteralExpr>(Expr)) 2988 if (const InitListExpr *ILE = 2989 dyn_cast<InitListExpr>(CLE->getInitializer())) 2990 Expr = ILE->getInit(0); 2991 } 2992 2993 bool Result; 2994 return (!Expr->isValueDependent() && 2995 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 2996 !Result); 2997 } 2998 2999 static void CheckNonNullArgument(Sema &S, 3000 const Expr *ArgExpr, 3001 SourceLocation CallSiteLoc) { 3002 if (CheckNonNullExpr(S, ArgExpr)) 3003 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3004 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3005 } 3006 3007 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3008 FormatStringInfo FSI; 3009 if ((GetFormatStringType(Format) == FST_NSString) && 3010 getFormatStringInfo(Format, false, &FSI)) { 3011 Idx = FSI.FormatIdx; 3012 return true; 3013 } 3014 return false; 3015 } 3016 3017 /// Diagnose use of %s directive in an NSString which is being passed 3018 /// as formatting string to formatting method. 3019 static void 3020 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3021 const NamedDecl *FDecl, 3022 Expr **Args, 3023 unsigned NumArgs) { 3024 unsigned Idx = 0; 3025 bool Format = false; 3026 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3027 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3028 Idx = 2; 3029 Format = true; 3030 } 3031 else 3032 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3033 if (S.GetFormatNSStringIdx(I, Idx)) { 3034 Format = true; 3035 break; 3036 } 3037 } 3038 if (!Format || NumArgs <= Idx) 3039 return; 3040 const Expr *FormatExpr = Args[Idx]; 3041 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3042 FormatExpr = CSCE->getSubExpr(); 3043 const StringLiteral *FormatString; 3044 if (const ObjCStringLiteral *OSL = 3045 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3046 FormatString = OSL->getString(); 3047 else 3048 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3049 if (!FormatString) 3050 return; 3051 if (S.FormatStringHasSArg(FormatString)) { 3052 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3053 << "%s" << 1 << 1; 3054 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3055 << FDecl->getDeclName(); 3056 } 3057 } 3058 3059 /// Determine whether the given type has a non-null nullability annotation. 3060 static bool isNonNullType(ASTContext &ctx, QualType type) { 3061 if (auto nullability = type->getNullability(ctx)) 3062 return *nullability == NullabilityKind::NonNull; 3063 3064 return false; 3065 } 3066 3067 static void CheckNonNullArguments(Sema &S, 3068 const NamedDecl *FDecl, 3069 const FunctionProtoType *Proto, 3070 ArrayRef<const Expr *> Args, 3071 SourceLocation CallSiteLoc) { 3072 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3073 3074 // Check the attributes attached to the method/function itself. 3075 llvm::SmallBitVector NonNullArgs; 3076 if (FDecl) { 3077 // Handle the nonnull attribute on the function/method declaration itself. 3078 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3079 if (!NonNull->args_size()) { 3080 // Easy case: all pointer arguments are nonnull. 3081 for (const auto *Arg : Args) 3082 if (S.isValidPointerAttrType(Arg->getType())) 3083 CheckNonNullArgument(S, Arg, CallSiteLoc); 3084 return; 3085 } 3086 3087 for (const ParamIdx &Idx : NonNull->args()) { 3088 unsigned IdxAST = Idx.getASTIndex(); 3089 if (IdxAST >= Args.size()) 3090 continue; 3091 if (NonNullArgs.empty()) 3092 NonNullArgs.resize(Args.size()); 3093 NonNullArgs.set(IdxAST); 3094 } 3095 } 3096 } 3097 3098 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3099 // Handle the nonnull attribute on the parameters of the 3100 // function/method. 3101 ArrayRef<ParmVarDecl*> parms; 3102 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3103 parms = FD->parameters(); 3104 else 3105 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3106 3107 unsigned ParamIndex = 0; 3108 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3109 I != E; ++I, ++ParamIndex) { 3110 const ParmVarDecl *PVD = *I; 3111 if (PVD->hasAttr<NonNullAttr>() || 3112 isNonNullType(S.Context, PVD->getType())) { 3113 if (NonNullArgs.empty()) 3114 NonNullArgs.resize(Args.size()); 3115 3116 NonNullArgs.set(ParamIndex); 3117 } 3118 } 3119 } else { 3120 // If we have a non-function, non-method declaration but no 3121 // function prototype, try to dig out the function prototype. 3122 if (!Proto) { 3123 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3124 QualType type = VD->getType().getNonReferenceType(); 3125 if (auto pointerType = type->getAs<PointerType>()) 3126 type = pointerType->getPointeeType(); 3127 else if (auto blockType = type->getAs<BlockPointerType>()) 3128 type = blockType->getPointeeType(); 3129 // FIXME: data member pointers? 3130 3131 // Dig out the function prototype, if there is one. 3132 Proto = type->getAs<FunctionProtoType>(); 3133 } 3134 } 3135 3136 // Fill in non-null argument information from the nullability 3137 // information on the parameter types (if we have them). 3138 if (Proto) { 3139 unsigned Index = 0; 3140 for (auto paramType : Proto->getParamTypes()) { 3141 if (isNonNullType(S.Context, paramType)) { 3142 if (NonNullArgs.empty()) 3143 NonNullArgs.resize(Args.size()); 3144 3145 NonNullArgs.set(Index); 3146 } 3147 3148 ++Index; 3149 } 3150 } 3151 } 3152 3153 // Check for non-null arguments. 3154 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3155 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3156 if (NonNullArgs[ArgIndex]) 3157 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3158 } 3159 } 3160 3161 /// Handles the checks for format strings, non-POD arguments to vararg 3162 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3163 /// attributes. 3164 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3165 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3166 bool IsMemberFunction, SourceLocation Loc, 3167 SourceRange Range, VariadicCallType CallType) { 3168 // FIXME: We should check as much as we can in the template definition. 3169 if (CurContext->isDependentContext()) 3170 return; 3171 3172 // Printf and scanf checking. 3173 llvm::SmallBitVector CheckedVarArgs; 3174 if (FDecl) { 3175 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3176 // Only create vector if there are format attributes. 3177 CheckedVarArgs.resize(Args.size()); 3178 3179 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3180 CheckedVarArgs); 3181 } 3182 } 3183 3184 // Refuse POD arguments that weren't caught by the format string 3185 // checks above. 3186 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3187 if (CallType != VariadicDoesNotApply && 3188 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3189 unsigned NumParams = Proto ? Proto->getNumParams() 3190 : FDecl && isa<FunctionDecl>(FDecl) 3191 ? cast<FunctionDecl>(FDecl)->getNumParams() 3192 : FDecl && isa<ObjCMethodDecl>(FDecl) 3193 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3194 : 0; 3195 3196 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3197 // Args[ArgIdx] can be null in malformed code. 3198 if (const Expr *Arg = Args[ArgIdx]) { 3199 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3200 checkVariadicArgument(Arg, CallType); 3201 } 3202 } 3203 } 3204 3205 if (FDecl || Proto) { 3206 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3207 3208 // Type safety checking. 3209 if (FDecl) { 3210 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3211 CheckArgumentWithTypeTag(I, Args, Loc); 3212 } 3213 } 3214 3215 if (FD) 3216 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3217 } 3218 3219 /// CheckConstructorCall - Check a constructor call for correctness and safety 3220 /// properties not enforced by the C type system. 3221 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 3222 ArrayRef<const Expr *> Args, 3223 const FunctionProtoType *Proto, 3224 SourceLocation Loc) { 3225 VariadicCallType CallType = 3226 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3227 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 3228 Loc, SourceRange(), CallType); 3229 } 3230 3231 /// CheckFunctionCall - Check a direct function call for various correctness 3232 /// and safety properties not strictly enforced by the C type system. 3233 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 3234 const FunctionProtoType *Proto) { 3235 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 3236 isa<CXXMethodDecl>(FDecl); 3237 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 3238 IsMemberOperatorCall; 3239 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 3240 TheCall->getCallee()); 3241 Expr** Args = TheCall->getArgs(); 3242 unsigned NumArgs = TheCall->getNumArgs(); 3243 3244 Expr *ImplicitThis = nullptr; 3245 if (IsMemberOperatorCall) { 3246 // If this is a call to a member operator, hide the first argument 3247 // from checkCall. 3248 // FIXME: Our choice of AST representation here is less than ideal. 3249 ImplicitThis = Args[0]; 3250 ++Args; 3251 --NumArgs; 3252 } else if (IsMemberFunction) 3253 ImplicitThis = 3254 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 3255 3256 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 3257 IsMemberFunction, TheCall->getRParenLoc(), 3258 TheCall->getCallee()->getSourceRange(), CallType); 3259 3260 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3261 // None of the checks below are needed for functions that don't have 3262 // simple names (e.g., C++ conversion functions). 3263 if (!FnInfo) 3264 return false; 3265 3266 CheckAbsoluteValueFunction(TheCall, FDecl); 3267 CheckMaxUnsignedZero(TheCall, FDecl); 3268 3269 if (getLangOpts().ObjC1) 3270 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 3271 3272 unsigned CMId = FDecl->getMemoryFunctionKind(); 3273 if (CMId == 0) 3274 return false; 3275 3276 // Handle memory setting and copying functions. 3277 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 3278 CheckStrlcpycatArguments(TheCall, FnInfo); 3279 else if (CMId == Builtin::BIstrncat) 3280 CheckStrncatArguments(TheCall, FnInfo); 3281 else 3282 CheckMemaccessArguments(TheCall, CMId, FnInfo); 3283 3284 return false; 3285 } 3286 3287 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 3288 ArrayRef<const Expr *> Args) { 3289 VariadicCallType CallType = 3290 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 3291 3292 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 3293 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 3294 CallType); 3295 3296 return false; 3297 } 3298 3299 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 3300 const FunctionProtoType *Proto) { 3301 QualType Ty; 3302 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 3303 Ty = V->getType().getNonReferenceType(); 3304 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 3305 Ty = F->getType().getNonReferenceType(); 3306 else 3307 return false; 3308 3309 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 3310 !Ty->isFunctionProtoType()) 3311 return false; 3312 3313 VariadicCallType CallType; 3314 if (!Proto || !Proto->isVariadic()) { 3315 CallType = VariadicDoesNotApply; 3316 } else if (Ty->isBlockPointerType()) { 3317 CallType = VariadicBlock; 3318 } else { // Ty->isFunctionPointerType() 3319 CallType = VariadicFunction; 3320 } 3321 3322 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 3323 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3324 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3325 TheCall->getCallee()->getSourceRange(), CallType); 3326 3327 return false; 3328 } 3329 3330 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 3331 /// such as function pointers returned from functions. 3332 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 3333 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 3334 TheCall->getCallee()); 3335 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 3336 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3337 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3338 TheCall->getCallee()->getSourceRange(), CallType); 3339 3340 return false; 3341 } 3342 3343 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 3344 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 3345 return false; 3346 3347 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 3348 switch (Op) { 3349 case AtomicExpr::AO__c11_atomic_init: 3350 case AtomicExpr::AO__opencl_atomic_init: 3351 llvm_unreachable("There is no ordering argument for an init"); 3352 3353 case AtomicExpr::AO__c11_atomic_load: 3354 case AtomicExpr::AO__opencl_atomic_load: 3355 case AtomicExpr::AO__atomic_load_n: 3356 case AtomicExpr::AO__atomic_load: 3357 return OrderingCABI != llvm::AtomicOrderingCABI::release && 3358 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3359 3360 case AtomicExpr::AO__c11_atomic_store: 3361 case AtomicExpr::AO__opencl_atomic_store: 3362 case AtomicExpr::AO__atomic_store: 3363 case AtomicExpr::AO__atomic_store_n: 3364 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 3365 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 3366 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3367 3368 default: 3369 return true; 3370 } 3371 } 3372 3373 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 3374 AtomicExpr::AtomicOp Op) { 3375 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3376 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3377 3378 // All the non-OpenCL operations take one of the following forms. 3379 // The OpenCL operations take the __c11 forms with one extra argument for 3380 // synchronization scope. 3381 enum { 3382 // C __c11_atomic_init(A *, C) 3383 Init, 3384 3385 // C __c11_atomic_load(A *, int) 3386 Load, 3387 3388 // void __atomic_load(A *, CP, int) 3389 LoadCopy, 3390 3391 // void __atomic_store(A *, CP, int) 3392 Copy, 3393 3394 // C __c11_atomic_add(A *, M, int) 3395 Arithmetic, 3396 3397 // C __atomic_exchange_n(A *, CP, int) 3398 Xchg, 3399 3400 // void __atomic_exchange(A *, C *, CP, int) 3401 GNUXchg, 3402 3403 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 3404 C11CmpXchg, 3405 3406 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 3407 GNUCmpXchg 3408 } Form = Init; 3409 3410 const unsigned NumForm = GNUCmpXchg + 1; 3411 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 3412 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 3413 // where: 3414 // C is an appropriate type, 3415 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 3416 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 3417 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 3418 // the int parameters are for orderings. 3419 3420 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 3421 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 3422 "need to update code for modified forms"); 3423 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 3424 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 3425 AtomicExpr::AO__atomic_load, 3426 "need to update code for modified C11 atomics"); 3427 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 3428 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 3429 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 3430 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 3431 IsOpenCL; 3432 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 3433 Op == AtomicExpr::AO__atomic_store_n || 3434 Op == AtomicExpr::AO__atomic_exchange_n || 3435 Op == AtomicExpr::AO__atomic_compare_exchange_n; 3436 bool IsAddSub = false; 3437 bool IsMinMax = false; 3438 3439 switch (Op) { 3440 case AtomicExpr::AO__c11_atomic_init: 3441 case AtomicExpr::AO__opencl_atomic_init: 3442 Form = Init; 3443 break; 3444 3445 case AtomicExpr::AO__c11_atomic_load: 3446 case AtomicExpr::AO__opencl_atomic_load: 3447 case AtomicExpr::AO__atomic_load_n: 3448 Form = Load; 3449 break; 3450 3451 case AtomicExpr::AO__atomic_load: 3452 Form = LoadCopy; 3453 break; 3454 3455 case AtomicExpr::AO__c11_atomic_store: 3456 case AtomicExpr::AO__opencl_atomic_store: 3457 case AtomicExpr::AO__atomic_store: 3458 case AtomicExpr::AO__atomic_store_n: 3459 Form = Copy; 3460 break; 3461 3462 case AtomicExpr::AO__c11_atomic_fetch_add: 3463 case AtomicExpr::AO__c11_atomic_fetch_sub: 3464 case AtomicExpr::AO__opencl_atomic_fetch_add: 3465 case AtomicExpr::AO__opencl_atomic_fetch_sub: 3466 case AtomicExpr::AO__opencl_atomic_fetch_min: 3467 case AtomicExpr::AO__opencl_atomic_fetch_max: 3468 case AtomicExpr::AO__atomic_fetch_add: 3469 case AtomicExpr::AO__atomic_fetch_sub: 3470 case AtomicExpr::AO__atomic_add_fetch: 3471 case AtomicExpr::AO__atomic_sub_fetch: 3472 IsAddSub = true; 3473 LLVM_FALLTHROUGH; 3474 case AtomicExpr::AO__c11_atomic_fetch_and: 3475 case AtomicExpr::AO__c11_atomic_fetch_or: 3476 case AtomicExpr::AO__c11_atomic_fetch_xor: 3477 case AtomicExpr::AO__opencl_atomic_fetch_and: 3478 case AtomicExpr::AO__opencl_atomic_fetch_or: 3479 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3480 case AtomicExpr::AO__atomic_fetch_and: 3481 case AtomicExpr::AO__atomic_fetch_or: 3482 case AtomicExpr::AO__atomic_fetch_xor: 3483 case AtomicExpr::AO__atomic_fetch_nand: 3484 case AtomicExpr::AO__atomic_and_fetch: 3485 case AtomicExpr::AO__atomic_or_fetch: 3486 case AtomicExpr::AO__atomic_xor_fetch: 3487 case AtomicExpr::AO__atomic_nand_fetch: 3488 Form = Arithmetic; 3489 break; 3490 3491 case AtomicExpr::AO__atomic_fetch_min: 3492 case AtomicExpr::AO__atomic_fetch_max: 3493 IsMinMax = true; 3494 Form = Arithmetic; 3495 break; 3496 3497 case AtomicExpr::AO__c11_atomic_exchange: 3498 case AtomicExpr::AO__opencl_atomic_exchange: 3499 case AtomicExpr::AO__atomic_exchange_n: 3500 Form = Xchg; 3501 break; 3502 3503 case AtomicExpr::AO__atomic_exchange: 3504 Form = GNUXchg; 3505 break; 3506 3507 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3508 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3509 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3510 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3511 Form = C11CmpXchg; 3512 break; 3513 3514 case AtomicExpr::AO__atomic_compare_exchange: 3515 case AtomicExpr::AO__atomic_compare_exchange_n: 3516 Form = GNUCmpXchg; 3517 break; 3518 } 3519 3520 unsigned AdjustedNumArgs = NumArgs[Form]; 3521 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 3522 ++AdjustedNumArgs; 3523 // Check we have the right number of arguments. 3524 if (TheCall->getNumArgs() < AdjustedNumArgs) { 3525 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 3526 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3527 << TheCall->getCallee()->getSourceRange(); 3528 return ExprError(); 3529 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 3530 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(), 3531 diag::err_typecheck_call_too_many_args) 3532 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 3533 << TheCall->getCallee()->getSourceRange(); 3534 return ExprError(); 3535 } 3536 3537 // Inspect the first argument of the atomic operation. 3538 Expr *Ptr = TheCall->getArg(0); 3539 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3540 if (ConvertedPtr.isInvalid()) 3541 return ExprError(); 3542 3543 Ptr = ConvertedPtr.get(); 3544 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3545 if (!pointerType) { 3546 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3547 << Ptr->getType() << Ptr->getSourceRange(); 3548 return ExprError(); 3549 } 3550 3551 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3552 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3553 QualType ValType = AtomTy; // 'C' 3554 if (IsC11) { 3555 if (!AtomTy->isAtomicType()) { 3556 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic) 3557 << Ptr->getType() << Ptr->getSourceRange(); 3558 return ExprError(); 3559 } 3560 if (AtomTy.isConstQualified() || 3561 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3562 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic) 3563 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3564 << Ptr->getSourceRange(); 3565 return ExprError(); 3566 } 3567 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 3568 } else if (Form != Load && Form != LoadCopy) { 3569 if (ValType.isConstQualified()) { 3570 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer) 3571 << Ptr->getType() << Ptr->getSourceRange(); 3572 return ExprError(); 3573 } 3574 } 3575 3576 // For an arithmetic operation, the implied arithmetic must be well-formed. 3577 if (Form == Arithmetic) { 3578 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 3579 if (IsAddSub && !ValType->isIntegerType() 3580 && !ValType->isPointerType()) { 3581 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3582 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3583 return ExprError(); 3584 } 3585 if (IsMinMax) { 3586 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 3587 if (!BT || (BT->getKind() != BuiltinType::Int && 3588 BT->getKind() != BuiltinType::UInt)) { 3589 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr); 3590 return ExprError(); 3591 } 3592 } 3593 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 3594 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int) 3595 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3596 return ExprError(); 3597 } 3598 if (IsC11 && ValType->isPointerType() && 3599 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(), 3600 diag::err_incomplete_type)) { 3601 return ExprError(); 3602 } 3603 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3604 // For __atomic_*_n operations, the value type must be a scalar integral or 3605 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3606 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3607 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3608 return ExprError(); 3609 } 3610 3611 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3612 !AtomTy->isScalarType()) { 3613 // For GNU atomics, require a trivially-copyable type. This is not part of 3614 // the GNU atomics specification, but we enforce it for sanity. 3615 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy) 3616 << Ptr->getType() << Ptr->getSourceRange(); 3617 return ExprError(); 3618 } 3619 3620 switch (ValType.getObjCLifetime()) { 3621 case Qualifiers::OCL_None: 3622 case Qualifiers::OCL_ExplicitNone: 3623 // okay 3624 break; 3625 3626 case Qualifiers::OCL_Weak: 3627 case Qualifiers::OCL_Strong: 3628 case Qualifiers::OCL_Autoreleasing: 3629 // FIXME: Can this happen? By this point, ValType should be known 3630 // to be trivially copyable. 3631 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3632 << ValType << Ptr->getSourceRange(); 3633 return ExprError(); 3634 } 3635 3636 // All atomic operations have an overload which takes a pointer to a volatile 3637 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 3638 // into the result or the other operands. Similarly atomic_load takes a 3639 // pointer to a const 'A'. 3640 ValType.removeLocalVolatile(); 3641 ValType.removeLocalConst(); 3642 QualType ResultType = ValType; 3643 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 3644 Form == Init) 3645 ResultType = Context.VoidTy; 3646 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 3647 ResultType = Context.BoolTy; 3648 3649 // The type of a parameter passed 'by value'. In the GNU atomics, such 3650 // arguments are actually passed as pointers. 3651 QualType ByValType = ValType; // 'CP' 3652 bool IsPassedByAddress = false; 3653 if (!IsC11 && !IsN) { 3654 ByValType = Ptr->getType(); 3655 IsPassedByAddress = true; 3656 } 3657 3658 // The first argument's non-CV pointer type is used to deduce the type of 3659 // subsequent arguments, except for: 3660 // - weak flag (always converted to bool) 3661 // - memory order (always converted to int) 3662 // - scope (always converted to int) 3663 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3664 QualType Ty; 3665 if (i < NumVals[Form] + 1) { 3666 switch (i) { 3667 case 0: 3668 // The first argument is always a pointer. It has a fixed type. 3669 // It is always dereferenced, a nullptr is undefined. 3670 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3671 // Nothing else to do: we already know all we want about this pointer. 3672 continue; 3673 case 1: 3674 // The second argument is the non-atomic operand. For arithmetic, this 3675 // is always passed by value, and for a compare_exchange it is always 3676 // passed by address. For the rest, GNU uses by-address and C11 uses 3677 // by-value. 3678 assert(Form != Load); 3679 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 3680 Ty = ValType; 3681 else if (Form == Copy || Form == Xchg) { 3682 if (IsPassedByAddress) 3683 // The value pointer is always dereferenced, a nullptr is undefined. 3684 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3685 Ty = ByValType; 3686 } else if (Form == Arithmetic) 3687 Ty = Context.getPointerDiffType(); 3688 else { 3689 Expr *ValArg = TheCall->getArg(i); 3690 // The value pointer is always dereferenced, a nullptr is undefined. 3691 CheckNonNullArgument(*this, ValArg, DRE->getLocStart()); 3692 LangAS AS = LangAS::Default; 3693 // Keep address space of non-atomic pointer type. 3694 if (const PointerType *PtrTy = 3695 ValArg->getType()->getAs<PointerType>()) { 3696 AS = PtrTy->getPointeeType().getAddressSpace(); 3697 } 3698 Ty = Context.getPointerType( 3699 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 3700 } 3701 break; 3702 case 2: 3703 // The third argument to compare_exchange / GNU exchange is the desired 3704 // value, either by-value (for the C11 and *_n variant) or as a pointer. 3705 if (IsPassedByAddress) 3706 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart()); 3707 Ty = ByValType; 3708 break; 3709 case 3: 3710 // The fourth argument to GNU compare_exchange is a 'weak' flag. 3711 Ty = Context.BoolTy; 3712 break; 3713 } 3714 } else { 3715 // The order(s) and scope are always converted to int. 3716 Ty = Context.IntTy; 3717 } 3718 3719 InitializedEntity Entity = 3720 InitializedEntity::InitializeParameter(Context, Ty, false); 3721 ExprResult Arg = TheCall->getArg(i); 3722 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 3723 if (Arg.isInvalid()) 3724 return true; 3725 TheCall->setArg(i, Arg.get()); 3726 } 3727 3728 // Permute the arguments into a 'consistent' order. 3729 SmallVector<Expr*, 5> SubExprs; 3730 SubExprs.push_back(Ptr); 3731 switch (Form) { 3732 case Init: 3733 // Note, AtomicExpr::getVal1() has a special case for this atomic. 3734 SubExprs.push_back(TheCall->getArg(1)); // Val1 3735 break; 3736 case Load: 3737 SubExprs.push_back(TheCall->getArg(1)); // Order 3738 break; 3739 case LoadCopy: 3740 case Copy: 3741 case Arithmetic: 3742 case Xchg: 3743 SubExprs.push_back(TheCall->getArg(2)); // Order 3744 SubExprs.push_back(TheCall->getArg(1)); // Val1 3745 break; 3746 case GNUXchg: 3747 // Note, AtomicExpr::getVal2() has a special case for this atomic. 3748 SubExprs.push_back(TheCall->getArg(3)); // Order 3749 SubExprs.push_back(TheCall->getArg(1)); // Val1 3750 SubExprs.push_back(TheCall->getArg(2)); // Val2 3751 break; 3752 case C11CmpXchg: 3753 SubExprs.push_back(TheCall->getArg(3)); // Order 3754 SubExprs.push_back(TheCall->getArg(1)); // Val1 3755 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 3756 SubExprs.push_back(TheCall->getArg(2)); // Val2 3757 break; 3758 case GNUCmpXchg: 3759 SubExprs.push_back(TheCall->getArg(4)); // Order 3760 SubExprs.push_back(TheCall->getArg(1)); // Val1 3761 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 3762 SubExprs.push_back(TheCall->getArg(2)); // Val2 3763 SubExprs.push_back(TheCall->getArg(3)); // Weak 3764 break; 3765 } 3766 3767 if (SubExprs.size() >= 2 && Form != Init) { 3768 llvm::APSInt Result(32); 3769 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 3770 !isValidOrderingForOp(Result.getSExtValue(), Op)) 3771 Diag(SubExprs[1]->getLocStart(), 3772 diag::warn_atomic_op_has_invalid_memory_order) 3773 << SubExprs[1]->getSourceRange(); 3774 } 3775 3776 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 3777 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 3778 llvm::APSInt Result(32); 3779 if (Scope->isIntegerConstantExpr(Result, Context) && 3780 !ScopeModel->isValid(Result.getZExtValue())) { 3781 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope) 3782 << Scope->getSourceRange(); 3783 } 3784 SubExprs.push_back(Scope); 3785 } 3786 3787 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(), 3788 SubExprs, ResultType, Op, 3789 TheCall->getRParenLoc()); 3790 3791 if ((Op == AtomicExpr::AO__c11_atomic_load || 3792 Op == AtomicExpr::AO__c11_atomic_store || 3793 Op == AtomicExpr::AO__opencl_atomic_load || 3794 Op == AtomicExpr::AO__opencl_atomic_store ) && 3795 Context.AtomicUsesUnsupportedLibcall(AE)) 3796 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) 3797 << ((Op == AtomicExpr::AO__c11_atomic_load || 3798 Op == AtomicExpr::AO__opencl_atomic_load) 3799 ? 0 : 1); 3800 3801 return AE; 3802 } 3803 3804 /// checkBuiltinArgument - Given a call to a builtin function, perform 3805 /// normal type-checking on the given argument, updating the call in 3806 /// place. This is useful when a builtin function requires custom 3807 /// type-checking for some of its arguments but not necessarily all of 3808 /// them. 3809 /// 3810 /// Returns true on error. 3811 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 3812 FunctionDecl *Fn = E->getDirectCallee(); 3813 assert(Fn && "builtin call without direct callee!"); 3814 3815 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 3816 InitializedEntity Entity = 3817 InitializedEntity::InitializeParameter(S.Context, Param); 3818 3819 ExprResult Arg = E->getArg(0); 3820 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 3821 if (Arg.isInvalid()) 3822 return true; 3823 3824 E->setArg(ArgIndex, Arg.get()); 3825 return false; 3826 } 3827 3828 /// SemaBuiltinAtomicOverloaded - We have a call to a function like 3829 /// __sync_fetch_and_add, which is an overloaded function based on the pointer 3830 /// type of its first argument. The main ActOnCallExpr routines have already 3831 /// promoted the types of arguments because all of these calls are prototyped as 3832 /// void(...). 3833 /// 3834 /// This function goes through and does final semantic checking for these 3835 /// builtins, 3836 ExprResult 3837 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 3838 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 3839 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3840 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 3841 3842 // Ensure that we have at least one argument to do type inference from. 3843 if (TheCall->getNumArgs() < 1) { 3844 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 3845 << 0 << 1 << TheCall->getNumArgs() 3846 << TheCall->getCallee()->getSourceRange(); 3847 return ExprError(); 3848 } 3849 3850 // Inspect the first argument of the atomic builtin. This should always be 3851 // a pointer type, whose element is an integral scalar or pointer type. 3852 // Because it is a pointer type, we don't have to worry about any implicit 3853 // casts here. 3854 // FIXME: We don't allow floating point scalars as input. 3855 Expr *FirstArg = TheCall->getArg(0); 3856 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 3857 if (FirstArgResult.isInvalid()) 3858 return ExprError(); 3859 FirstArg = FirstArgResult.get(); 3860 TheCall->setArg(0, FirstArg); 3861 3862 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 3863 if (!pointerType) { 3864 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer) 3865 << FirstArg->getType() << FirstArg->getSourceRange(); 3866 return ExprError(); 3867 } 3868 3869 QualType ValType = pointerType->getPointeeType(); 3870 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 3871 !ValType->isBlockPointerType()) { 3872 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr) 3873 << FirstArg->getType() << FirstArg->getSourceRange(); 3874 return ExprError(); 3875 } 3876 3877 if (ValType.isConstQualified()) { 3878 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const) 3879 << FirstArg->getType() << FirstArg->getSourceRange(); 3880 return ExprError(); 3881 } 3882 3883 switch (ValType.getObjCLifetime()) { 3884 case Qualifiers::OCL_None: 3885 case Qualifiers::OCL_ExplicitNone: 3886 // okay 3887 break; 3888 3889 case Qualifiers::OCL_Weak: 3890 case Qualifiers::OCL_Strong: 3891 case Qualifiers::OCL_Autoreleasing: 3892 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership) 3893 << ValType << FirstArg->getSourceRange(); 3894 return ExprError(); 3895 } 3896 3897 // Strip any qualifiers off ValType. 3898 ValType = ValType.getUnqualifiedType(); 3899 3900 // The majority of builtins return a value, but a few have special return 3901 // types, so allow them to override appropriately below. 3902 QualType ResultType = ValType; 3903 3904 // We need to figure out which concrete builtin this maps onto. For example, 3905 // __sync_fetch_and_add with a 2 byte object turns into 3906 // __sync_fetch_and_add_2. 3907 #define BUILTIN_ROW(x) \ 3908 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 3909 Builtin::BI##x##_8, Builtin::BI##x##_16 } 3910 3911 static const unsigned BuiltinIndices[][5] = { 3912 BUILTIN_ROW(__sync_fetch_and_add), 3913 BUILTIN_ROW(__sync_fetch_and_sub), 3914 BUILTIN_ROW(__sync_fetch_and_or), 3915 BUILTIN_ROW(__sync_fetch_and_and), 3916 BUILTIN_ROW(__sync_fetch_and_xor), 3917 BUILTIN_ROW(__sync_fetch_and_nand), 3918 3919 BUILTIN_ROW(__sync_add_and_fetch), 3920 BUILTIN_ROW(__sync_sub_and_fetch), 3921 BUILTIN_ROW(__sync_and_and_fetch), 3922 BUILTIN_ROW(__sync_or_and_fetch), 3923 BUILTIN_ROW(__sync_xor_and_fetch), 3924 BUILTIN_ROW(__sync_nand_and_fetch), 3925 3926 BUILTIN_ROW(__sync_val_compare_and_swap), 3927 BUILTIN_ROW(__sync_bool_compare_and_swap), 3928 BUILTIN_ROW(__sync_lock_test_and_set), 3929 BUILTIN_ROW(__sync_lock_release), 3930 BUILTIN_ROW(__sync_swap) 3931 }; 3932 #undef BUILTIN_ROW 3933 3934 // Determine the index of the size. 3935 unsigned SizeIndex; 3936 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 3937 case 1: SizeIndex = 0; break; 3938 case 2: SizeIndex = 1; break; 3939 case 4: SizeIndex = 2; break; 3940 case 8: SizeIndex = 3; break; 3941 case 16: SizeIndex = 4; break; 3942 default: 3943 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size) 3944 << FirstArg->getType() << FirstArg->getSourceRange(); 3945 return ExprError(); 3946 } 3947 3948 // Each of these builtins has one pointer argument, followed by some number of 3949 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 3950 // that we ignore. Find out which row of BuiltinIndices to read from as well 3951 // as the number of fixed args. 3952 unsigned BuiltinID = FDecl->getBuiltinID(); 3953 unsigned BuiltinIndex, NumFixed = 1; 3954 bool WarnAboutSemanticsChange = false; 3955 switch (BuiltinID) { 3956 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 3957 case Builtin::BI__sync_fetch_and_add: 3958 case Builtin::BI__sync_fetch_and_add_1: 3959 case Builtin::BI__sync_fetch_and_add_2: 3960 case Builtin::BI__sync_fetch_and_add_4: 3961 case Builtin::BI__sync_fetch_and_add_8: 3962 case Builtin::BI__sync_fetch_and_add_16: 3963 BuiltinIndex = 0; 3964 break; 3965 3966 case Builtin::BI__sync_fetch_and_sub: 3967 case Builtin::BI__sync_fetch_and_sub_1: 3968 case Builtin::BI__sync_fetch_and_sub_2: 3969 case Builtin::BI__sync_fetch_and_sub_4: 3970 case Builtin::BI__sync_fetch_and_sub_8: 3971 case Builtin::BI__sync_fetch_and_sub_16: 3972 BuiltinIndex = 1; 3973 break; 3974 3975 case Builtin::BI__sync_fetch_and_or: 3976 case Builtin::BI__sync_fetch_and_or_1: 3977 case Builtin::BI__sync_fetch_and_or_2: 3978 case Builtin::BI__sync_fetch_and_or_4: 3979 case Builtin::BI__sync_fetch_and_or_8: 3980 case Builtin::BI__sync_fetch_and_or_16: 3981 BuiltinIndex = 2; 3982 break; 3983 3984 case Builtin::BI__sync_fetch_and_and: 3985 case Builtin::BI__sync_fetch_and_and_1: 3986 case Builtin::BI__sync_fetch_and_and_2: 3987 case Builtin::BI__sync_fetch_and_and_4: 3988 case Builtin::BI__sync_fetch_and_and_8: 3989 case Builtin::BI__sync_fetch_and_and_16: 3990 BuiltinIndex = 3; 3991 break; 3992 3993 case Builtin::BI__sync_fetch_and_xor: 3994 case Builtin::BI__sync_fetch_and_xor_1: 3995 case Builtin::BI__sync_fetch_and_xor_2: 3996 case Builtin::BI__sync_fetch_and_xor_4: 3997 case Builtin::BI__sync_fetch_and_xor_8: 3998 case Builtin::BI__sync_fetch_and_xor_16: 3999 BuiltinIndex = 4; 4000 break; 4001 4002 case Builtin::BI__sync_fetch_and_nand: 4003 case Builtin::BI__sync_fetch_and_nand_1: 4004 case Builtin::BI__sync_fetch_and_nand_2: 4005 case Builtin::BI__sync_fetch_and_nand_4: 4006 case Builtin::BI__sync_fetch_and_nand_8: 4007 case Builtin::BI__sync_fetch_and_nand_16: 4008 BuiltinIndex = 5; 4009 WarnAboutSemanticsChange = true; 4010 break; 4011 4012 case Builtin::BI__sync_add_and_fetch: 4013 case Builtin::BI__sync_add_and_fetch_1: 4014 case Builtin::BI__sync_add_and_fetch_2: 4015 case Builtin::BI__sync_add_and_fetch_4: 4016 case Builtin::BI__sync_add_and_fetch_8: 4017 case Builtin::BI__sync_add_and_fetch_16: 4018 BuiltinIndex = 6; 4019 break; 4020 4021 case Builtin::BI__sync_sub_and_fetch: 4022 case Builtin::BI__sync_sub_and_fetch_1: 4023 case Builtin::BI__sync_sub_and_fetch_2: 4024 case Builtin::BI__sync_sub_and_fetch_4: 4025 case Builtin::BI__sync_sub_and_fetch_8: 4026 case Builtin::BI__sync_sub_and_fetch_16: 4027 BuiltinIndex = 7; 4028 break; 4029 4030 case Builtin::BI__sync_and_and_fetch: 4031 case Builtin::BI__sync_and_and_fetch_1: 4032 case Builtin::BI__sync_and_and_fetch_2: 4033 case Builtin::BI__sync_and_and_fetch_4: 4034 case Builtin::BI__sync_and_and_fetch_8: 4035 case Builtin::BI__sync_and_and_fetch_16: 4036 BuiltinIndex = 8; 4037 break; 4038 4039 case Builtin::BI__sync_or_and_fetch: 4040 case Builtin::BI__sync_or_and_fetch_1: 4041 case Builtin::BI__sync_or_and_fetch_2: 4042 case Builtin::BI__sync_or_and_fetch_4: 4043 case Builtin::BI__sync_or_and_fetch_8: 4044 case Builtin::BI__sync_or_and_fetch_16: 4045 BuiltinIndex = 9; 4046 break; 4047 4048 case Builtin::BI__sync_xor_and_fetch: 4049 case Builtin::BI__sync_xor_and_fetch_1: 4050 case Builtin::BI__sync_xor_and_fetch_2: 4051 case Builtin::BI__sync_xor_and_fetch_4: 4052 case Builtin::BI__sync_xor_and_fetch_8: 4053 case Builtin::BI__sync_xor_and_fetch_16: 4054 BuiltinIndex = 10; 4055 break; 4056 4057 case Builtin::BI__sync_nand_and_fetch: 4058 case Builtin::BI__sync_nand_and_fetch_1: 4059 case Builtin::BI__sync_nand_and_fetch_2: 4060 case Builtin::BI__sync_nand_and_fetch_4: 4061 case Builtin::BI__sync_nand_and_fetch_8: 4062 case Builtin::BI__sync_nand_and_fetch_16: 4063 BuiltinIndex = 11; 4064 WarnAboutSemanticsChange = true; 4065 break; 4066 4067 case Builtin::BI__sync_val_compare_and_swap: 4068 case Builtin::BI__sync_val_compare_and_swap_1: 4069 case Builtin::BI__sync_val_compare_and_swap_2: 4070 case Builtin::BI__sync_val_compare_and_swap_4: 4071 case Builtin::BI__sync_val_compare_and_swap_8: 4072 case Builtin::BI__sync_val_compare_and_swap_16: 4073 BuiltinIndex = 12; 4074 NumFixed = 2; 4075 break; 4076 4077 case Builtin::BI__sync_bool_compare_and_swap: 4078 case Builtin::BI__sync_bool_compare_and_swap_1: 4079 case Builtin::BI__sync_bool_compare_and_swap_2: 4080 case Builtin::BI__sync_bool_compare_and_swap_4: 4081 case Builtin::BI__sync_bool_compare_and_swap_8: 4082 case Builtin::BI__sync_bool_compare_and_swap_16: 4083 BuiltinIndex = 13; 4084 NumFixed = 2; 4085 ResultType = Context.BoolTy; 4086 break; 4087 4088 case Builtin::BI__sync_lock_test_and_set: 4089 case Builtin::BI__sync_lock_test_and_set_1: 4090 case Builtin::BI__sync_lock_test_and_set_2: 4091 case Builtin::BI__sync_lock_test_and_set_4: 4092 case Builtin::BI__sync_lock_test_and_set_8: 4093 case Builtin::BI__sync_lock_test_and_set_16: 4094 BuiltinIndex = 14; 4095 break; 4096 4097 case Builtin::BI__sync_lock_release: 4098 case Builtin::BI__sync_lock_release_1: 4099 case Builtin::BI__sync_lock_release_2: 4100 case Builtin::BI__sync_lock_release_4: 4101 case Builtin::BI__sync_lock_release_8: 4102 case Builtin::BI__sync_lock_release_16: 4103 BuiltinIndex = 15; 4104 NumFixed = 0; 4105 ResultType = Context.VoidTy; 4106 break; 4107 4108 case Builtin::BI__sync_swap: 4109 case Builtin::BI__sync_swap_1: 4110 case Builtin::BI__sync_swap_2: 4111 case Builtin::BI__sync_swap_4: 4112 case Builtin::BI__sync_swap_8: 4113 case Builtin::BI__sync_swap_16: 4114 BuiltinIndex = 16; 4115 break; 4116 } 4117 4118 // Now that we know how many fixed arguments we expect, first check that we 4119 // have at least that many. 4120 if (TheCall->getNumArgs() < 1+NumFixed) { 4121 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least) 4122 << 0 << 1+NumFixed << TheCall->getNumArgs() 4123 << TheCall->getCallee()->getSourceRange(); 4124 return ExprError(); 4125 } 4126 4127 if (WarnAboutSemanticsChange) { 4128 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change) 4129 << TheCall->getCallee()->getSourceRange(); 4130 } 4131 4132 // Get the decl for the concrete builtin from this, we can tell what the 4133 // concrete integer type we should convert to is. 4134 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4135 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4136 FunctionDecl *NewBuiltinDecl; 4137 if (NewBuiltinID == BuiltinID) 4138 NewBuiltinDecl = FDecl; 4139 else { 4140 // Perform builtin lookup to avoid redeclaring it. 4141 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4142 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName); 4143 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4144 assert(Res.getFoundDecl()); 4145 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4146 if (!NewBuiltinDecl) 4147 return ExprError(); 4148 } 4149 4150 // The first argument --- the pointer --- has a fixed type; we 4151 // deduce the types of the rest of the arguments accordingly. Walk 4152 // the remaining arguments, converting them to the deduced value type. 4153 for (unsigned i = 0; i != NumFixed; ++i) { 4154 ExprResult Arg = TheCall->getArg(i+1); 4155 4156 // GCC does an implicit conversion to the pointer or integer ValType. This 4157 // can fail in some cases (1i -> int**), check for this error case now. 4158 // Initialize the argument. 4159 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4160 ValType, /*consume*/ false); 4161 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4162 if (Arg.isInvalid()) 4163 return ExprError(); 4164 4165 // Okay, we have something that *can* be converted to the right type. Check 4166 // to see if there is a potentially weird extension going on here. This can 4167 // happen when you do an atomic operation on something like an char* and 4168 // pass in 42. The 42 gets converted to char. This is even more strange 4169 // for things like 45.123 -> char, etc. 4170 // FIXME: Do this check. 4171 TheCall->setArg(i+1, Arg.get()); 4172 } 4173 4174 ASTContext& Context = this->getASTContext(); 4175 4176 // Create a new DeclRefExpr to refer to the new decl. 4177 DeclRefExpr* NewDRE = DeclRefExpr::Create( 4178 Context, 4179 DRE->getQualifierLoc(), 4180 SourceLocation(), 4181 NewBuiltinDecl, 4182 /*enclosing*/ false, 4183 DRE->getLocation(), 4184 Context.BuiltinFnTy, 4185 DRE->getValueKind()); 4186 4187 // Set the callee in the CallExpr. 4188 // FIXME: This loses syntactic information. 4189 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 4190 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 4191 CK_BuiltinFnToFnPtr); 4192 TheCall->setCallee(PromotedCall.get()); 4193 4194 // Change the result type of the call to match the original value type. This 4195 // is arbitrary, but the codegen for these builtins ins design to handle it 4196 // gracefully. 4197 TheCall->setType(ResultType); 4198 4199 return TheCallResult; 4200 } 4201 4202 /// SemaBuiltinNontemporalOverloaded - We have a call to 4203 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 4204 /// overloaded function based on the pointer type of its last argument. 4205 /// 4206 /// This function goes through and does final semantic checking for these 4207 /// builtins. 4208 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4209 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4210 DeclRefExpr *DRE = 4211 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4212 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4213 unsigned BuiltinID = FDecl->getBuiltinID(); 4214 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 4215 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 4216 "Unexpected nontemporal load/store builtin!"); 4217 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 4218 unsigned numArgs = isStore ? 2 : 1; 4219 4220 // Ensure that we have the proper number of arguments. 4221 if (checkArgCount(*this, TheCall, numArgs)) 4222 return ExprError(); 4223 4224 // Inspect the last argument of the nontemporal builtin. This should always 4225 // be a pointer type, from which we imply the type of the memory access. 4226 // Because it is a pointer type, we don't have to worry about any implicit 4227 // casts here. 4228 Expr *PointerArg = TheCall->getArg(numArgs - 1); 4229 ExprResult PointerArgResult = 4230 DefaultFunctionArrayLvalueConversion(PointerArg); 4231 4232 if (PointerArgResult.isInvalid()) 4233 return ExprError(); 4234 PointerArg = PointerArgResult.get(); 4235 TheCall->setArg(numArgs - 1, PointerArg); 4236 4237 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 4238 if (!pointerType) { 4239 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer) 4240 << PointerArg->getType() << PointerArg->getSourceRange(); 4241 return ExprError(); 4242 } 4243 4244 QualType ValType = pointerType->getPointeeType(); 4245 4246 // Strip any qualifiers off ValType. 4247 ValType = ValType.getUnqualifiedType(); 4248 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4249 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 4250 !ValType->isVectorType()) { 4251 Diag(DRE->getLocStart(), 4252 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 4253 << PointerArg->getType() << PointerArg->getSourceRange(); 4254 return ExprError(); 4255 } 4256 4257 if (!isStore) { 4258 TheCall->setType(ValType); 4259 return TheCallResult; 4260 } 4261 4262 ExprResult ValArg = TheCall->getArg(0); 4263 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4264 Context, ValType, /*consume*/ false); 4265 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 4266 if (ValArg.isInvalid()) 4267 return ExprError(); 4268 4269 TheCall->setArg(0, ValArg.get()); 4270 TheCall->setType(Context.VoidTy); 4271 return TheCallResult; 4272 } 4273 4274 /// CheckObjCString - Checks that the argument to the builtin 4275 /// CFString constructor is correct 4276 /// Note: It might also make sense to do the UTF-16 conversion here (would 4277 /// simplify the backend). 4278 bool Sema::CheckObjCString(Expr *Arg) { 4279 Arg = Arg->IgnoreParenCasts(); 4280 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 4281 4282 if (!Literal || !Literal->isAscii()) { 4283 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant) 4284 << Arg->getSourceRange(); 4285 return true; 4286 } 4287 4288 if (Literal->containsNonAsciiOrNull()) { 4289 StringRef String = Literal->getString(); 4290 unsigned NumBytes = String.size(); 4291 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 4292 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4293 llvm::UTF16 *ToPtr = &ToBuf[0]; 4294 4295 llvm::ConversionResult Result = 4296 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4297 ToPtr + NumBytes, llvm::strictConversion); 4298 // Check for conversion failure. 4299 if (Result != llvm::conversionOK) 4300 Diag(Arg->getLocStart(), 4301 diag::warn_cfstring_truncated) << Arg->getSourceRange(); 4302 } 4303 return false; 4304 } 4305 4306 /// CheckObjCString - Checks that the format string argument to the os_log() 4307 /// and os_trace() functions is correct, and converts it to const char *. 4308 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 4309 Arg = Arg->IgnoreParenCasts(); 4310 auto *Literal = dyn_cast<StringLiteral>(Arg); 4311 if (!Literal) { 4312 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 4313 Literal = ObjcLiteral->getString(); 4314 } 4315 } 4316 4317 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 4318 return ExprError( 4319 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant) 4320 << Arg->getSourceRange()); 4321 } 4322 4323 ExprResult Result(Literal); 4324 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 4325 InitializedEntity Entity = 4326 InitializedEntity::InitializeParameter(Context, ResultTy, false); 4327 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 4328 return Result; 4329 } 4330 4331 /// Check that the user is calling the appropriate va_start builtin for the 4332 /// target and calling convention. 4333 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 4334 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 4335 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 4336 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 4337 bool IsWindows = TT.isOSWindows(); 4338 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 4339 if (IsX64 || IsAArch64) { 4340 CallingConv CC = CC_C; 4341 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 4342 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 4343 if (IsMSVAStart) { 4344 // Don't allow this in System V ABI functions. 4345 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 4346 return S.Diag(Fn->getLocStart(), 4347 diag::err_ms_va_start_used_in_sysv_function); 4348 } else { 4349 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 4350 // On x64 Windows, don't allow this in System V ABI functions. 4351 // (Yes, that means there's no corresponding way to support variadic 4352 // System V ABI functions on Windows.) 4353 if ((IsWindows && CC == CC_X86_64SysV) || 4354 (!IsWindows && CC == CC_Win64)) 4355 return S.Diag(Fn->getLocStart(), 4356 diag::err_va_start_used_in_wrong_abi_function) 4357 << !IsWindows; 4358 } 4359 return false; 4360 } 4361 4362 if (IsMSVAStart) 4363 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only); 4364 return false; 4365 } 4366 4367 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 4368 ParmVarDecl **LastParam = nullptr) { 4369 // Determine whether the current function, block, or obj-c method is variadic 4370 // and get its parameter list. 4371 bool IsVariadic = false; 4372 ArrayRef<ParmVarDecl *> Params; 4373 DeclContext *Caller = S.CurContext; 4374 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 4375 IsVariadic = Block->isVariadic(); 4376 Params = Block->parameters(); 4377 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 4378 IsVariadic = FD->isVariadic(); 4379 Params = FD->parameters(); 4380 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 4381 IsVariadic = MD->isVariadic(); 4382 // FIXME: This isn't correct for methods (results in bogus warning). 4383 Params = MD->parameters(); 4384 } else if (isa<CapturedDecl>(Caller)) { 4385 // We don't support va_start in a CapturedDecl. 4386 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt); 4387 return true; 4388 } else { 4389 // This must be some other declcontext that parses exprs. 4390 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function); 4391 return true; 4392 } 4393 4394 if (!IsVariadic) { 4395 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function); 4396 return true; 4397 } 4398 4399 if (LastParam) 4400 *LastParam = Params.empty() ? nullptr : Params.back(); 4401 4402 return false; 4403 } 4404 4405 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 4406 /// for validity. Emit an error and return true on failure; return false 4407 /// on success. 4408 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 4409 Expr *Fn = TheCall->getCallee(); 4410 4411 if (checkVAStartABI(*this, BuiltinID, Fn)) 4412 return true; 4413 4414 if (TheCall->getNumArgs() > 2) { 4415 Diag(TheCall->getArg(2)->getLocStart(), 4416 diag::err_typecheck_call_too_many_args) 4417 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4418 << Fn->getSourceRange() 4419 << SourceRange(TheCall->getArg(2)->getLocStart(), 4420 (*(TheCall->arg_end()-1))->getLocEnd()); 4421 return true; 4422 } 4423 4424 if (TheCall->getNumArgs() < 2) { 4425 return Diag(TheCall->getLocEnd(), 4426 diag::err_typecheck_call_too_few_args_at_least) 4427 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 4428 } 4429 4430 // Type-check the first argument normally. 4431 if (checkBuiltinArgument(*this, TheCall, 0)) 4432 return true; 4433 4434 // Check that the current function is variadic, and get its last parameter. 4435 ParmVarDecl *LastParam; 4436 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 4437 return true; 4438 4439 // Verify that the second argument to the builtin is the last argument of the 4440 // current function or method. 4441 bool SecondArgIsLastNamedArgument = false; 4442 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 4443 4444 // These are valid if SecondArgIsLastNamedArgument is false after the next 4445 // block. 4446 QualType Type; 4447 SourceLocation ParamLoc; 4448 bool IsCRegister = false; 4449 4450 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 4451 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 4452 SecondArgIsLastNamedArgument = PV == LastParam; 4453 4454 Type = PV->getType(); 4455 ParamLoc = PV->getLocation(); 4456 IsCRegister = 4457 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 4458 } 4459 } 4460 4461 if (!SecondArgIsLastNamedArgument) 4462 Diag(TheCall->getArg(1)->getLocStart(), 4463 diag::warn_second_arg_of_va_start_not_last_named_param); 4464 else if (IsCRegister || Type->isReferenceType() || 4465 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 4466 // Promotable integers are UB, but enumerations need a bit of 4467 // extra checking to see what their promotable type actually is. 4468 if (!Type->isPromotableIntegerType()) 4469 return false; 4470 if (!Type->isEnumeralType()) 4471 return true; 4472 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 4473 return !(ED && 4474 Context.typesAreCompatible(ED->getPromotionType(), Type)); 4475 }()) { 4476 unsigned Reason = 0; 4477 if (Type->isReferenceType()) Reason = 1; 4478 else if (IsCRegister) Reason = 2; 4479 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason; 4480 Diag(ParamLoc, diag::note_parameter_type) << Type; 4481 } 4482 4483 TheCall->setType(Context.VoidTy); 4484 return false; 4485 } 4486 4487 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 4488 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 4489 // const char *named_addr); 4490 4491 Expr *Func = Call->getCallee(); 4492 4493 if (Call->getNumArgs() < 3) 4494 return Diag(Call->getLocEnd(), 4495 diag::err_typecheck_call_too_few_args_at_least) 4496 << 0 /*function call*/ << 3 << Call->getNumArgs(); 4497 4498 // Type-check the first argument normally. 4499 if (checkBuiltinArgument(*this, Call, 0)) 4500 return true; 4501 4502 // Check that the current function is variadic. 4503 if (checkVAStartIsInVariadicFunction(*this, Func)) 4504 return true; 4505 4506 // __va_start on Windows does not validate the parameter qualifiers 4507 4508 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4509 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4510 4511 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4512 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4513 4514 const QualType &ConstCharPtrTy = 4515 Context.getPointerType(Context.CharTy.withConst()); 4516 if (!Arg1Ty->isPointerType() || 4517 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 4518 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible) 4519 << Arg1->getType() << ConstCharPtrTy 4520 << 1 /* different class */ 4521 << 0 /* qualifier difference */ 4522 << 3 /* parameter mismatch */ 4523 << 2 << Arg1->getType() << ConstCharPtrTy; 4524 4525 const QualType SizeTy = Context.getSizeType(); 4526 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4527 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible) 4528 << Arg2->getType() << SizeTy 4529 << 1 /* different class */ 4530 << 0 /* qualifier difference */ 4531 << 3 /* parameter mismatch */ 4532 << 3 << Arg2->getType() << SizeTy; 4533 4534 return false; 4535 } 4536 4537 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 4538 /// friends. This is declared to take (...), so we have to check everything. 4539 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 4540 if (TheCall->getNumArgs() < 2) 4541 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4542 << 0 << 2 << TheCall->getNumArgs()/*function call*/; 4543 if (TheCall->getNumArgs() > 2) 4544 return Diag(TheCall->getArg(2)->getLocStart(), 4545 diag::err_typecheck_call_too_many_args) 4546 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4547 << SourceRange(TheCall->getArg(2)->getLocStart(), 4548 (*(TheCall->arg_end()-1))->getLocEnd()); 4549 4550 ExprResult OrigArg0 = TheCall->getArg(0); 4551 ExprResult OrigArg1 = TheCall->getArg(1); 4552 4553 // Do standard promotions between the two arguments, returning their common 4554 // type. 4555 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 4556 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4557 return true; 4558 4559 // Make sure any conversions are pushed back into the call; this is 4560 // type safe since unordered compare builtins are declared as "_Bool 4561 // foo(...)". 4562 TheCall->setArg(0, OrigArg0.get()); 4563 TheCall->setArg(1, OrigArg1.get()); 4564 4565 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4566 return false; 4567 4568 // If the common type isn't a real floating type, then the arguments were 4569 // invalid for this operation. 4570 if (Res.isNull() || !Res->isRealFloatingType()) 4571 return Diag(OrigArg0.get()->getLocStart(), 4572 diag::err_typecheck_call_invalid_ordered_compare) 4573 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4574 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd()); 4575 4576 return false; 4577 } 4578 4579 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 4580 /// __builtin_isnan and friends. This is declared to take (...), so we have 4581 /// to check everything. We expect the last argument to be a floating point 4582 /// value. 4583 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 4584 if (TheCall->getNumArgs() < NumArgs) 4585 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4586 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/; 4587 if (TheCall->getNumArgs() > NumArgs) 4588 return Diag(TheCall->getArg(NumArgs)->getLocStart(), 4589 diag::err_typecheck_call_too_many_args) 4590 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 4591 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(), 4592 (*(TheCall->arg_end()-1))->getLocEnd()); 4593 4594 Expr *OrigArg = TheCall->getArg(NumArgs-1); 4595 4596 if (OrigArg->isTypeDependent()) 4597 return false; 4598 4599 // This operation requires a non-_Complex floating-point number. 4600 if (!OrigArg->getType()->isRealFloatingType()) 4601 return Diag(OrigArg->getLocStart(), 4602 diag::err_typecheck_call_invalid_unary_fp) 4603 << OrigArg->getType() << OrigArg->getSourceRange(); 4604 4605 // If this is an implicit conversion from float -> float, double, or 4606 // long double, remove it. 4607 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 4608 // Only remove standard FloatCasts, leaving other casts inplace 4609 if (Cast->getCastKind() == CK_FloatingCast) { 4610 Expr *CastArg = Cast->getSubExpr(); 4611 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 4612 assert( 4613 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 4614 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 4615 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 4616 "promotion from float to either float, double, or long double is " 4617 "the only expected cast here"); 4618 Cast->setSubExpr(nullptr); 4619 TheCall->setArg(NumArgs-1, CastArg); 4620 } 4621 } 4622 } 4623 4624 return false; 4625 } 4626 4627 // Customized Sema Checking for VSX builtins that have the following signature: 4628 // vector [...] builtinName(vector [...], vector [...], const int); 4629 // Which takes the same type of vectors (any legal vector type) for the first 4630 // two arguments and takes compile time constant for the third argument. 4631 // Example builtins are : 4632 // vector double vec_xxpermdi(vector double, vector double, int); 4633 // vector short vec_xxsldwi(vector short, vector short, int); 4634 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 4635 unsigned ExpectedNumArgs = 3; 4636 if (TheCall->getNumArgs() < ExpectedNumArgs) 4637 return Diag(TheCall->getLocEnd(), 4638 diag::err_typecheck_call_too_few_args_at_least) 4639 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4640 << TheCall->getSourceRange(); 4641 4642 if (TheCall->getNumArgs() > ExpectedNumArgs) 4643 return Diag(TheCall->getLocEnd(), 4644 diag::err_typecheck_call_too_many_args_at_most) 4645 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 4646 << TheCall->getSourceRange(); 4647 4648 // Check the third argument is a compile time constant 4649 llvm::APSInt Value; 4650 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 4651 return Diag(TheCall->getLocStart(), 4652 diag::err_vsx_builtin_nonconstant_argument) 4653 << 3 /* argument index */ << TheCall->getDirectCallee() 4654 << SourceRange(TheCall->getArg(2)->getLocStart(), 4655 TheCall->getArg(2)->getLocEnd()); 4656 4657 QualType Arg1Ty = TheCall->getArg(0)->getType(); 4658 QualType Arg2Ty = TheCall->getArg(1)->getType(); 4659 4660 // Check the type of argument 1 and argument 2 are vectors. 4661 SourceLocation BuiltinLoc = TheCall->getLocStart(); 4662 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 4663 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 4664 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 4665 << TheCall->getDirectCallee() 4666 << SourceRange(TheCall->getArg(0)->getLocStart(), 4667 TheCall->getArg(1)->getLocEnd()); 4668 } 4669 4670 // Check the first two arguments are the same type. 4671 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 4672 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 4673 << TheCall->getDirectCallee() 4674 << SourceRange(TheCall->getArg(0)->getLocStart(), 4675 TheCall->getArg(1)->getLocEnd()); 4676 } 4677 4678 // When default clang type checking is turned off and the customized type 4679 // checking is used, the returning type of the function must be explicitly 4680 // set. Otherwise it is _Bool by default. 4681 TheCall->setType(Arg1Ty); 4682 4683 return false; 4684 } 4685 4686 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 4687 // This is declared to take (...), so we have to check everything. 4688 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 4689 if (TheCall->getNumArgs() < 2) 4690 return ExprError(Diag(TheCall->getLocEnd(), 4691 diag::err_typecheck_call_too_few_args_at_least) 4692 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 4693 << TheCall->getSourceRange()); 4694 4695 // Determine which of the following types of shufflevector we're checking: 4696 // 1) unary, vector mask: (lhs, mask) 4697 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 4698 QualType resType = TheCall->getArg(0)->getType(); 4699 unsigned numElements = 0; 4700 4701 if (!TheCall->getArg(0)->isTypeDependent() && 4702 !TheCall->getArg(1)->isTypeDependent()) { 4703 QualType LHSType = TheCall->getArg(0)->getType(); 4704 QualType RHSType = TheCall->getArg(1)->getType(); 4705 4706 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 4707 return ExprError(Diag(TheCall->getLocStart(), 4708 diag::err_vec_builtin_non_vector) 4709 << TheCall->getDirectCallee() 4710 << SourceRange(TheCall->getArg(0)->getLocStart(), 4711 TheCall->getArg(1)->getLocEnd())); 4712 4713 numElements = LHSType->getAs<VectorType>()->getNumElements(); 4714 unsigned numResElements = TheCall->getNumArgs() - 2; 4715 4716 // Check to see if we have a call with 2 vector arguments, the unary shuffle 4717 // with mask. If so, verify that RHS is an integer vector type with the 4718 // same number of elts as lhs. 4719 if (TheCall->getNumArgs() == 2) { 4720 if (!RHSType->hasIntegerRepresentation() || 4721 RHSType->getAs<VectorType>()->getNumElements() != numElements) 4722 return ExprError(Diag(TheCall->getLocStart(), 4723 diag::err_vec_builtin_incompatible_vector) 4724 << TheCall->getDirectCallee() 4725 << SourceRange(TheCall->getArg(1)->getLocStart(), 4726 TheCall->getArg(1)->getLocEnd())); 4727 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 4728 return ExprError(Diag(TheCall->getLocStart(), 4729 diag::err_vec_builtin_incompatible_vector) 4730 << TheCall->getDirectCallee() 4731 << SourceRange(TheCall->getArg(0)->getLocStart(), 4732 TheCall->getArg(1)->getLocEnd())); 4733 } else if (numElements != numResElements) { 4734 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 4735 resType = Context.getVectorType(eltType, numResElements, 4736 VectorType::GenericVector); 4737 } 4738 } 4739 4740 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 4741 if (TheCall->getArg(i)->isTypeDependent() || 4742 TheCall->getArg(i)->isValueDependent()) 4743 continue; 4744 4745 llvm::APSInt Result(32); 4746 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 4747 return ExprError(Diag(TheCall->getLocStart(), 4748 diag::err_shufflevector_nonconstant_argument) 4749 << TheCall->getArg(i)->getSourceRange()); 4750 4751 // Allow -1 which will be translated to undef in the IR. 4752 if (Result.isSigned() && Result.isAllOnesValue()) 4753 continue; 4754 4755 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 4756 return ExprError(Diag(TheCall->getLocStart(), 4757 diag::err_shufflevector_argument_too_large) 4758 << TheCall->getArg(i)->getSourceRange()); 4759 } 4760 4761 SmallVector<Expr*, 32> exprs; 4762 4763 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 4764 exprs.push_back(TheCall->getArg(i)); 4765 TheCall->setArg(i, nullptr); 4766 } 4767 4768 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 4769 TheCall->getCallee()->getLocStart(), 4770 TheCall->getRParenLoc()); 4771 } 4772 4773 /// SemaConvertVectorExpr - Handle __builtin_convertvector 4774 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 4775 SourceLocation BuiltinLoc, 4776 SourceLocation RParenLoc) { 4777 ExprValueKind VK = VK_RValue; 4778 ExprObjectKind OK = OK_Ordinary; 4779 QualType DstTy = TInfo->getType(); 4780 QualType SrcTy = E->getType(); 4781 4782 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 4783 return ExprError(Diag(BuiltinLoc, 4784 diag::err_convertvector_non_vector) 4785 << E->getSourceRange()); 4786 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 4787 return ExprError(Diag(BuiltinLoc, 4788 diag::err_convertvector_non_vector_type)); 4789 4790 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 4791 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 4792 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 4793 if (SrcElts != DstElts) 4794 return ExprError(Diag(BuiltinLoc, 4795 diag::err_convertvector_incompatible_vector) 4796 << E->getSourceRange()); 4797 } 4798 4799 return new (Context) 4800 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4801 } 4802 4803 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 4804 // This is declared to take (const void*, ...) and can take two 4805 // optional constant int args. 4806 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 4807 unsigned NumArgs = TheCall->getNumArgs(); 4808 4809 if (NumArgs > 3) 4810 return Diag(TheCall->getLocEnd(), 4811 diag::err_typecheck_call_too_many_args_at_most) 4812 << 0 /*function call*/ << 3 << NumArgs 4813 << TheCall->getSourceRange(); 4814 4815 // Argument 0 is checked for us and the remaining arguments must be 4816 // constant integers. 4817 for (unsigned i = 1; i != NumArgs; ++i) 4818 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 4819 return true; 4820 4821 return false; 4822 } 4823 4824 /// SemaBuiltinAssume - Handle __assume (MS Extension). 4825 // __assume does not evaluate its arguments, and should warn if its argument 4826 // has side effects. 4827 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 4828 Expr *Arg = TheCall->getArg(0); 4829 if (Arg->isInstantiationDependent()) return false; 4830 4831 if (Arg->HasSideEffects(Context)) 4832 Diag(Arg->getLocStart(), diag::warn_assume_side_effects) 4833 << Arg->getSourceRange() 4834 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 4835 4836 return false; 4837 } 4838 4839 /// Handle __builtin_alloca_with_align. This is declared 4840 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 4841 /// than 8. 4842 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 4843 // The alignment must be a constant integer. 4844 Expr *Arg = TheCall->getArg(1); 4845 4846 // We can't check the value of a dependent argument. 4847 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4848 if (const auto *UE = 4849 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 4850 if (UE->getKind() == UETT_AlignOf) 4851 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof) 4852 << Arg->getSourceRange(); 4853 4854 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 4855 4856 if (!Result.isPowerOf2()) 4857 return Diag(TheCall->getLocStart(), 4858 diag::err_alignment_not_power_of_two) 4859 << Arg->getSourceRange(); 4860 4861 if (Result < Context.getCharWidth()) 4862 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small) 4863 << (unsigned)Context.getCharWidth() 4864 << Arg->getSourceRange(); 4865 4866 if (Result > std::numeric_limits<int32_t>::max()) 4867 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big) 4868 << std::numeric_limits<int32_t>::max() 4869 << Arg->getSourceRange(); 4870 } 4871 4872 return false; 4873 } 4874 4875 /// Handle __builtin_assume_aligned. This is declared 4876 /// as (const void*, size_t, ...) and can take one optional constant int arg. 4877 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 4878 unsigned NumArgs = TheCall->getNumArgs(); 4879 4880 if (NumArgs > 3) 4881 return Diag(TheCall->getLocEnd(), 4882 diag::err_typecheck_call_too_many_args_at_most) 4883 << 0 /*function call*/ << 3 << NumArgs 4884 << TheCall->getSourceRange(); 4885 4886 // The alignment must be a constant integer. 4887 Expr *Arg = TheCall->getArg(1); 4888 4889 // We can't check the value of a dependent argument. 4890 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 4891 llvm::APSInt Result; 4892 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 4893 return true; 4894 4895 if (!Result.isPowerOf2()) 4896 return Diag(TheCall->getLocStart(), 4897 diag::err_alignment_not_power_of_two) 4898 << Arg->getSourceRange(); 4899 } 4900 4901 if (NumArgs > 2) { 4902 ExprResult Arg(TheCall->getArg(2)); 4903 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4904 Context.getSizeType(), false); 4905 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4906 if (Arg.isInvalid()) return true; 4907 TheCall->setArg(2, Arg.get()); 4908 } 4909 4910 return false; 4911 } 4912 4913 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 4914 unsigned BuiltinID = 4915 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 4916 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 4917 4918 unsigned NumArgs = TheCall->getNumArgs(); 4919 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 4920 if (NumArgs < NumRequiredArgs) { 4921 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args) 4922 << 0 /* function call */ << NumRequiredArgs << NumArgs 4923 << TheCall->getSourceRange(); 4924 } 4925 if (NumArgs >= NumRequiredArgs + 0x100) { 4926 return Diag(TheCall->getLocEnd(), 4927 diag::err_typecheck_call_too_many_args_at_most) 4928 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 4929 << TheCall->getSourceRange(); 4930 } 4931 unsigned i = 0; 4932 4933 // For formatting call, check buffer arg. 4934 if (!IsSizeCall) { 4935 ExprResult Arg(TheCall->getArg(i)); 4936 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4937 Context, Context.VoidPtrTy, false); 4938 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4939 if (Arg.isInvalid()) 4940 return true; 4941 TheCall->setArg(i, Arg.get()); 4942 i++; 4943 } 4944 4945 // Check string literal arg. 4946 unsigned FormatIdx = i; 4947 { 4948 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 4949 if (Arg.isInvalid()) 4950 return true; 4951 TheCall->setArg(i, Arg.get()); 4952 i++; 4953 } 4954 4955 // Make sure variadic args are scalar. 4956 unsigned FirstDataArg = i; 4957 while (i < NumArgs) { 4958 ExprResult Arg = DefaultVariadicArgumentPromotion( 4959 TheCall->getArg(i), VariadicFunction, nullptr); 4960 if (Arg.isInvalid()) 4961 return true; 4962 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 4963 if (ArgSize.getQuantity() >= 0x100) { 4964 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big) 4965 << i << (int)ArgSize.getQuantity() << 0xff 4966 << TheCall->getSourceRange(); 4967 } 4968 TheCall->setArg(i, Arg.get()); 4969 i++; 4970 } 4971 4972 // Check formatting specifiers. NOTE: We're only doing this for the non-size 4973 // call to avoid duplicate diagnostics. 4974 if (!IsSizeCall) { 4975 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 4976 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 4977 bool Success = CheckFormatArguments( 4978 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 4979 VariadicFunction, TheCall->getLocStart(), SourceRange(), 4980 CheckedVarArgs); 4981 if (!Success) 4982 return true; 4983 } 4984 4985 if (IsSizeCall) { 4986 TheCall->setType(Context.getSizeType()); 4987 } else { 4988 TheCall->setType(Context.VoidPtrTy); 4989 } 4990 return false; 4991 } 4992 4993 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 4994 /// TheCall is a constant expression. 4995 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 4996 llvm::APSInt &Result) { 4997 Expr *Arg = TheCall->getArg(ArgNum); 4998 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4999 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5000 5001 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5002 5003 if (!Arg->isIntegerConstantExpr(Result, Context)) 5004 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type) 5005 << FDecl->getDeclName() << Arg->getSourceRange(); 5006 5007 return false; 5008 } 5009 5010 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5011 /// TheCall is a constant expression in the range [Low, High]. 5012 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5013 int Low, int High, bool RangeIsError) { 5014 llvm::APSInt Result; 5015 5016 // We can't check the value of a dependent argument. 5017 Expr *Arg = TheCall->getArg(ArgNum); 5018 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5019 return false; 5020 5021 // Check constant-ness first. 5022 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5023 return true; 5024 5025 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5026 if (RangeIsError) 5027 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range) 5028 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5029 else 5030 // Defer the warning until we know if the code will be emitted so that 5031 // dead code can ignore this. 5032 DiagRuntimeBehavior(TheCall->getLocStart(), TheCall, 5033 PDiag(diag::warn_argument_invalid_range) 5034 << Result.toString(10) << Low << High 5035 << Arg->getSourceRange()); 5036 } 5037 5038 return false; 5039 } 5040 5041 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5042 /// TheCall is a constant expression is a multiple of Num.. 5043 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5044 unsigned Num) { 5045 llvm::APSInt Result; 5046 5047 // We can't check the value of a dependent argument. 5048 Expr *Arg = TheCall->getArg(ArgNum); 5049 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5050 return false; 5051 5052 // Check constant-ness first. 5053 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5054 return true; 5055 5056 if (Result.getSExtValue() % Num != 0) 5057 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple) 5058 << Num << Arg->getSourceRange(); 5059 5060 return false; 5061 } 5062 5063 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5064 /// TheCall is an ARM/AArch64 special register string literal. 5065 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5066 int ArgNum, unsigned ExpectedFieldNum, 5067 bool AllowName) { 5068 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5069 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5070 BuiltinID == ARM::BI__builtin_arm_rsr || 5071 BuiltinID == ARM::BI__builtin_arm_rsrp || 5072 BuiltinID == ARM::BI__builtin_arm_wsr || 5073 BuiltinID == ARM::BI__builtin_arm_wsrp; 5074 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5075 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5076 BuiltinID == AArch64::BI__builtin_arm_rsr || 5077 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5078 BuiltinID == AArch64::BI__builtin_arm_wsr || 5079 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5080 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5081 5082 // We can't check the value of a dependent argument. 5083 Expr *Arg = TheCall->getArg(ArgNum); 5084 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5085 return false; 5086 5087 // Check if the argument is a string literal. 5088 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5089 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal) 5090 << Arg->getSourceRange(); 5091 5092 // Check the type of special register given. 5093 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 5094 SmallVector<StringRef, 6> Fields; 5095 Reg.split(Fields, ":"); 5096 5097 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 5098 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 5099 << Arg->getSourceRange(); 5100 5101 // If the string is the name of a register then we cannot check that it is 5102 // valid here but if the string is of one the forms described in ACLE then we 5103 // can check that the supplied fields are integers and within the valid 5104 // ranges. 5105 if (Fields.size() > 1) { 5106 bool FiveFields = Fields.size() == 5; 5107 5108 bool ValidString = true; 5109 if (IsARMBuiltin) { 5110 ValidString &= Fields[0].startswith_lower("cp") || 5111 Fields[0].startswith_lower("p"); 5112 if (ValidString) 5113 Fields[0] = 5114 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 5115 5116 ValidString &= Fields[2].startswith_lower("c"); 5117 if (ValidString) 5118 Fields[2] = Fields[2].drop_front(1); 5119 5120 if (FiveFields) { 5121 ValidString &= Fields[3].startswith_lower("c"); 5122 if (ValidString) 5123 Fields[3] = Fields[3].drop_front(1); 5124 } 5125 } 5126 5127 SmallVector<int, 5> Ranges; 5128 if (FiveFields) 5129 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 5130 else 5131 Ranges.append({15, 7, 15}); 5132 5133 for (unsigned i=0; i<Fields.size(); ++i) { 5134 int IntField; 5135 ValidString &= !Fields[i].getAsInteger(10, IntField); 5136 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 5137 } 5138 5139 if (!ValidString) 5140 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg) 5141 << Arg->getSourceRange(); 5142 } else if (IsAArch64Builtin && Fields.size() == 1) { 5143 // If the register name is one of those that appear in the condition below 5144 // and the special register builtin being used is one of the write builtins, 5145 // then we require that the argument provided for writing to the register 5146 // is an integer constant expression. This is because it will be lowered to 5147 // an MSR (immediate) instruction, so we need to know the immediate at 5148 // compile time. 5149 if (TheCall->getNumArgs() != 2) 5150 return false; 5151 5152 std::string RegLower = Reg.lower(); 5153 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 5154 RegLower != "pan" && RegLower != "uao") 5155 return false; 5156 5157 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 5158 } 5159 5160 return false; 5161 } 5162 5163 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 5164 /// This checks that the target supports __builtin_longjmp and 5165 /// that val is a constant 1. 5166 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 5167 if (!Context.getTargetInfo().hasSjLjLowering()) 5168 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported) 5169 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 5170 5171 Expr *Arg = TheCall->getArg(1); 5172 llvm::APSInt Result; 5173 5174 // TODO: This is less than ideal. Overload this to take a value. 5175 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5176 return true; 5177 5178 if (Result != 1) 5179 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val) 5180 << SourceRange(Arg->getLocStart(), Arg->getLocEnd()); 5181 5182 return false; 5183 } 5184 5185 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 5186 /// This checks that the target supports __builtin_setjmp. 5187 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 5188 if (!Context.getTargetInfo().hasSjLjLowering()) 5189 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported) 5190 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd()); 5191 return false; 5192 } 5193 5194 namespace { 5195 5196 class UncoveredArgHandler { 5197 enum { Unknown = -1, AllCovered = -2 }; 5198 5199 signed FirstUncoveredArg = Unknown; 5200 SmallVector<const Expr *, 4> DiagnosticExprs; 5201 5202 public: 5203 UncoveredArgHandler() = default; 5204 5205 bool hasUncoveredArg() const { 5206 return (FirstUncoveredArg >= 0); 5207 } 5208 5209 unsigned getUncoveredArg() const { 5210 assert(hasUncoveredArg() && "no uncovered argument"); 5211 return FirstUncoveredArg; 5212 } 5213 5214 void setAllCovered() { 5215 // A string has been found with all arguments covered, so clear out 5216 // the diagnostics. 5217 DiagnosticExprs.clear(); 5218 FirstUncoveredArg = AllCovered; 5219 } 5220 5221 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 5222 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 5223 5224 // Don't update if a previous string covers all arguments. 5225 if (FirstUncoveredArg == AllCovered) 5226 return; 5227 5228 // UncoveredArgHandler tracks the highest uncovered argument index 5229 // and with it all the strings that match this index. 5230 if (NewFirstUncoveredArg == FirstUncoveredArg) 5231 DiagnosticExprs.push_back(StrExpr); 5232 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 5233 DiagnosticExprs.clear(); 5234 DiagnosticExprs.push_back(StrExpr); 5235 FirstUncoveredArg = NewFirstUncoveredArg; 5236 } 5237 } 5238 5239 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 5240 }; 5241 5242 enum StringLiteralCheckType { 5243 SLCT_NotALiteral, 5244 SLCT_UncheckedLiteral, 5245 SLCT_CheckedLiteral 5246 }; 5247 5248 } // namespace 5249 5250 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 5251 BinaryOperatorKind BinOpKind, 5252 bool AddendIsRight) { 5253 unsigned BitWidth = Offset.getBitWidth(); 5254 unsigned AddendBitWidth = Addend.getBitWidth(); 5255 // There might be negative interim results. 5256 if (Addend.isUnsigned()) { 5257 Addend = Addend.zext(++AddendBitWidth); 5258 Addend.setIsSigned(true); 5259 } 5260 // Adjust the bit width of the APSInts. 5261 if (AddendBitWidth > BitWidth) { 5262 Offset = Offset.sext(AddendBitWidth); 5263 BitWidth = AddendBitWidth; 5264 } else if (BitWidth > AddendBitWidth) { 5265 Addend = Addend.sext(BitWidth); 5266 } 5267 5268 bool Ov = false; 5269 llvm::APSInt ResOffset = Offset; 5270 if (BinOpKind == BO_Add) 5271 ResOffset = Offset.sadd_ov(Addend, Ov); 5272 else { 5273 assert(AddendIsRight && BinOpKind == BO_Sub && 5274 "operator must be add or sub with addend on the right"); 5275 ResOffset = Offset.ssub_ov(Addend, Ov); 5276 } 5277 5278 // We add an offset to a pointer here so we should support an offset as big as 5279 // possible. 5280 if (Ov) { 5281 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 5282 "index (intermediate) result too big"); 5283 Offset = Offset.sext(2 * BitWidth); 5284 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 5285 return; 5286 } 5287 5288 Offset = ResOffset; 5289 } 5290 5291 namespace { 5292 5293 // This is a wrapper class around StringLiteral to support offsetted string 5294 // literals as format strings. It takes the offset into account when returning 5295 // the string and its length or the source locations to display notes correctly. 5296 class FormatStringLiteral { 5297 const StringLiteral *FExpr; 5298 int64_t Offset; 5299 5300 public: 5301 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 5302 : FExpr(fexpr), Offset(Offset) {} 5303 5304 StringRef getString() const { 5305 return FExpr->getString().drop_front(Offset); 5306 } 5307 5308 unsigned getByteLength() const { 5309 return FExpr->getByteLength() - getCharByteWidth() * Offset; 5310 } 5311 5312 unsigned getLength() const { return FExpr->getLength() - Offset; } 5313 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 5314 5315 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 5316 5317 QualType getType() const { return FExpr->getType(); } 5318 5319 bool isAscii() const { return FExpr->isAscii(); } 5320 bool isWide() const { return FExpr->isWide(); } 5321 bool isUTF8() const { return FExpr->isUTF8(); } 5322 bool isUTF16() const { return FExpr->isUTF16(); } 5323 bool isUTF32() const { return FExpr->isUTF32(); } 5324 bool isPascal() const { return FExpr->isPascal(); } 5325 5326 SourceLocation getLocationOfByte( 5327 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 5328 const TargetInfo &Target, unsigned *StartToken = nullptr, 5329 unsigned *StartTokenByteOffset = nullptr) const { 5330 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 5331 StartToken, StartTokenByteOffset); 5332 } 5333 5334 SourceLocation getLocStart() const LLVM_READONLY { 5335 return FExpr->getLocStart().getLocWithOffset(Offset); 5336 } 5337 5338 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); } 5339 }; 5340 5341 } // namespace 5342 5343 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 5344 const Expr *OrigFormatExpr, 5345 ArrayRef<const Expr *> Args, 5346 bool HasVAListArg, unsigned format_idx, 5347 unsigned firstDataArg, 5348 Sema::FormatStringType Type, 5349 bool inFunctionCall, 5350 Sema::VariadicCallType CallType, 5351 llvm::SmallBitVector &CheckedVarArgs, 5352 UncoveredArgHandler &UncoveredArg); 5353 5354 // Determine if an expression is a string literal or constant string. 5355 // If this function returns false on the arguments to a function expecting a 5356 // format string, we will usually need to emit a warning. 5357 // True string literals are then checked by CheckFormatString. 5358 static StringLiteralCheckType 5359 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 5360 bool HasVAListArg, unsigned format_idx, 5361 unsigned firstDataArg, Sema::FormatStringType Type, 5362 Sema::VariadicCallType CallType, bool InFunctionCall, 5363 llvm::SmallBitVector &CheckedVarArgs, 5364 UncoveredArgHandler &UncoveredArg, 5365 llvm::APSInt Offset) { 5366 tryAgain: 5367 assert(Offset.isSigned() && "invalid offset"); 5368 5369 if (E->isTypeDependent() || E->isValueDependent()) 5370 return SLCT_NotALiteral; 5371 5372 E = E->IgnoreParenCasts(); 5373 5374 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 5375 // Technically -Wformat-nonliteral does not warn about this case. 5376 // The behavior of printf and friends in this case is implementation 5377 // dependent. Ideally if the format string cannot be null then 5378 // it should have a 'nonnull' attribute in the function prototype. 5379 return SLCT_UncheckedLiteral; 5380 5381 switch (E->getStmtClass()) { 5382 case Stmt::BinaryConditionalOperatorClass: 5383 case Stmt::ConditionalOperatorClass: { 5384 // The expression is a literal if both sub-expressions were, and it was 5385 // completely checked only if both sub-expressions were checked. 5386 const AbstractConditionalOperator *C = 5387 cast<AbstractConditionalOperator>(E); 5388 5389 // Determine whether it is necessary to check both sub-expressions, for 5390 // example, because the condition expression is a constant that can be 5391 // evaluated at compile time. 5392 bool CheckLeft = true, CheckRight = true; 5393 5394 bool Cond; 5395 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 5396 if (Cond) 5397 CheckRight = false; 5398 else 5399 CheckLeft = false; 5400 } 5401 5402 // We need to maintain the offsets for the right and the left hand side 5403 // separately to check if every possible indexed expression is a valid 5404 // string literal. They might have different offsets for different string 5405 // literals in the end. 5406 StringLiteralCheckType Left; 5407 if (!CheckLeft) 5408 Left = SLCT_UncheckedLiteral; 5409 else { 5410 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 5411 HasVAListArg, format_idx, firstDataArg, 5412 Type, CallType, InFunctionCall, 5413 CheckedVarArgs, UncoveredArg, Offset); 5414 if (Left == SLCT_NotALiteral || !CheckRight) { 5415 return Left; 5416 } 5417 } 5418 5419 StringLiteralCheckType Right = 5420 checkFormatStringExpr(S, C->getFalseExpr(), Args, 5421 HasVAListArg, format_idx, firstDataArg, 5422 Type, CallType, InFunctionCall, CheckedVarArgs, 5423 UncoveredArg, Offset); 5424 5425 return (CheckLeft && Left < Right) ? Left : Right; 5426 } 5427 5428 case Stmt::ImplicitCastExprClass: 5429 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 5430 goto tryAgain; 5431 5432 case Stmt::OpaqueValueExprClass: 5433 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 5434 E = src; 5435 goto tryAgain; 5436 } 5437 return SLCT_NotALiteral; 5438 5439 case Stmt::PredefinedExprClass: 5440 // While __func__, etc., are technically not string literals, they 5441 // cannot contain format specifiers and thus are not a security 5442 // liability. 5443 return SLCT_UncheckedLiteral; 5444 5445 case Stmt::DeclRefExprClass: { 5446 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 5447 5448 // As an exception, do not flag errors for variables binding to 5449 // const string literals. 5450 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 5451 bool isConstant = false; 5452 QualType T = DR->getType(); 5453 5454 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 5455 isConstant = AT->getElementType().isConstant(S.Context); 5456 } else if (const PointerType *PT = T->getAs<PointerType>()) { 5457 isConstant = T.isConstant(S.Context) && 5458 PT->getPointeeType().isConstant(S.Context); 5459 } else if (T->isObjCObjectPointerType()) { 5460 // In ObjC, there is usually no "const ObjectPointer" type, 5461 // so don't check if the pointee type is constant. 5462 isConstant = T.isConstant(S.Context); 5463 } 5464 5465 if (isConstant) { 5466 if (const Expr *Init = VD->getAnyInitializer()) { 5467 // Look through initializers like const char c[] = { "foo" } 5468 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 5469 if (InitList->isStringLiteralInit()) 5470 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 5471 } 5472 return checkFormatStringExpr(S, Init, Args, 5473 HasVAListArg, format_idx, 5474 firstDataArg, Type, CallType, 5475 /*InFunctionCall*/ false, CheckedVarArgs, 5476 UncoveredArg, Offset); 5477 } 5478 } 5479 5480 // For vprintf* functions (i.e., HasVAListArg==true), we add a 5481 // special check to see if the format string is a function parameter 5482 // of the function calling the printf function. If the function 5483 // has an attribute indicating it is a printf-like function, then we 5484 // should suppress warnings concerning non-literals being used in a call 5485 // to a vprintf function. For example: 5486 // 5487 // void 5488 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 5489 // va_list ap; 5490 // va_start(ap, fmt); 5491 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 5492 // ... 5493 // } 5494 if (HasVAListArg) { 5495 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 5496 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 5497 int PVIndex = PV->getFunctionScopeIndex() + 1; 5498 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 5499 // adjust for implicit parameter 5500 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5501 if (MD->isInstance()) 5502 ++PVIndex; 5503 // We also check if the formats are compatible. 5504 // We can't pass a 'scanf' string to a 'printf' function. 5505 if (PVIndex == PVFormat->getFormatIdx() && 5506 Type == S.GetFormatStringType(PVFormat)) 5507 return SLCT_UncheckedLiteral; 5508 } 5509 } 5510 } 5511 } 5512 } 5513 5514 return SLCT_NotALiteral; 5515 } 5516 5517 case Stmt::CallExprClass: 5518 case Stmt::CXXMemberCallExprClass: { 5519 const CallExpr *CE = cast<CallExpr>(E); 5520 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 5521 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) { 5522 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 5523 return checkFormatStringExpr(S, Arg, Args, 5524 HasVAListArg, format_idx, firstDataArg, 5525 Type, CallType, InFunctionCall, 5526 CheckedVarArgs, UncoveredArg, Offset); 5527 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5528 unsigned BuiltinID = FD->getBuiltinID(); 5529 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 5530 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 5531 const Expr *Arg = CE->getArg(0); 5532 return checkFormatStringExpr(S, Arg, Args, 5533 HasVAListArg, format_idx, 5534 firstDataArg, Type, CallType, 5535 InFunctionCall, CheckedVarArgs, 5536 UncoveredArg, Offset); 5537 } 5538 } 5539 } 5540 5541 return SLCT_NotALiteral; 5542 } 5543 case Stmt::ObjCMessageExprClass: { 5544 const auto *ME = cast<ObjCMessageExpr>(E); 5545 if (const auto *ND = ME->getMethodDecl()) { 5546 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 5547 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 5548 return checkFormatStringExpr( 5549 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 5550 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 5551 } 5552 } 5553 5554 return SLCT_NotALiteral; 5555 } 5556 case Stmt::ObjCStringLiteralClass: 5557 case Stmt::StringLiteralClass: { 5558 const StringLiteral *StrE = nullptr; 5559 5560 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 5561 StrE = ObjCFExpr->getString(); 5562 else 5563 StrE = cast<StringLiteral>(E); 5564 5565 if (StrE) { 5566 if (Offset.isNegative() || Offset > StrE->getLength()) { 5567 // TODO: It would be better to have an explicit warning for out of 5568 // bounds literals. 5569 return SLCT_NotALiteral; 5570 } 5571 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 5572 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 5573 firstDataArg, Type, InFunctionCall, CallType, 5574 CheckedVarArgs, UncoveredArg); 5575 return SLCT_CheckedLiteral; 5576 } 5577 5578 return SLCT_NotALiteral; 5579 } 5580 case Stmt::BinaryOperatorClass: { 5581 llvm::APSInt LResult; 5582 llvm::APSInt RResult; 5583 5584 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 5585 5586 // A string literal + an int offset is still a string literal. 5587 if (BinOp->isAdditiveOp()) { 5588 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 5589 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 5590 5591 if (LIsInt != RIsInt) { 5592 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 5593 5594 if (LIsInt) { 5595 if (BinOpKind == BO_Add) { 5596 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 5597 E = BinOp->getRHS(); 5598 goto tryAgain; 5599 } 5600 } else { 5601 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 5602 E = BinOp->getLHS(); 5603 goto tryAgain; 5604 } 5605 } 5606 } 5607 5608 return SLCT_NotALiteral; 5609 } 5610 case Stmt::UnaryOperatorClass: { 5611 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 5612 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 5613 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 5614 llvm::APSInt IndexResult; 5615 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 5616 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 5617 E = ASE->getBase(); 5618 goto tryAgain; 5619 } 5620 } 5621 5622 return SLCT_NotALiteral; 5623 } 5624 5625 default: 5626 return SLCT_NotALiteral; 5627 } 5628 } 5629 5630 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 5631 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 5632 .Case("scanf", FST_Scanf) 5633 .Cases("printf", "printf0", FST_Printf) 5634 .Cases("NSString", "CFString", FST_NSString) 5635 .Case("strftime", FST_Strftime) 5636 .Case("strfmon", FST_Strfmon) 5637 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 5638 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 5639 .Case("os_trace", FST_OSLog) 5640 .Case("os_log", FST_OSLog) 5641 .Default(FST_Unknown); 5642 } 5643 5644 /// CheckFormatArguments - Check calls to printf and scanf (and similar 5645 /// functions) for correct use of format strings. 5646 /// Returns true if a format string has been fully checked. 5647 bool Sema::CheckFormatArguments(const FormatAttr *Format, 5648 ArrayRef<const Expr *> Args, 5649 bool IsCXXMember, 5650 VariadicCallType CallType, 5651 SourceLocation Loc, SourceRange Range, 5652 llvm::SmallBitVector &CheckedVarArgs) { 5653 FormatStringInfo FSI; 5654 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 5655 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 5656 FSI.FirstDataArg, GetFormatStringType(Format), 5657 CallType, Loc, Range, CheckedVarArgs); 5658 return false; 5659 } 5660 5661 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 5662 bool HasVAListArg, unsigned format_idx, 5663 unsigned firstDataArg, FormatStringType Type, 5664 VariadicCallType CallType, 5665 SourceLocation Loc, SourceRange Range, 5666 llvm::SmallBitVector &CheckedVarArgs) { 5667 // CHECK: printf/scanf-like function is called with no format string. 5668 if (format_idx >= Args.size()) { 5669 Diag(Loc, diag::warn_missing_format_string) << Range; 5670 return false; 5671 } 5672 5673 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 5674 5675 // CHECK: format string is not a string literal. 5676 // 5677 // Dynamically generated format strings are difficult to 5678 // automatically vet at compile time. Requiring that format strings 5679 // are string literals: (1) permits the checking of format strings by 5680 // the compiler and thereby (2) can practically remove the source of 5681 // many format string exploits. 5682 5683 // Format string can be either ObjC string (e.g. @"%d") or 5684 // C string (e.g. "%d") 5685 // ObjC string uses the same format specifiers as C string, so we can use 5686 // the same format string checking logic for both ObjC and C strings. 5687 UncoveredArgHandler UncoveredArg; 5688 StringLiteralCheckType CT = 5689 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 5690 format_idx, firstDataArg, Type, CallType, 5691 /*IsFunctionCall*/ true, CheckedVarArgs, 5692 UncoveredArg, 5693 /*no string offset*/ llvm::APSInt(64, false) = 0); 5694 5695 // Generate a diagnostic where an uncovered argument is detected. 5696 if (UncoveredArg.hasUncoveredArg()) { 5697 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 5698 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 5699 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 5700 } 5701 5702 if (CT != SLCT_NotALiteral) 5703 // Literal format string found, check done! 5704 return CT == SLCT_CheckedLiteral; 5705 5706 // Strftime is particular as it always uses a single 'time' argument, 5707 // so it is safe to pass a non-literal string. 5708 if (Type == FST_Strftime) 5709 return false; 5710 5711 // Do not emit diag when the string param is a macro expansion and the 5712 // format is either NSString or CFString. This is a hack to prevent 5713 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 5714 // which are usually used in place of NS and CF string literals. 5715 SourceLocation FormatLoc = Args[format_idx]->getLocStart(); 5716 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 5717 return false; 5718 5719 // If there are no arguments specified, warn with -Wformat-security, otherwise 5720 // warn only with -Wformat-nonliteral. 5721 if (Args.size() == firstDataArg) { 5722 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 5723 << OrigFormatExpr->getSourceRange(); 5724 switch (Type) { 5725 default: 5726 break; 5727 case FST_Kprintf: 5728 case FST_FreeBSDKPrintf: 5729 case FST_Printf: 5730 Diag(FormatLoc, diag::note_format_security_fixit) 5731 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 5732 break; 5733 case FST_NSString: 5734 Diag(FormatLoc, diag::note_format_security_fixit) 5735 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 5736 break; 5737 } 5738 } else { 5739 Diag(FormatLoc, diag::warn_format_nonliteral) 5740 << OrigFormatExpr->getSourceRange(); 5741 } 5742 return false; 5743 } 5744 5745 namespace { 5746 5747 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 5748 protected: 5749 Sema &S; 5750 const FormatStringLiteral *FExpr; 5751 const Expr *OrigFormatExpr; 5752 const Sema::FormatStringType FSType; 5753 const unsigned FirstDataArg; 5754 const unsigned NumDataArgs; 5755 const char *Beg; // Start of format string. 5756 const bool HasVAListArg; 5757 ArrayRef<const Expr *> Args; 5758 unsigned FormatIdx; 5759 llvm::SmallBitVector CoveredArgs; 5760 bool usesPositionalArgs = false; 5761 bool atFirstArg = true; 5762 bool inFunctionCall; 5763 Sema::VariadicCallType CallType; 5764 llvm::SmallBitVector &CheckedVarArgs; 5765 UncoveredArgHandler &UncoveredArg; 5766 5767 public: 5768 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 5769 const Expr *origFormatExpr, 5770 const Sema::FormatStringType type, unsigned firstDataArg, 5771 unsigned numDataArgs, const char *beg, bool hasVAListArg, 5772 ArrayRef<const Expr *> Args, unsigned formatIdx, 5773 bool inFunctionCall, Sema::VariadicCallType callType, 5774 llvm::SmallBitVector &CheckedVarArgs, 5775 UncoveredArgHandler &UncoveredArg) 5776 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 5777 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 5778 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 5779 inFunctionCall(inFunctionCall), CallType(callType), 5780 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 5781 CoveredArgs.resize(numDataArgs); 5782 CoveredArgs.reset(); 5783 } 5784 5785 void DoneProcessing(); 5786 5787 void HandleIncompleteSpecifier(const char *startSpecifier, 5788 unsigned specifierLen) override; 5789 5790 void HandleInvalidLengthModifier( 5791 const analyze_format_string::FormatSpecifier &FS, 5792 const analyze_format_string::ConversionSpecifier &CS, 5793 const char *startSpecifier, unsigned specifierLen, 5794 unsigned DiagID); 5795 5796 void HandleNonStandardLengthModifier( 5797 const analyze_format_string::FormatSpecifier &FS, 5798 const char *startSpecifier, unsigned specifierLen); 5799 5800 void HandleNonStandardConversionSpecifier( 5801 const analyze_format_string::ConversionSpecifier &CS, 5802 const char *startSpecifier, unsigned specifierLen); 5803 5804 void HandlePosition(const char *startPos, unsigned posLen) override; 5805 5806 void HandleInvalidPosition(const char *startSpecifier, 5807 unsigned specifierLen, 5808 analyze_format_string::PositionContext p) override; 5809 5810 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 5811 5812 void HandleNullChar(const char *nullCharacter) override; 5813 5814 template <typename Range> 5815 static void 5816 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 5817 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 5818 bool IsStringLocation, Range StringRange, 5819 ArrayRef<FixItHint> Fixit = None); 5820 5821 protected: 5822 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 5823 const char *startSpec, 5824 unsigned specifierLen, 5825 const char *csStart, unsigned csLen); 5826 5827 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 5828 const char *startSpec, 5829 unsigned specifierLen); 5830 5831 SourceRange getFormatStringRange(); 5832 CharSourceRange getSpecifierRange(const char *startSpecifier, 5833 unsigned specifierLen); 5834 SourceLocation getLocationOfByte(const char *x); 5835 5836 const Expr *getDataArg(unsigned i) const; 5837 5838 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 5839 const analyze_format_string::ConversionSpecifier &CS, 5840 const char *startSpecifier, unsigned specifierLen, 5841 unsigned argIndex); 5842 5843 template <typename Range> 5844 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 5845 bool IsStringLocation, Range StringRange, 5846 ArrayRef<FixItHint> Fixit = None); 5847 }; 5848 5849 } // namespace 5850 5851 SourceRange CheckFormatHandler::getFormatStringRange() { 5852 return OrigFormatExpr->getSourceRange(); 5853 } 5854 5855 CharSourceRange CheckFormatHandler:: 5856 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 5857 SourceLocation Start = getLocationOfByte(startSpecifier); 5858 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 5859 5860 // Advance the end SourceLocation by one due to half-open ranges. 5861 End = End.getLocWithOffset(1); 5862 5863 return CharSourceRange::getCharRange(Start, End); 5864 } 5865 5866 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 5867 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 5868 S.getLangOpts(), S.Context.getTargetInfo()); 5869 } 5870 5871 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 5872 unsigned specifierLen){ 5873 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 5874 getLocationOfByte(startSpecifier), 5875 /*IsStringLocation*/true, 5876 getSpecifierRange(startSpecifier, specifierLen)); 5877 } 5878 5879 void CheckFormatHandler::HandleInvalidLengthModifier( 5880 const analyze_format_string::FormatSpecifier &FS, 5881 const analyze_format_string::ConversionSpecifier &CS, 5882 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 5883 using namespace analyze_format_string; 5884 5885 const LengthModifier &LM = FS.getLengthModifier(); 5886 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5887 5888 // See if we know how to fix this length modifier. 5889 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5890 if (FixedLM) { 5891 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5892 getLocationOfByte(LM.getStart()), 5893 /*IsStringLocation*/true, 5894 getSpecifierRange(startSpecifier, specifierLen)); 5895 5896 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5897 << FixedLM->toString() 5898 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5899 5900 } else { 5901 FixItHint Hint; 5902 if (DiagID == diag::warn_format_nonsensical_length) 5903 Hint = FixItHint::CreateRemoval(LMRange); 5904 5905 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 5906 getLocationOfByte(LM.getStart()), 5907 /*IsStringLocation*/true, 5908 getSpecifierRange(startSpecifier, specifierLen), 5909 Hint); 5910 } 5911 } 5912 5913 void CheckFormatHandler::HandleNonStandardLengthModifier( 5914 const analyze_format_string::FormatSpecifier &FS, 5915 const char *startSpecifier, unsigned specifierLen) { 5916 using namespace analyze_format_string; 5917 5918 const LengthModifier &LM = FS.getLengthModifier(); 5919 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 5920 5921 // See if we know how to fix this length modifier. 5922 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 5923 if (FixedLM) { 5924 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5925 << LM.toString() << 0, 5926 getLocationOfByte(LM.getStart()), 5927 /*IsStringLocation*/true, 5928 getSpecifierRange(startSpecifier, specifierLen)); 5929 5930 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 5931 << FixedLM->toString() 5932 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 5933 5934 } else { 5935 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5936 << LM.toString() << 0, 5937 getLocationOfByte(LM.getStart()), 5938 /*IsStringLocation*/true, 5939 getSpecifierRange(startSpecifier, specifierLen)); 5940 } 5941 } 5942 5943 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 5944 const analyze_format_string::ConversionSpecifier &CS, 5945 const char *startSpecifier, unsigned specifierLen) { 5946 using namespace analyze_format_string; 5947 5948 // See if we know how to fix this conversion specifier. 5949 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 5950 if (FixedCS) { 5951 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5952 << CS.toString() << /*conversion specifier*/1, 5953 getLocationOfByte(CS.getStart()), 5954 /*IsStringLocation*/true, 5955 getSpecifierRange(startSpecifier, specifierLen)); 5956 5957 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 5958 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 5959 << FixedCS->toString() 5960 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 5961 } else { 5962 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 5963 << CS.toString() << /*conversion specifier*/1, 5964 getLocationOfByte(CS.getStart()), 5965 /*IsStringLocation*/true, 5966 getSpecifierRange(startSpecifier, specifierLen)); 5967 } 5968 } 5969 5970 void CheckFormatHandler::HandlePosition(const char *startPos, 5971 unsigned posLen) { 5972 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 5973 getLocationOfByte(startPos), 5974 /*IsStringLocation*/true, 5975 getSpecifierRange(startPos, posLen)); 5976 } 5977 5978 void 5979 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 5980 analyze_format_string::PositionContext p) { 5981 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 5982 << (unsigned) p, 5983 getLocationOfByte(startPos), /*IsStringLocation*/true, 5984 getSpecifierRange(startPos, posLen)); 5985 } 5986 5987 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 5988 unsigned posLen) { 5989 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 5990 getLocationOfByte(startPos), 5991 /*IsStringLocation*/true, 5992 getSpecifierRange(startPos, posLen)); 5993 } 5994 5995 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 5996 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 5997 // The presence of a null character is likely an error. 5998 EmitFormatDiagnostic( 5999 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6000 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6001 getFormatStringRange()); 6002 } 6003 } 6004 6005 // Note that this may return NULL if there was an error parsing or building 6006 // one of the argument expressions. 6007 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6008 return Args[FirstDataArg + i]; 6009 } 6010 6011 void CheckFormatHandler::DoneProcessing() { 6012 // Does the number of data arguments exceed the number of 6013 // format conversions in the format string? 6014 if (!HasVAListArg) { 6015 // Find any arguments that weren't covered. 6016 CoveredArgs.flip(); 6017 signed notCoveredArg = CoveredArgs.find_first(); 6018 if (notCoveredArg >= 0) { 6019 assert((unsigned)notCoveredArg < NumDataArgs); 6020 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6021 } else { 6022 UncoveredArg.setAllCovered(); 6023 } 6024 } 6025 } 6026 6027 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6028 const Expr *ArgExpr) { 6029 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6030 "Invalid state"); 6031 6032 if (!ArgExpr) 6033 return; 6034 6035 SourceLocation Loc = ArgExpr->getLocStart(); 6036 6037 if (S.getSourceManager().isInSystemMacro(Loc)) 6038 return; 6039 6040 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6041 for (auto E : DiagnosticExprs) 6042 PDiag << E->getSourceRange(); 6043 6044 CheckFormatHandler::EmitFormatDiagnostic( 6045 S, IsFunctionCall, DiagnosticExprs[0], 6046 PDiag, Loc, /*IsStringLocation*/false, 6047 DiagnosticExprs[0]->getSourceRange()); 6048 } 6049 6050 bool 6051 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6052 SourceLocation Loc, 6053 const char *startSpec, 6054 unsigned specifierLen, 6055 const char *csStart, 6056 unsigned csLen) { 6057 bool keepGoing = true; 6058 if (argIndex < NumDataArgs) { 6059 // Consider the argument coverered, even though the specifier doesn't 6060 // make sense. 6061 CoveredArgs.set(argIndex); 6062 } 6063 else { 6064 // If argIndex exceeds the number of data arguments we 6065 // don't issue a warning because that is just a cascade of warnings (and 6066 // they may have intended '%%' anyway). We don't want to continue processing 6067 // the format string after this point, however, as we will like just get 6068 // gibberish when trying to match arguments. 6069 keepGoing = false; 6070 } 6071 6072 StringRef Specifier(csStart, csLen); 6073 6074 // If the specifier in non-printable, it could be the first byte of a UTF-8 6075 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6076 // hex value. 6077 std::string CodePointStr; 6078 if (!llvm::sys::locale::isPrint(*csStart)) { 6079 llvm::UTF32 CodePoint; 6080 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6081 const llvm::UTF8 *E = 6082 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6083 llvm::ConversionResult Result = 6084 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6085 6086 if (Result != llvm::conversionOK) { 6087 unsigned char FirstChar = *csStart; 6088 CodePoint = (llvm::UTF32)FirstChar; 6089 } 6090 6091 llvm::raw_string_ostream OS(CodePointStr); 6092 if (CodePoint < 256) 6093 OS << "\\x" << llvm::format("%02x", CodePoint); 6094 else if (CodePoint <= 0xFFFF) 6095 OS << "\\u" << llvm::format("%04x", CodePoint); 6096 else 6097 OS << "\\U" << llvm::format("%08x", CodePoint); 6098 OS.flush(); 6099 Specifier = CodePointStr; 6100 } 6101 6102 EmitFormatDiagnostic( 6103 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 6104 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 6105 6106 return keepGoing; 6107 } 6108 6109 void 6110 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 6111 const char *startSpec, 6112 unsigned specifierLen) { 6113 EmitFormatDiagnostic( 6114 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 6115 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 6116 } 6117 6118 bool 6119 CheckFormatHandler::CheckNumArgs( 6120 const analyze_format_string::FormatSpecifier &FS, 6121 const analyze_format_string::ConversionSpecifier &CS, 6122 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 6123 6124 if (argIndex >= NumDataArgs) { 6125 PartialDiagnostic PDiag = FS.usesPositionalArg() 6126 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 6127 << (argIndex+1) << NumDataArgs) 6128 : S.PDiag(diag::warn_printf_insufficient_data_args); 6129 EmitFormatDiagnostic( 6130 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 6131 getSpecifierRange(startSpecifier, specifierLen)); 6132 6133 // Since more arguments than conversion tokens are given, by extension 6134 // all arguments are covered, so mark this as so. 6135 UncoveredArg.setAllCovered(); 6136 return false; 6137 } 6138 return true; 6139 } 6140 6141 template<typename Range> 6142 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 6143 SourceLocation Loc, 6144 bool IsStringLocation, 6145 Range StringRange, 6146 ArrayRef<FixItHint> FixIt) { 6147 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 6148 Loc, IsStringLocation, StringRange, FixIt); 6149 } 6150 6151 /// If the format string is not within the function call, emit a note 6152 /// so that the function call and string are in diagnostic messages. 6153 /// 6154 /// \param InFunctionCall if true, the format string is within the function 6155 /// call and only one diagnostic message will be produced. Otherwise, an 6156 /// extra note will be emitted pointing to location of the format string. 6157 /// 6158 /// \param ArgumentExpr the expression that is passed as the format string 6159 /// argument in the function call. Used for getting locations when two 6160 /// diagnostics are emitted. 6161 /// 6162 /// \param PDiag the callee should already have provided any strings for the 6163 /// diagnostic message. This function only adds locations and fixits 6164 /// to diagnostics. 6165 /// 6166 /// \param Loc primary location for diagnostic. If two diagnostics are 6167 /// required, one will be at Loc and a new SourceLocation will be created for 6168 /// the other one. 6169 /// 6170 /// \param IsStringLocation if true, Loc points to the format string should be 6171 /// used for the note. Otherwise, Loc points to the argument list and will 6172 /// be used with PDiag. 6173 /// 6174 /// \param StringRange some or all of the string to highlight. This is 6175 /// templated so it can accept either a CharSourceRange or a SourceRange. 6176 /// 6177 /// \param FixIt optional fix it hint for the format string. 6178 template <typename Range> 6179 void CheckFormatHandler::EmitFormatDiagnostic( 6180 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 6181 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 6182 Range StringRange, ArrayRef<FixItHint> FixIt) { 6183 if (InFunctionCall) { 6184 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 6185 D << StringRange; 6186 D << FixIt; 6187 } else { 6188 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 6189 << ArgumentExpr->getSourceRange(); 6190 6191 const Sema::SemaDiagnosticBuilder &Note = 6192 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 6193 diag::note_format_string_defined); 6194 6195 Note << StringRange; 6196 Note << FixIt; 6197 } 6198 } 6199 6200 //===--- CHECK: Printf format string checking ------------------------------===// 6201 6202 namespace { 6203 6204 class CheckPrintfHandler : public CheckFormatHandler { 6205 public: 6206 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 6207 const Expr *origFormatExpr, 6208 const Sema::FormatStringType type, unsigned firstDataArg, 6209 unsigned numDataArgs, bool isObjC, const char *beg, 6210 bool hasVAListArg, ArrayRef<const Expr *> Args, 6211 unsigned formatIdx, bool inFunctionCall, 6212 Sema::VariadicCallType CallType, 6213 llvm::SmallBitVector &CheckedVarArgs, 6214 UncoveredArgHandler &UncoveredArg) 6215 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6216 numDataArgs, beg, hasVAListArg, Args, formatIdx, 6217 inFunctionCall, CallType, CheckedVarArgs, 6218 UncoveredArg) {} 6219 6220 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 6221 6222 /// Returns true if '%@' specifiers are allowed in the format string. 6223 bool allowsObjCArg() const { 6224 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 6225 FSType == Sema::FST_OSTrace; 6226 } 6227 6228 bool HandleInvalidPrintfConversionSpecifier( 6229 const analyze_printf::PrintfSpecifier &FS, 6230 const char *startSpecifier, 6231 unsigned specifierLen) override; 6232 6233 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 6234 const char *startSpecifier, 6235 unsigned specifierLen) override; 6236 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6237 const char *StartSpecifier, 6238 unsigned SpecifierLen, 6239 const Expr *E); 6240 6241 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 6242 const char *startSpecifier, unsigned specifierLen); 6243 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 6244 const analyze_printf::OptionalAmount &Amt, 6245 unsigned type, 6246 const char *startSpecifier, unsigned specifierLen); 6247 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6248 const analyze_printf::OptionalFlag &flag, 6249 const char *startSpecifier, unsigned specifierLen); 6250 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 6251 const analyze_printf::OptionalFlag &ignoredFlag, 6252 const analyze_printf::OptionalFlag &flag, 6253 const char *startSpecifier, unsigned specifierLen); 6254 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 6255 const Expr *E); 6256 6257 void HandleEmptyObjCModifierFlag(const char *startFlag, 6258 unsigned flagLen) override; 6259 6260 void HandleInvalidObjCModifierFlag(const char *startFlag, 6261 unsigned flagLen) override; 6262 6263 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 6264 const char *flagsEnd, 6265 const char *conversionPosition) 6266 override; 6267 }; 6268 6269 } // namespace 6270 6271 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 6272 const analyze_printf::PrintfSpecifier &FS, 6273 const char *startSpecifier, 6274 unsigned specifierLen) { 6275 const analyze_printf::PrintfConversionSpecifier &CS = 6276 FS.getConversionSpecifier(); 6277 6278 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6279 getLocationOfByte(CS.getStart()), 6280 startSpecifier, specifierLen, 6281 CS.getStart(), CS.getLength()); 6282 } 6283 6284 bool CheckPrintfHandler::HandleAmount( 6285 const analyze_format_string::OptionalAmount &Amt, 6286 unsigned k, const char *startSpecifier, 6287 unsigned specifierLen) { 6288 if (Amt.hasDataArgument()) { 6289 if (!HasVAListArg) { 6290 unsigned argIndex = Amt.getArgIndex(); 6291 if (argIndex >= NumDataArgs) { 6292 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 6293 << k, 6294 getLocationOfByte(Amt.getStart()), 6295 /*IsStringLocation*/true, 6296 getSpecifierRange(startSpecifier, specifierLen)); 6297 // Don't do any more checking. We will just emit 6298 // spurious errors. 6299 return false; 6300 } 6301 6302 // Type check the data argument. It should be an 'int'. 6303 // Although not in conformance with C99, we also allow the argument to be 6304 // an 'unsigned int' as that is a reasonably safe case. GCC also 6305 // doesn't emit a warning for that case. 6306 CoveredArgs.set(argIndex); 6307 const Expr *Arg = getDataArg(argIndex); 6308 if (!Arg) 6309 return false; 6310 6311 QualType T = Arg->getType(); 6312 6313 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 6314 assert(AT.isValid()); 6315 6316 if (!AT.matchesType(S.Context, T)) { 6317 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 6318 << k << AT.getRepresentativeTypeName(S.Context) 6319 << T << Arg->getSourceRange(), 6320 getLocationOfByte(Amt.getStart()), 6321 /*IsStringLocation*/true, 6322 getSpecifierRange(startSpecifier, specifierLen)); 6323 // Don't do any more checking. We will just emit 6324 // spurious errors. 6325 return false; 6326 } 6327 } 6328 } 6329 return true; 6330 } 6331 6332 void CheckPrintfHandler::HandleInvalidAmount( 6333 const analyze_printf::PrintfSpecifier &FS, 6334 const analyze_printf::OptionalAmount &Amt, 6335 unsigned type, 6336 const char *startSpecifier, 6337 unsigned specifierLen) { 6338 const analyze_printf::PrintfConversionSpecifier &CS = 6339 FS.getConversionSpecifier(); 6340 6341 FixItHint fixit = 6342 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 6343 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 6344 Amt.getConstantLength())) 6345 : FixItHint(); 6346 6347 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 6348 << type << CS.toString(), 6349 getLocationOfByte(Amt.getStart()), 6350 /*IsStringLocation*/true, 6351 getSpecifierRange(startSpecifier, specifierLen), 6352 fixit); 6353 } 6354 6355 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6356 const analyze_printf::OptionalFlag &flag, 6357 const char *startSpecifier, 6358 unsigned specifierLen) { 6359 // Warn about pointless flag with a fixit removal. 6360 const analyze_printf::PrintfConversionSpecifier &CS = 6361 FS.getConversionSpecifier(); 6362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 6363 << flag.toString() << CS.toString(), 6364 getLocationOfByte(flag.getPosition()), 6365 /*IsStringLocation*/true, 6366 getSpecifierRange(startSpecifier, specifierLen), 6367 FixItHint::CreateRemoval( 6368 getSpecifierRange(flag.getPosition(), 1))); 6369 } 6370 6371 void CheckPrintfHandler::HandleIgnoredFlag( 6372 const analyze_printf::PrintfSpecifier &FS, 6373 const analyze_printf::OptionalFlag &ignoredFlag, 6374 const analyze_printf::OptionalFlag &flag, 6375 const char *startSpecifier, 6376 unsigned specifierLen) { 6377 // Warn about ignored flag with a fixit removal. 6378 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 6379 << ignoredFlag.toString() << flag.toString(), 6380 getLocationOfByte(ignoredFlag.getPosition()), 6381 /*IsStringLocation*/true, 6382 getSpecifierRange(startSpecifier, specifierLen), 6383 FixItHint::CreateRemoval( 6384 getSpecifierRange(ignoredFlag.getPosition(), 1))); 6385 } 6386 6387 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 6388 unsigned flagLen) { 6389 // Warn about an empty flag. 6390 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 6391 getLocationOfByte(startFlag), 6392 /*IsStringLocation*/true, 6393 getSpecifierRange(startFlag, flagLen)); 6394 } 6395 6396 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 6397 unsigned flagLen) { 6398 // Warn about an invalid flag. 6399 auto Range = getSpecifierRange(startFlag, flagLen); 6400 StringRef flag(startFlag, flagLen); 6401 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 6402 getLocationOfByte(startFlag), 6403 /*IsStringLocation*/true, 6404 Range, FixItHint::CreateRemoval(Range)); 6405 } 6406 6407 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 6408 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 6409 // Warn about using '[...]' without a '@' conversion. 6410 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 6411 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 6412 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 6413 getLocationOfByte(conversionPosition), 6414 /*IsStringLocation*/true, 6415 Range, FixItHint::CreateRemoval(Range)); 6416 } 6417 6418 // Determines if the specified is a C++ class or struct containing 6419 // a member with the specified name and kind (e.g. a CXXMethodDecl named 6420 // "c_str()"). 6421 template<typename MemberKind> 6422 static llvm::SmallPtrSet<MemberKind*, 1> 6423 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 6424 const RecordType *RT = Ty->getAs<RecordType>(); 6425 llvm::SmallPtrSet<MemberKind*, 1> Results; 6426 6427 if (!RT) 6428 return Results; 6429 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 6430 if (!RD || !RD->getDefinition()) 6431 return Results; 6432 6433 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 6434 Sema::LookupMemberName); 6435 R.suppressDiagnostics(); 6436 6437 // We just need to include all members of the right kind turned up by the 6438 // filter, at this point. 6439 if (S.LookupQualifiedName(R, RT->getDecl())) 6440 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6441 NamedDecl *decl = (*I)->getUnderlyingDecl(); 6442 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 6443 Results.insert(FK); 6444 } 6445 return Results; 6446 } 6447 6448 /// Check if we could call '.c_str()' on an object. 6449 /// 6450 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 6451 /// allow the call, or if it would be ambiguous). 6452 bool Sema::hasCStrMethod(const Expr *E) { 6453 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6454 6455 MethodSet Results = 6456 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 6457 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6458 MI != ME; ++MI) 6459 if ((*MI)->getMinRequiredArguments() == 0) 6460 return true; 6461 return false; 6462 } 6463 6464 // Check if a (w)string was passed when a (w)char* was needed, and offer a 6465 // better diagnostic if so. AT is assumed to be valid. 6466 // Returns true when a c_str() conversion method is found. 6467 bool CheckPrintfHandler::checkForCStrMembers( 6468 const analyze_printf::ArgType &AT, const Expr *E) { 6469 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 6470 6471 MethodSet Results = 6472 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 6473 6474 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 6475 MI != ME; ++MI) { 6476 const CXXMethodDecl *Method = *MI; 6477 if (Method->getMinRequiredArguments() == 0 && 6478 AT.matchesType(S.Context, Method->getReturnType())) { 6479 // FIXME: Suggest parens if the expression needs them. 6480 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd()); 6481 S.Diag(E->getLocStart(), diag::note_printf_c_str) 6482 << "c_str()" 6483 << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 6484 return true; 6485 } 6486 } 6487 6488 return false; 6489 } 6490 6491 bool 6492 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 6493 &FS, 6494 const char *startSpecifier, 6495 unsigned specifierLen) { 6496 using namespace analyze_format_string; 6497 using namespace analyze_printf; 6498 6499 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 6500 6501 if (FS.consumesDataArgument()) { 6502 if (atFirstArg) { 6503 atFirstArg = false; 6504 usesPositionalArgs = FS.usesPositionalArg(); 6505 } 6506 else if (usesPositionalArgs != FS.usesPositionalArg()) { 6507 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 6508 startSpecifier, specifierLen); 6509 return false; 6510 } 6511 } 6512 6513 // First check if the field width, precision, and conversion specifier 6514 // have matching data arguments. 6515 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 6516 startSpecifier, specifierLen)) { 6517 return false; 6518 } 6519 6520 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 6521 startSpecifier, specifierLen)) { 6522 return false; 6523 } 6524 6525 if (!CS.consumesDataArgument()) { 6526 // FIXME: Technically specifying a precision or field width here 6527 // makes no sense. Worth issuing a warning at some point. 6528 return true; 6529 } 6530 6531 // Consume the argument. 6532 unsigned argIndex = FS.getArgIndex(); 6533 if (argIndex < NumDataArgs) { 6534 // The check to see if the argIndex is valid will come later. 6535 // We set the bit here because we may exit early from this 6536 // function if we encounter some other error. 6537 CoveredArgs.set(argIndex); 6538 } 6539 6540 // FreeBSD kernel extensions. 6541 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 6542 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 6543 // We need at least two arguments. 6544 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 6545 return false; 6546 6547 // Claim the second argument. 6548 CoveredArgs.set(argIndex + 1); 6549 6550 // Type check the first argument (int for %b, pointer for %D) 6551 const Expr *Ex = getDataArg(argIndex); 6552 const analyze_printf::ArgType &AT = 6553 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 6554 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 6555 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 6556 EmitFormatDiagnostic( 6557 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6558 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 6559 << false << Ex->getSourceRange(), 6560 Ex->getLocStart(), /*IsStringLocation*/false, 6561 getSpecifierRange(startSpecifier, specifierLen)); 6562 6563 // Type check the second argument (char * for both %b and %D) 6564 Ex = getDataArg(argIndex + 1); 6565 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 6566 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 6567 EmitFormatDiagnostic( 6568 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6569 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 6570 << false << Ex->getSourceRange(), 6571 Ex->getLocStart(), /*IsStringLocation*/false, 6572 getSpecifierRange(startSpecifier, specifierLen)); 6573 6574 return true; 6575 } 6576 6577 // Check for using an Objective-C specific conversion specifier 6578 // in a non-ObjC literal. 6579 if (!allowsObjCArg() && CS.isObjCArg()) { 6580 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6581 specifierLen); 6582 } 6583 6584 // %P can only be used with os_log. 6585 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 6586 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6587 specifierLen); 6588 } 6589 6590 // %n is not allowed with os_log. 6591 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 6592 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 6593 getLocationOfByte(CS.getStart()), 6594 /*IsStringLocation*/ false, 6595 getSpecifierRange(startSpecifier, specifierLen)); 6596 6597 return true; 6598 } 6599 6600 // Only scalars are allowed for os_trace. 6601 if (FSType == Sema::FST_OSTrace && 6602 (CS.getKind() == ConversionSpecifier::PArg || 6603 CS.getKind() == ConversionSpecifier::sArg || 6604 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 6605 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 6606 specifierLen); 6607 } 6608 6609 // Check for use of public/private annotation outside of os_log(). 6610 if (FSType != Sema::FST_OSLog) { 6611 if (FS.isPublic().isSet()) { 6612 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6613 << "public", 6614 getLocationOfByte(FS.isPublic().getPosition()), 6615 /*IsStringLocation*/ false, 6616 getSpecifierRange(startSpecifier, specifierLen)); 6617 } 6618 if (FS.isPrivate().isSet()) { 6619 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 6620 << "private", 6621 getLocationOfByte(FS.isPrivate().getPosition()), 6622 /*IsStringLocation*/ false, 6623 getSpecifierRange(startSpecifier, specifierLen)); 6624 } 6625 } 6626 6627 // Check for invalid use of field width 6628 if (!FS.hasValidFieldWidth()) { 6629 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 6630 startSpecifier, specifierLen); 6631 } 6632 6633 // Check for invalid use of precision 6634 if (!FS.hasValidPrecision()) { 6635 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 6636 startSpecifier, specifierLen); 6637 } 6638 6639 // Precision is mandatory for %P specifier. 6640 if (CS.getKind() == ConversionSpecifier::PArg && 6641 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 6642 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 6643 getLocationOfByte(startSpecifier), 6644 /*IsStringLocation*/ false, 6645 getSpecifierRange(startSpecifier, specifierLen)); 6646 } 6647 6648 // Check each flag does not conflict with any other component. 6649 if (!FS.hasValidThousandsGroupingPrefix()) 6650 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 6651 if (!FS.hasValidLeadingZeros()) 6652 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 6653 if (!FS.hasValidPlusPrefix()) 6654 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 6655 if (!FS.hasValidSpacePrefix()) 6656 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 6657 if (!FS.hasValidAlternativeForm()) 6658 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 6659 if (!FS.hasValidLeftJustified()) 6660 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 6661 6662 // Check that flags are not ignored by another flag 6663 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 6664 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 6665 startSpecifier, specifierLen); 6666 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 6667 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 6668 startSpecifier, specifierLen); 6669 6670 // Check the length modifier is valid with the given conversion specifier. 6671 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 6672 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6673 diag::warn_format_nonsensical_length); 6674 else if (!FS.hasStandardLengthModifier()) 6675 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 6676 else if (!FS.hasStandardLengthConversionCombination()) 6677 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 6678 diag::warn_format_non_standard_conversion_spec); 6679 6680 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 6681 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 6682 6683 // The remaining checks depend on the data arguments. 6684 if (HasVAListArg) 6685 return true; 6686 6687 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 6688 return false; 6689 6690 const Expr *Arg = getDataArg(argIndex); 6691 if (!Arg) 6692 return true; 6693 6694 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 6695 } 6696 6697 static bool requiresParensToAddCast(const Expr *E) { 6698 // FIXME: We should have a general way to reason about operator 6699 // precedence and whether parens are actually needed here. 6700 // Take care of a few common cases where they aren't. 6701 const Expr *Inside = E->IgnoreImpCasts(); 6702 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 6703 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 6704 6705 switch (Inside->getStmtClass()) { 6706 case Stmt::ArraySubscriptExprClass: 6707 case Stmt::CallExprClass: 6708 case Stmt::CharacterLiteralClass: 6709 case Stmt::CXXBoolLiteralExprClass: 6710 case Stmt::DeclRefExprClass: 6711 case Stmt::FloatingLiteralClass: 6712 case Stmt::IntegerLiteralClass: 6713 case Stmt::MemberExprClass: 6714 case Stmt::ObjCArrayLiteralClass: 6715 case Stmt::ObjCBoolLiteralExprClass: 6716 case Stmt::ObjCBoxedExprClass: 6717 case Stmt::ObjCDictionaryLiteralClass: 6718 case Stmt::ObjCEncodeExprClass: 6719 case Stmt::ObjCIvarRefExprClass: 6720 case Stmt::ObjCMessageExprClass: 6721 case Stmt::ObjCPropertyRefExprClass: 6722 case Stmt::ObjCStringLiteralClass: 6723 case Stmt::ObjCSubscriptRefExprClass: 6724 case Stmt::ParenExprClass: 6725 case Stmt::StringLiteralClass: 6726 case Stmt::UnaryOperatorClass: 6727 return false; 6728 default: 6729 return true; 6730 } 6731 } 6732 6733 static std::pair<QualType, StringRef> 6734 shouldNotPrintDirectly(const ASTContext &Context, 6735 QualType IntendedTy, 6736 const Expr *E) { 6737 // Use a 'while' to peel off layers of typedefs. 6738 QualType TyTy = IntendedTy; 6739 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 6740 StringRef Name = UserTy->getDecl()->getName(); 6741 QualType CastTy = llvm::StringSwitch<QualType>(Name) 6742 .Case("CFIndex", Context.getNSIntegerType()) 6743 .Case("NSInteger", Context.getNSIntegerType()) 6744 .Case("NSUInteger", Context.getNSUIntegerType()) 6745 .Case("SInt32", Context.IntTy) 6746 .Case("UInt32", Context.UnsignedIntTy) 6747 .Default(QualType()); 6748 6749 if (!CastTy.isNull()) 6750 return std::make_pair(CastTy, Name); 6751 6752 TyTy = UserTy->desugar(); 6753 } 6754 6755 // Strip parens if necessary. 6756 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 6757 return shouldNotPrintDirectly(Context, 6758 PE->getSubExpr()->getType(), 6759 PE->getSubExpr()); 6760 6761 // If this is a conditional expression, then its result type is constructed 6762 // via usual arithmetic conversions and thus there might be no necessary 6763 // typedef sugar there. Recurse to operands to check for NSInteger & 6764 // Co. usage condition. 6765 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6766 QualType TrueTy, FalseTy; 6767 StringRef TrueName, FalseName; 6768 6769 std::tie(TrueTy, TrueName) = 6770 shouldNotPrintDirectly(Context, 6771 CO->getTrueExpr()->getType(), 6772 CO->getTrueExpr()); 6773 std::tie(FalseTy, FalseName) = 6774 shouldNotPrintDirectly(Context, 6775 CO->getFalseExpr()->getType(), 6776 CO->getFalseExpr()); 6777 6778 if (TrueTy == FalseTy) 6779 return std::make_pair(TrueTy, TrueName); 6780 else if (TrueTy.isNull()) 6781 return std::make_pair(FalseTy, FalseName); 6782 else if (FalseTy.isNull()) 6783 return std::make_pair(TrueTy, TrueName); 6784 } 6785 6786 return std::make_pair(QualType(), StringRef()); 6787 } 6788 6789 bool 6790 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6791 const char *StartSpecifier, 6792 unsigned SpecifierLen, 6793 const Expr *E) { 6794 using namespace analyze_format_string; 6795 using namespace analyze_printf; 6796 6797 // Now type check the data expression that matches the 6798 // format specifier. 6799 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 6800 if (!AT.isValid()) 6801 return true; 6802 6803 QualType ExprTy = E->getType(); 6804 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 6805 ExprTy = TET->getUnderlyingExpr()->getType(); 6806 } 6807 6808 const analyze_printf::ArgType::MatchKind Match = 6809 AT.matchesType(S.Context, ExprTy); 6810 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 6811 if (Match == analyze_printf::ArgType::Match) 6812 return true; 6813 6814 // Look through argument promotions for our error message's reported type. 6815 // This includes the integral and floating promotions, but excludes array 6816 // and function pointer decay; seeing that an argument intended to be a 6817 // string has type 'char [6]' is probably more confusing than 'char *'. 6818 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 6819 if (ICE->getCastKind() == CK_IntegralCast || 6820 ICE->getCastKind() == CK_FloatingCast) { 6821 E = ICE->getSubExpr(); 6822 ExprTy = E->getType(); 6823 6824 // Check if we didn't match because of an implicit cast from a 'char' 6825 // or 'short' to an 'int'. This is done because printf is a varargs 6826 // function. 6827 if (ICE->getType() == S.Context.IntTy || 6828 ICE->getType() == S.Context.UnsignedIntTy) { 6829 // All further checking is done on the subexpression. 6830 if (AT.matchesType(S.Context, ExprTy)) 6831 return true; 6832 } 6833 } 6834 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 6835 // Special case for 'a', which has type 'int' in C. 6836 // Note, however, that we do /not/ want to treat multibyte constants like 6837 // 'MooV' as characters! This form is deprecated but still exists. 6838 if (ExprTy == S.Context.IntTy) 6839 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 6840 ExprTy = S.Context.CharTy; 6841 } 6842 6843 // Look through enums to their underlying type. 6844 bool IsEnum = false; 6845 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 6846 ExprTy = EnumTy->getDecl()->getIntegerType(); 6847 IsEnum = true; 6848 } 6849 6850 // %C in an Objective-C context prints a unichar, not a wchar_t. 6851 // If the argument is an integer of some kind, believe the %C and suggest 6852 // a cast instead of changing the conversion specifier. 6853 QualType IntendedTy = ExprTy; 6854 if (isObjCContext() && 6855 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 6856 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 6857 !ExprTy->isCharType()) { 6858 // 'unichar' is defined as a typedef of unsigned short, but we should 6859 // prefer using the typedef if it is visible. 6860 IntendedTy = S.Context.UnsignedShortTy; 6861 6862 // While we are here, check if the value is an IntegerLiteral that happens 6863 // to be within the valid range. 6864 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 6865 const llvm::APInt &V = IL->getValue(); 6866 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 6867 return true; 6868 } 6869 6870 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(), 6871 Sema::LookupOrdinaryName); 6872 if (S.LookupName(Result, S.getCurScope())) { 6873 NamedDecl *ND = Result.getFoundDecl(); 6874 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 6875 if (TD->getUnderlyingType() == IntendedTy) 6876 IntendedTy = S.Context.getTypedefType(TD); 6877 } 6878 } 6879 } 6880 6881 // Special-case some of Darwin's platform-independence types by suggesting 6882 // casts to primitive types that are known to be large enough. 6883 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 6884 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 6885 QualType CastTy; 6886 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 6887 if (!CastTy.isNull()) { 6888 // %zi/%zu are OK to use for NSInteger/NSUInteger of type int 6889 // (long in ASTContext). Only complain to pedants. 6890 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 6891 AT.isSizeT() && AT.matchesType(S.Context, CastTy)) 6892 Pedantic = true; 6893 IntendedTy = CastTy; 6894 ShouldNotPrintDirectly = true; 6895 } 6896 } 6897 6898 // We may be able to offer a FixItHint if it is a supported type. 6899 PrintfSpecifier fixedFS = FS; 6900 bool Success = 6901 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 6902 6903 if (Success) { 6904 // Get the fix string from the fixed format specifier 6905 SmallString<16> buf; 6906 llvm::raw_svector_ostream os(buf); 6907 fixedFS.toString(os); 6908 6909 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 6910 6911 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 6912 unsigned Diag = 6913 Pedantic 6914 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 6915 : diag::warn_format_conversion_argument_type_mismatch; 6916 // In this case, the specifier is wrong and should be changed to match 6917 // the argument. 6918 EmitFormatDiagnostic(S.PDiag(Diag) 6919 << AT.getRepresentativeTypeName(S.Context) 6920 << IntendedTy << IsEnum << E->getSourceRange(), 6921 E->getLocStart(), 6922 /*IsStringLocation*/ false, SpecRange, 6923 FixItHint::CreateReplacement(SpecRange, os.str())); 6924 } else { 6925 // The canonical type for formatting this value is different from the 6926 // actual type of the expression. (This occurs, for example, with Darwin's 6927 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 6928 // should be printed as 'long' for 64-bit compatibility.) 6929 // Rather than emitting a normal format/argument mismatch, we want to 6930 // add a cast to the recommended type (and correct the format string 6931 // if necessary). 6932 SmallString<16> CastBuf; 6933 llvm::raw_svector_ostream CastFix(CastBuf); 6934 CastFix << "("; 6935 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 6936 CastFix << ")"; 6937 6938 SmallVector<FixItHint,4> Hints; 6939 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 6940 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 6941 6942 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 6943 // If there's already a cast present, just replace it. 6944 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 6945 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 6946 6947 } else if (!requiresParensToAddCast(E)) { 6948 // If the expression has high enough precedence, 6949 // just write the C-style cast. 6950 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6951 CastFix.str())); 6952 } else { 6953 // Otherwise, add parens around the expression as well as the cast. 6954 CastFix << "("; 6955 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(), 6956 CastFix.str())); 6957 6958 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd()); 6959 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 6960 } 6961 6962 if (ShouldNotPrintDirectly) { 6963 // The expression has a type that should not be printed directly. 6964 // We extract the name from the typedef because we don't want to show 6965 // the underlying type in the diagnostic. 6966 StringRef Name; 6967 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 6968 Name = TypedefTy->getDecl()->getName(); 6969 else 6970 Name = CastTyName; 6971 unsigned Diag = Pedantic 6972 ? diag::warn_format_argument_needs_cast_pedantic 6973 : diag::warn_format_argument_needs_cast; 6974 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 6975 << E->getSourceRange(), 6976 E->getLocStart(), /*IsStringLocation=*/false, 6977 SpecRange, Hints); 6978 } else { 6979 // In this case, the expression could be printed using a different 6980 // specifier, but we've decided that the specifier is probably correct 6981 // and we should cast instead. Just use the normal warning message. 6982 EmitFormatDiagnostic( 6983 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 6984 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 6985 << E->getSourceRange(), 6986 E->getLocStart(), /*IsStringLocation*/false, 6987 SpecRange, Hints); 6988 } 6989 } 6990 } else { 6991 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 6992 SpecifierLen); 6993 // Since the warning for passing non-POD types to variadic functions 6994 // was deferred until now, we emit a warning for non-POD 6995 // arguments here. 6996 switch (S.isValidVarArgType(ExprTy)) { 6997 case Sema::VAK_Valid: 6998 case Sema::VAK_ValidInCXX11: { 6999 unsigned Diag = 7000 Pedantic 7001 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7002 : diag::warn_format_conversion_argument_type_mismatch; 7003 7004 EmitFormatDiagnostic( 7005 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7006 << IsEnum << CSR << E->getSourceRange(), 7007 E->getLocStart(), /*IsStringLocation*/ false, CSR); 7008 break; 7009 } 7010 case Sema::VAK_Undefined: 7011 case Sema::VAK_MSVCUndefined: 7012 EmitFormatDiagnostic( 7013 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 7014 << S.getLangOpts().CPlusPlus11 7015 << ExprTy 7016 << CallType 7017 << AT.getRepresentativeTypeName(S.Context) 7018 << CSR 7019 << E->getSourceRange(), 7020 E->getLocStart(), /*IsStringLocation*/false, CSR); 7021 checkForCStrMembers(AT, E); 7022 break; 7023 7024 case Sema::VAK_Invalid: 7025 if (ExprTy->isObjCObjectType()) 7026 EmitFormatDiagnostic( 7027 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7028 << S.getLangOpts().CPlusPlus11 7029 << ExprTy 7030 << CallType 7031 << AT.getRepresentativeTypeName(S.Context) 7032 << CSR 7033 << E->getSourceRange(), 7034 E->getLocStart(), /*IsStringLocation*/false, CSR); 7035 else 7036 // FIXME: If this is an initializer list, suggest removing the braces 7037 // or inserting a cast to the target type. 7038 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format) 7039 << isa<InitListExpr>(E) << ExprTy << CallType 7040 << AT.getRepresentativeTypeName(S.Context) 7041 << E->getSourceRange(); 7042 break; 7043 } 7044 7045 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7046 "format string specifier index out of range"); 7047 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7048 } 7049 7050 return true; 7051 } 7052 7053 //===--- CHECK: Scanf format string checking ------------------------------===// 7054 7055 namespace { 7056 7057 class CheckScanfHandler : public CheckFormatHandler { 7058 public: 7059 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7060 const Expr *origFormatExpr, Sema::FormatStringType type, 7061 unsigned firstDataArg, unsigned numDataArgs, 7062 const char *beg, bool hasVAListArg, 7063 ArrayRef<const Expr *> Args, unsigned formatIdx, 7064 bool inFunctionCall, Sema::VariadicCallType CallType, 7065 llvm::SmallBitVector &CheckedVarArgs, 7066 UncoveredArgHandler &UncoveredArg) 7067 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7068 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7069 inFunctionCall, CallType, CheckedVarArgs, 7070 UncoveredArg) {} 7071 7072 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7073 const char *startSpecifier, 7074 unsigned specifierLen) override; 7075 7076 bool HandleInvalidScanfConversionSpecifier( 7077 const analyze_scanf::ScanfSpecifier &FS, 7078 const char *startSpecifier, 7079 unsigned specifierLen) override; 7080 7081 void HandleIncompleteScanList(const char *start, const char *end) override; 7082 }; 7083 7084 } // namespace 7085 7086 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7087 const char *end) { 7088 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7089 getLocationOfByte(end), /*IsStringLocation*/true, 7090 getSpecifierRange(start, end - start)); 7091 } 7092 7093 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7094 const analyze_scanf::ScanfSpecifier &FS, 7095 const char *startSpecifier, 7096 unsigned specifierLen) { 7097 const analyze_scanf::ScanfConversionSpecifier &CS = 7098 FS.getConversionSpecifier(); 7099 7100 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7101 getLocationOfByte(CS.getStart()), 7102 startSpecifier, specifierLen, 7103 CS.getStart(), CS.getLength()); 7104 } 7105 7106 bool CheckScanfHandler::HandleScanfSpecifier( 7107 const analyze_scanf::ScanfSpecifier &FS, 7108 const char *startSpecifier, 7109 unsigned specifierLen) { 7110 using namespace analyze_scanf; 7111 using namespace analyze_format_string; 7112 7113 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 7114 7115 // Handle case where '%' and '*' don't consume an argument. These shouldn't 7116 // be used to decide if we are using positional arguments consistently. 7117 if (FS.consumesDataArgument()) { 7118 if (atFirstArg) { 7119 atFirstArg = false; 7120 usesPositionalArgs = FS.usesPositionalArg(); 7121 } 7122 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7123 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7124 startSpecifier, specifierLen); 7125 return false; 7126 } 7127 } 7128 7129 // Check if the field with is non-zero. 7130 const OptionalAmount &Amt = FS.getFieldWidth(); 7131 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 7132 if (Amt.getConstantAmount() == 0) { 7133 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 7134 Amt.getConstantLength()); 7135 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 7136 getLocationOfByte(Amt.getStart()), 7137 /*IsStringLocation*/true, R, 7138 FixItHint::CreateRemoval(R)); 7139 } 7140 } 7141 7142 if (!FS.consumesDataArgument()) { 7143 // FIXME: Technically specifying a precision or field width here 7144 // makes no sense. Worth issuing a warning at some point. 7145 return true; 7146 } 7147 7148 // Consume the argument. 7149 unsigned argIndex = FS.getArgIndex(); 7150 if (argIndex < NumDataArgs) { 7151 // The check to see if the argIndex is valid will come later. 7152 // We set the bit here because we may exit early from this 7153 // function if we encounter some other error. 7154 CoveredArgs.set(argIndex); 7155 } 7156 7157 // Check the length modifier is valid with the given conversion specifier. 7158 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7159 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7160 diag::warn_format_nonsensical_length); 7161 else if (!FS.hasStandardLengthModifier()) 7162 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7163 else if (!FS.hasStandardLengthConversionCombination()) 7164 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7165 diag::warn_format_non_standard_conversion_spec); 7166 7167 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7168 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7169 7170 // The remaining checks depend on the data arguments. 7171 if (HasVAListArg) 7172 return true; 7173 7174 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7175 return false; 7176 7177 // Check that the argument type matches the format specifier. 7178 const Expr *Ex = getDataArg(argIndex); 7179 if (!Ex) 7180 return true; 7181 7182 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 7183 7184 if (!AT.isValid()) { 7185 return true; 7186 } 7187 7188 analyze_format_string::ArgType::MatchKind Match = 7189 AT.matchesType(S.Context, Ex->getType()); 7190 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 7191 if (Match == analyze_format_string::ArgType::Match) 7192 return true; 7193 7194 ScanfSpecifier fixedFS = FS; 7195 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 7196 S.getLangOpts(), S.Context); 7197 7198 unsigned Diag = 7199 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7200 : diag::warn_format_conversion_argument_type_mismatch; 7201 7202 if (Success) { 7203 // Get the fix string from the fixed format specifier. 7204 SmallString<128> buf; 7205 llvm::raw_svector_ostream os(buf); 7206 fixedFS.toString(os); 7207 7208 EmitFormatDiagnostic( 7209 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 7210 << Ex->getType() << false << Ex->getSourceRange(), 7211 Ex->getLocStart(), 7212 /*IsStringLocation*/ false, 7213 getSpecifierRange(startSpecifier, specifierLen), 7214 FixItHint::CreateReplacement( 7215 getSpecifierRange(startSpecifier, specifierLen), os.str())); 7216 } else { 7217 EmitFormatDiagnostic(S.PDiag(Diag) 7218 << AT.getRepresentativeTypeName(S.Context) 7219 << Ex->getType() << false << Ex->getSourceRange(), 7220 Ex->getLocStart(), 7221 /*IsStringLocation*/ false, 7222 getSpecifierRange(startSpecifier, specifierLen)); 7223 } 7224 7225 return true; 7226 } 7227 7228 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7229 const Expr *OrigFormatExpr, 7230 ArrayRef<const Expr *> Args, 7231 bool HasVAListArg, unsigned format_idx, 7232 unsigned firstDataArg, 7233 Sema::FormatStringType Type, 7234 bool inFunctionCall, 7235 Sema::VariadicCallType CallType, 7236 llvm::SmallBitVector &CheckedVarArgs, 7237 UncoveredArgHandler &UncoveredArg) { 7238 // CHECK: is the format string a wide literal? 7239 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 7240 CheckFormatHandler::EmitFormatDiagnostic( 7241 S, inFunctionCall, Args[format_idx], 7242 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(), 7243 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7244 return; 7245 } 7246 7247 // Str - The format string. NOTE: this is NOT null-terminated! 7248 StringRef StrRef = FExpr->getString(); 7249 const char *Str = StrRef.data(); 7250 // Account for cases where the string literal is truncated in a declaration. 7251 const ConstantArrayType *T = 7252 S.Context.getAsConstantArrayType(FExpr->getType()); 7253 assert(T && "String literal not of constant array type!"); 7254 size_t TypeSize = T->getSize().getZExtValue(); 7255 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7256 const unsigned numDataArgs = Args.size() - firstDataArg; 7257 7258 // Emit a warning if the string literal is truncated and does not contain an 7259 // embedded null character. 7260 if (TypeSize <= StrRef.size() && 7261 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 7262 CheckFormatHandler::EmitFormatDiagnostic( 7263 S, inFunctionCall, Args[format_idx], 7264 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 7265 FExpr->getLocStart(), 7266 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 7267 return; 7268 } 7269 7270 // CHECK: empty format string? 7271 if (StrLen == 0 && numDataArgs > 0) { 7272 CheckFormatHandler::EmitFormatDiagnostic( 7273 S, inFunctionCall, Args[format_idx], 7274 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(), 7275 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange()); 7276 return; 7277 } 7278 7279 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 7280 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 7281 Type == Sema::FST_OSTrace) { 7282 CheckPrintfHandler H( 7283 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 7284 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 7285 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 7286 CheckedVarArgs, UncoveredArg); 7287 7288 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 7289 S.getLangOpts(), 7290 S.Context.getTargetInfo(), 7291 Type == Sema::FST_FreeBSDKPrintf)) 7292 H.DoneProcessing(); 7293 } else if (Type == Sema::FST_Scanf) { 7294 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 7295 numDataArgs, Str, HasVAListArg, Args, format_idx, 7296 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 7297 7298 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 7299 S.getLangOpts(), 7300 S.Context.getTargetInfo())) 7301 H.DoneProcessing(); 7302 } // TODO: handle other formats 7303 } 7304 7305 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 7306 // Str - The format string. NOTE: this is NOT null-terminated! 7307 StringRef StrRef = FExpr->getString(); 7308 const char *Str = StrRef.data(); 7309 // Account for cases where the string literal is truncated in a declaration. 7310 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 7311 assert(T && "String literal not of constant array type!"); 7312 size_t TypeSize = T->getSize().getZExtValue(); 7313 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 7314 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 7315 getLangOpts(), 7316 Context.getTargetInfo()); 7317 } 7318 7319 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 7320 7321 // Returns the related absolute value function that is larger, of 0 if one 7322 // does not exist. 7323 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 7324 switch (AbsFunction) { 7325 default: 7326 return 0; 7327 7328 case Builtin::BI__builtin_abs: 7329 return Builtin::BI__builtin_labs; 7330 case Builtin::BI__builtin_labs: 7331 return Builtin::BI__builtin_llabs; 7332 case Builtin::BI__builtin_llabs: 7333 return 0; 7334 7335 case Builtin::BI__builtin_fabsf: 7336 return Builtin::BI__builtin_fabs; 7337 case Builtin::BI__builtin_fabs: 7338 return Builtin::BI__builtin_fabsl; 7339 case Builtin::BI__builtin_fabsl: 7340 return 0; 7341 7342 case Builtin::BI__builtin_cabsf: 7343 return Builtin::BI__builtin_cabs; 7344 case Builtin::BI__builtin_cabs: 7345 return Builtin::BI__builtin_cabsl; 7346 case Builtin::BI__builtin_cabsl: 7347 return 0; 7348 7349 case Builtin::BIabs: 7350 return Builtin::BIlabs; 7351 case Builtin::BIlabs: 7352 return Builtin::BIllabs; 7353 case Builtin::BIllabs: 7354 return 0; 7355 7356 case Builtin::BIfabsf: 7357 return Builtin::BIfabs; 7358 case Builtin::BIfabs: 7359 return Builtin::BIfabsl; 7360 case Builtin::BIfabsl: 7361 return 0; 7362 7363 case Builtin::BIcabsf: 7364 return Builtin::BIcabs; 7365 case Builtin::BIcabs: 7366 return Builtin::BIcabsl; 7367 case Builtin::BIcabsl: 7368 return 0; 7369 } 7370 } 7371 7372 // Returns the argument type of the absolute value function. 7373 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 7374 unsigned AbsType) { 7375 if (AbsType == 0) 7376 return QualType(); 7377 7378 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 7379 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 7380 if (Error != ASTContext::GE_None) 7381 return QualType(); 7382 7383 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 7384 if (!FT) 7385 return QualType(); 7386 7387 if (FT->getNumParams() != 1) 7388 return QualType(); 7389 7390 return FT->getParamType(0); 7391 } 7392 7393 // Returns the best absolute value function, or zero, based on type and 7394 // current absolute value function. 7395 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 7396 unsigned AbsFunctionKind) { 7397 unsigned BestKind = 0; 7398 uint64_t ArgSize = Context.getTypeSize(ArgType); 7399 for (unsigned Kind = AbsFunctionKind; Kind != 0; 7400 Kind = getLargerAbsoluteValueFunction(Kind)) { 7401 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 7402 if (Context.getTypeSize(ParamType) >= ArgSize) { 7403 if (BestKind == 0) 7404 BestKind = Kind; 7405 else if (Context.hasSameType(ParamType, ArgType)) { 7406 BestKind = Kind; 7407 break; 7408 } 7409 } 7410 } 7411 return BestKind; 7412 } 7413 7414 enum AbsoluteValueKind { 7415 AVK_Integer, 7416 AVK_Floating, 7417 AVK_Complex 7418 }; 7419 7420 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 7421 if (T->isIntegralOrEnumerationType()) 7422 return AVK_Integer; 7423 if (T->isRealFloatingType()) 7424 return AVK_Floating; 7425 if (T->isAnyComplexType()) 7426 return AVK_Complex; 7427 7428 llvm_unreachable("Type not integer, floating, or complex"); 7429 } 7430 7431 // Changes the absolute value function to a different type. Preserves whether 7432 // the function is a builtin. 7433 static unsigned changeAbsFunction(unsigned AbsKind, 7434 AbsoluteValueKind ValueKind) { 7435 switch (ValueKind) { 7436 case AVK_Integer: 7437 switch (AbsKind) { 7438 default: 7439 return 0; 7440 case Builtin::BI__builtin_fabsf: 7441 case Builtin::BI__builtin_fabs: 7442 case Builtin::BI__builtin_fabsl: 7443 case Builtin::BI__builtin_cabsf: 7444 case Builtin::BI__builtin_cabs: 7445 case Builtin::BI__builtin_cabsl: 7446 return Builtin::BI__builtin_abs; 7447 case Builtin::BIfabsf: 7448 case Builtin::BIfabs: 7449 case Builtin::BIfabsl: 7450 case Builtin::BIcabsf: 7451 case Builtin::BIcabs: 7452 case Builtin::BIcabsl: 7453 return Builtin::BIabs; 7454 } 7455 case AVK_Floating: 7456 switch (AbsKind) { 7457 default: 7458 return 0; 7459 case Builtin::BI__builtin_abs: 7460 case Builtin::BI__builtin_labs: 7461 case Builtin::BI__builtin_llabs: 7462 case Builtin::BI__builtin_cabsf: 7463 case Builtin::BI__builtin_cabs: 7464 case Builtin::BI__builtin_cabsl: 7465 return Builtin::BI__builtin_fabsf; 7466 case Builtin::BIabs: 7467 case Builtin::BIlabs: 7468 case Builtin::BIllabs: 7469 case Builtin::BIcabsf: 7470 case Builtin::BIcabs: 7471 case Builtin::BIcabsl: 7472 return Builtin::BIfabsf; 7473 } 7474 case AVK_Complex: 7475 switch (AbsKind) { 7476 default: 7477 return 0; 7478 case Builtin::BI__builtin_abs: 7479 case Builtin::BI__builtin_labs: 7480 case Builtin::BI__builtin_llabs: 7481 case Builtin::BI__builtin_fabsf: 7482 case Builtin::BI__builtin_fabs: 7483 case Builtin::BI__builtin_fabsl: 7484 return Builtin::BI__builtin_cabsf; 7485 case Builtin::BIabs: 7486 case Builtin::BIlabs: 7487 case Builtin::BIllabs: 7488 case Builtin::BIfabsf: 7489 case Builtin::BIfabs: 7490 case Builtin::BIfabsl: 7491 return Builtin::BIcabsf; 7492 } 7493 } 7494 llvm_unreachable("Unable to convert function"); 7495 } 7496 7497 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 7498 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 7499 if (!FnInfo) 7500 return 0; 7501 7502 switch (FDecl->getBuiltinID()) { 7503 default: 7504 return 0; 7505 case Builtin::BI__builtin_abs: 7506 case Builtin::BI__builtin_fabs: 7507 case Builtin::BI__builtin_fabsf: 7508 case Builtin::BI__builtin_fabsl: 7509 case Builtin::BI__builtin_labs: 7510 case Builtin::BI__builtin_llabs: 7511 case Builtin::BI__builtin_cabs: 7512 case Builtin::BI__builtin_cabsf: 7513 case Builtin::BI__builtin_cabsl: 7514 case Builtin::BIabs: 7515 case Builtin::BIlabs: 7516 case Builtin::BIllabs: 7517 case Builtin::BIfabs: 7518 case Builtin::BIfabsf: 7519 case Builtin::BIfabsl: 7520 case Builtin::BIcabs: 7521 case Builtin::BIcabsf: 7522 case Builtin::BIcabsl: 7523 return FDecl->getBuiltinID(); 7524 } 7525 llvm_unreachable("Unknown Builtin type"); 7526 } 7527 7528 // If the replacement is valid, emit a note with replacement function. 7529 // Additionally, suggest including the proper header if not already included. 7530 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 7531 unsigned AbsKind, QualType ArgType) { 7532 bool EmitHeaderHint = true; 7533 const char *HeaderName = nullptr; 7534 const char *FunctionName = nullptr; 7535 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 7536 FunctionName = "std::abs"; 7537 if (ArgType->isIntegralOrEnumerationType()) { 7538 HeaderName = "cstdlib"; 7539 } else if (ArgType->isRealFloatingType()) { 7540 HeaderName = "cmath"; 7541 } else { 7542 llvm_unreachable("Invalid Type"); 7543 } 7544 7545 // Lookup all std::abs 7546 if (NamespaceDecl *Std = S.getStdNamespace()) { 7547 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 7548 R.suppressDiagnostics(); 7549 S.LookupQualifiedName(R, Std); 7550 7551 for (const auto *I : R) { 7552 const FunctionDecl *FDecl = nullptr; 7553 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 7554 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 7555 } else { 7556 FDecl = dyn_cast<FunctionDecl>(I); 7557 } 7558 if (!FDecl) 7559 continue; 7560 7561 // Found std::abs(), check that they are the right ones. 7562 if (FDecl->getNumParams() != 1) 7563 continue; 7564 7565 // Check that the parameter type can handle the argument. 7566 QualType ParamType = FDecl->getParamDecl(0)->getType(); 7567 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 7568 S.Context.getTypeSize(ArgType) <= 7569 S.Context.getTypeSize(ParamType)) { 7570 // Found a function, don't need the header hint. 7571 EmitHeaderHint = false; 7572 break; 7573 } 7574 } 7575 } 7576 } else { 7577 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 7578 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 7579 7580 if (HeaderName) { 7581 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 7582 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 7583 R.suppressDiagnostics(); 7584 S.LookupName(R, S.getCurScope()); 7585 7586 if (R.isSingleResult()) { 7587 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 7588 if (FD && FD->getBuiltinID() == AbsKind) { 7589 EmitHeaderHint = false; 7590 } else { 7591 return; 7592 } 7593 } else if (!R.empty()) { 7594 return; 7595 } 7596 } 7597 } 7598 7599 S.Diag(Loc, diag::note_replace_abs_function) 7600 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 7601 7602 if (!HeaderName) 7603 return; 7604 7605 if (!EmitHeaderHint) 7606 return; 7607 7608 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 7609 << FunctionName; 7610 } 7611 7612 template <std::size_t StrLen> 7613 static bool IsStdFunction(const FunctionDecl *FDecl, 7614 const char (&Str)[StrLen]) { 7615 if (!FDecl) 7616 return false; 7617 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 7618 return false; 7619 if (!FDecl->isInStdNamespace()) 7620 return false; 7621 7622 return true; 7623 } 7624 7625 // Warn when using the wrong abs() function. 7626 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 7627 const FunctionDecl *FDecl) { 7628 if (Call->getNumArgs() != 1) 7629 return; 7630 7631 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 7632 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 7633 if (AbsKind == 0 && !IsStdAbs) 7634 return; 7635 7636 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7637 QualType ParamType = Call->getArg(0)->getType(); 7638 7639 // Unsigned types cannot be negative. Suggest removing the absolute value 7640 // function call. 7641 if (ArgType->isUnsignedIntegerType()) { 7642 const char *FunctionName = 7643 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 7644 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 7645 Diag(Call->getExprLoc(), diag::note_remove_abs) 7646 << FunctionName 7647 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 7648 return; 7649 } 7650 7651 // Taking the absolute value of a pointer is very suspicious, they probably 7652 // wanted to index into an array, dereference a pointer, call a function, etc. 7653 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 7654 unsigned DiagType = 0; 7655 if (ArgType->isFunctionType()) 7656 DiagType = 1; 7657 else if (ArgType->isArrayType()) 7658 DiagType = 2; 7659 7660 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 7661 return; 7662 } 7663 7664 // std::abs has overloads which prevent most of the absolute value problems 7665 // from occurring. 7666 if (IsStdAbs) 7667 return; 7668 7669 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 7670 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 7671 7672 // The argument and parameter are the same kind. Check if they are the right 7673 // size. 7674 if (ArgValueKind == ParamValueKind) { 7675 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 7676 return; 7677 7678 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 7679 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 7680 << FDecl << ArgType << ParamType; 7681 7682 if (NewAbsKind == 0) 7683 return; 7684 7685 emitReplacement(*this, Call->getExprLoc(), 7686 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7687 return; 7688 } 7689 7690 // ArgValueKind != ParamValueKind 7691 // The wrong type of absolute value function was used. Attempt to find the 7692 // proper one. 7693 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 7694 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 7695 if (NewAbsKind == 0) 7696 return; 7697 7698 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 7699 << FDecl << ParamValueKind << ArgValueKind; 7700 7701 emitReplacement(*this, Call->getExprLoc(), 7702 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 7703 } 7704 7705 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 7706 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 7707 const FunctionDecl *FDecl) { 7708 if (!Call || !FDecl) return; 7709 7710 // Ignore template specializations and macros. 7711 if (inTemplateInstantiation()) return; 7712 if (Call->getExprLoc().isMacroID()) return; 7713 7714 // Only care about the one template argument, two function parameter std::max 7715 if (Call->getNumArgs() != 2) return; 7716 if (!IsStdFunction(FDecl, "max")) return; 7717 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 7718 if (!ArgList) return; 7719 if (ArgList->size() != 1) return; 7720 7721 // Check that template type argument is unsigned integer. 7722 const auto& TA = ArgList->get(0); 7723 if (TA.getKind() != TemplateArgument::Type) return; 7724 QualType ArgType = TA.getAsType(); 7725 if (!ArgType->isUnsignedIntegerType()) return; 7726 7727 // See if either argument is a literal zero. 7728 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 7729 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 7730 if (!MTE) return false; 7731 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 7732 if (!Num) return false; 7733 if (Num->getValue() != 0) return false; 7734 return true; 7735 }; 7736 7737 const Expr *FirstArg = Call->getArg(0); 7738 const Expr *SecondArg = Call->getArg(1); 7739 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 7740 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 7741 7742 // Only warn when exactly one argument is zero. 7743 if (IsFirstArgZero == IsSecondArgZero) return; 7744 7745 SourceRange FirstRange = FirstArg->getSourceRange(); 7746 SourceRange SecondRange = SecondArg->getSourceRange(); 7747 7748 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 7749 7750 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 7751 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 7752 7753 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 7754 SourceRange RemovalRange; 7755 if (IsFirstArgZero) { 7756 RemovalRange = SourceRange(FirstRange.getBegin(), 7757 SecondRange.getBegin().getLocWithOffset(-1)); 7758 } else { 7759 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 7760 SecondRange.getEnd()); 7761 } 7762 7763 Diag(Call->getExprLoc(), diag::note_remove_max_call) 7764 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 7765 << FixItHint::CreateRemoval(RemovalRange); 7766 } 7767 7768 //===--- CHECK: Standard memory functions ---------------------------------===// 7769 7770 /// Takes the expression passed to the size_t parameter of functions 7771 /// such as memcmp, strncat, etc and warns if it's a comparison. 7772 /// 7773 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 7774 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 7775 IdentifierInfo *FnName, 7776 SourceLocation FnLoc, 7777 SourceLocation RParenLoc) { 7778 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 7779 if (!Size) 7780 return false; 7781 7782 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 7783 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 7784 return false; 7785 7786 SourceRange SizeRange = Size->getSourceRange(); 7787 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 7788 << SizeRange << FnName; 7789 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 7790 << FnName << FixItHint::CreateInsertion( 7791 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")") 7792 << FixItHint::CreateRemoval(RParenLoc); 7793 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 7794 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 7795 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 7796 ")"); 7797 7798 return true; 7799 } 7800 7801 /// Determine whether the given type is or contains a dynamic class type 7802 /// (e.g., whether it has a vtable). 7803 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 7804 bool &IsContained) { 7805 // Look through array types while ignoring qualifiers. 7806 const Type *Ty = T->getBaseElementTypeUnsafe(); 7807 IsContained = false; 7808 7809 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 7810 RD = RD ? RD->getDefinition() : nullptr; 7811 if (!RD || RD->isInvalidDecl()) 7812 return nullptr; 7813 7814 if (RD->isDynamicClass()) 7815 return RD; 7816 7817 // Check all the fields. If any bases were dynamic, the class is dynamic. 7818 // It's impossible for a class to transitively contain itself by value, so 7819 // infinite recursion is impossible. 7820 for (auto *FD : RD->fields()) { 7821 bool SubContained; 7822 if (const CXXRecordDecl *ContainedRD = 7823 getContainedDynamicClass(FD->getType(), SubContained)) { 7824 IsContained = true; 7825 return ContainedRD; 7826 } 7827 } 7828 7829 return nullptr; 7830 } 7831 7832 /// If E is a sizeof expression, returns its argument expression, 7833 /// otherwise returns NULL. 7834 static const Expr *getSizeOfExprArg(const Expr *E) { 7835 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7836 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7837 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType()) 7838 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 7839 7840 return nullptr; 7841 } 7842 7843 /// If E is a sizeof expression, returns its argument type. 7844 static QualType getSizeOfArgType(const Expr *E) { 7845 if (const UnaryExprOrTypeTraitExpr *SizeOf = 7846 dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 7847 if (SizeOf->getKind() == UETT_SizeOf) 7848 return SizeOf->getTypeOfArgument(); 7849 7850 return QualType(); 7851 } 7852 7853 namespace { 7854 7855 struct SearchNonTrivialToInitializeField 7856 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 7857 using Super = 7858 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 7859 7860 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 7861 7862 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 7863 SourceLocation SL) { 7864 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7865 asDerived().visitArray(PDIK, AT, SL); 7866 return; 7867 } 7868 7869 Super::visitWithKind(PDIK, FT, SL); 7870 } 7871 7872 void visitARCStrong(QualType FT, SourceLocation SL) { 7873 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7874 } 7875 void visitARCWeak(QualType FT, SourceLocation SL) { 7876 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 7877 } 7878 void visitStruct(QualType FT, SourceLocation SL) { 7879 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7880 visit(FD->getType(), FD->getLocation()); 7881 } 7882 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 7883 const ArrayType *AT, SourceLocation SL) { 7884 visit(getContext().getBaseElementType(AT), SL); 7885 } 7886 void visitTrivial(QualType FT, SourceLocation SL) {} 7887 7888 static void diag(QualType RT, const Expr *E, Sema &S) { 7889 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 7890 } 7891 7892 ASTContext &getContext() { return S.getASTContext(); } 7893 7894 const Expr *E; 7895 Sema &S; 7896 }; 7897 7898 struct SearchNonTrivialToCopyField 7899 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 7900 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 7901 7902 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 7903 7904 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 7905 SourceLocation SL) { 7906 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 7907 asDerived().visitArray(PCK, AT, SL); 7908 return; 7909 } 7910 7911 Super::visitWithKind(PCK, FT, SL); 7912 } 7913 7914 void visitARCStrong(QualType FT, SourceLocation SL) { 7915 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7916 } 7917 void visitARCWeak(QualType FT, SourceLocation SL) { 7918 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 7919 } 7920 void visitStruct(QualType FT, SourceLocation SL) { 7921 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 7922 visit(FD->getType(), FD->getLocation()); 7923 } 7924 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 7925 SourceLocation SL) { 7926 visit(getContext().getBaseElementType(AT), SL); 7927 } 7928 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 7929 SourceLocation SL) {} 7930 void visitTrivial(QualType FT, SourceLocation SL) {} 7931 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 7932 7933 static void diag(QualType RT, const Expr *E, Sema &S) { 7934 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 7935 } 7936 7937 ASTContext &getContext() { return S.getASTContext(); } 7938 7939 const Expr *E; 7940 Sema &S; 7941 }; 7942 7943 } 7944 7945 /// Check for dangerous or invalid arguments to memset(). 7946 /// 7947 /// This issues warnings on known problematic, dangerous or unspecified 7948 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 7949 /// function calls. 7950 /// 7951 /// \param Call The call expression to diagnose. 7952 void Sema::CheckMemaccessArguments(const CallExpr *Call, 7953 unsigned BId, 7954 IdentifierInfo *FnName) { 7955 assert(BId != 0); 7956 7957 // It is possible to have a non-standard definition of memset. Validate 7958 // we have enough arguments, and if not, abort further checking. 7959 unsigned ExpectedNumArgs = 7960 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 7961 if (Call->getNumArgs() < ExpectedNumArgs) 7962 return; 7963 7964 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 7965 BId == Builtin::BIstrndup ? 1 : 2); 7966 unsigned LenArg = 7967 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 7968 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 7969 7970 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 7971 Call->getLocStart(), Call->getRParenLoc())) 7972 return; 7973 7974 // We have special checking when the length is a sizeof expression. 7975 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 7976 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 7977 llvm::FoldingSetNodeID SizeOfArgID; 7978 7979 // Although widely used, 'bzero' is not a standard function. Be more strict 7980 // with the argument types before allowing diagnostics and only allow the 7981 // form bzero(ptr, sizeof(...)). 7982 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 7983 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 7984 return; 7985 7986 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 7987 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 7988 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 7989 7990 QualType DestTy = Dest->getType(); 7991 QualType PointeeTy; 7992 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 7993 PointeeTy = DestPtrTy->getPointeeType(); 7994 7995 // Never warn about void type pointers. This can be used to suppress 7996 // false positives. 7997 if (PointeeTy->isVoidType()) 7998 continue; 7999 8000 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 8001 // actually comparing the expressions for equality. Because computing the 8002 // expression IDs can be expensive, we only do this if the diagnostic is 8003 // enabled. 8004 if (SizeOfArg && 8005 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 8006 SizeOfArg->getExprLoc())) { 8007 // We only compute IDs for expressions if the warning is enabled, and 8008 // cache the sizeof arg's ID. 8009 if (SizeOfArgID == llvm::FoldingSetNodeID()) 8010 SizeOfArg->Profile(SizeOfArgID, Context, true); 8011 llvm::FoldingSetNodeID DestID; 8012 Dest->Profile(DestID, Context, true); 8013 if (DestID == SizeOfArgID) { 8014 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 8015 // over sizeof(src) as well. 8016 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 8017 StringRef ReadableName = FnName->getName(); 8018 8019 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 8020 if (UnaryOp->getOpcode() == UO_AddrOf) 8021 ActionIdx = 1; // If its an address-of operator, just remove it. 8022 if (!PointeeTy->isIncompleteType() && 8023 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 8024 ActionIdx = 2; // If the pointee's size is sizeof(char), 8025 // suggest an explicit length. 8026 8027 // If the function is defined as a builtin macro, do not show macro 8028 // expansion. 8029 SourceLocation SL = SizeOfArg->getExprLoc(); 8030 SourceRange DSR = Dest->getSourceRange(); 8031 SourceRange SSR = SizeOfArg->getSourceRange(); 8032 SourceManager &SM = getSourceManager(); 8033 8034 if (SM.isMacroArgExpansion(SL)) { 8035 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 8036 SL = SM.getSpellingLoc(SL); 8037 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 8038 SM.getSpellingLoc(DSR.getEnd())); 8039 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 8040 SM.getSpellingLoc(SSR.getEnd())); 8041 } 8042 8043 DiagRuntimeBehavior(SL, SizeOfArg, 8044 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 8045 << ReadableName 8046 << PointeeTy 8047 << DestTy 8048 << DSR 8049 << SSR); 8050 DiagRuntimeBehavior(SL, SizeOfArg, 8051 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 8052 << ActionIdx 8053 << SSR); 8054 8055 break; 8056 } 8057 } 8058 8059 // Also check for cases where the sizeof argument is the exact same 8060 // type as the memory argument, and where it points to a user-defined 8061 // record type. 8062 if (SizeOfArgTy != QualType()) { 8063 if (PointeeTy->isRecordType() && 8064 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 8065 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 8066 PDiag(diag::warn_sizeof_pointer_type_memaccess) 8067 << FnName << SizeOfArgTy << ArgIdx 8068 << PointeeTy << Dest->getSourceRange() 8069 << LenExpr->getSourceRange()); 8070 break; 8071 } 8072 } 8073 } else if (DestTy->isArrayType()) { 8074 PointeeTy = DestTy; 8075 } 8076 8077 if (PointeeTy == QualType()) 8078 continue; 8079 8080 // Always complain about dynamic classes. 8081 bool IsContained; 8082 if (const CXXRecordDecl *ContainedRD = 8083 getContainedDynamicClass(PointeeTy, IsContained)) { 8084 8085 unsigned OperationType = 0; 8086 // "overwritten" if we're warning about the destination for any call 8087 // but memcmp; otherwise a verb appropriate to the call. 8088 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 8089 if (BId == Builtin::BImemcpy) 8090 OperationType = 1; 8091 else if(BId == Builtin::BImemmove) 8092 OperationType = 2; 8093 else if (BId == Builtin::BImemcmp) 8094 OperationType = 3; 8095 } 8096 8097 DiagRuntimeBehavior( 8098 Dest->getExprLoc(), Dest, 8099 PDiag(diag::warn_dyn_class_memaccess) 8100 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 8101 << FnName << IsContained << ContainedRD << OperationType 8102 << Call->getCallee()->getSourceRange()); 8103 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 8104 BId != Builtin::BImemset) 8105 DiagRuntimeBehavior( 8106 Dest->getExprLoc(), Dest, 8107 PDiag(diag::warn_arc_object_memaccess) 8108 << ArgIdx << FnName << PointeeTy 8109 << Call->getCallee()->getSourceRange()); 8110 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 8111 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 8112 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 8113 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 8114 PDiag(diag::warn_cstruct_memaccess) 8115 << ArgIdx << FnName << PointeeTy << 0); 8116 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 8117 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 8118 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 8119 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 8120 PDiag(diag::warn_cstruct_memaccess) 8121 << ArgIdx << FnName << PointeeTy << 1); 8122 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 8123 } else { 8124 continue; 8125 } 8126 } else 8127 continue; 8128 8129 DiagRuntimeBehavior( 8130 Dest->getExprLoc(), Dest, 8131 PDiag(diag::note_bad_memaccess_silence) 8132 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 8133 break; 8134 } 8135 } 8136 8137 // A little helper routine: ignore addition and subtraction of integer literals. 8138 // This intentionally does not ignore all integer constant expressions because 8139 // we don't want to remove sizeof(). 8140 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 8141 Ex = Ex->IgnoreParenCasts(); 8142 8143 while (true) { 8144 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 8145 if (!BO || !BO->isAdditiveOp()) 8146 break; 8147 8148 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 8149 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 8150 8151 if (isa<IntegerLiteral>(RHS)) 8152 Ex = LHS; 8153 else if (isa<IntegerLiteral>(LHS)) 8154 Ex = RHS; 8155 else 8156 break; 8157 } 8158 8159 return Ex; 8160 } 8161 8162 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 8163 ASTContext &Context) { 8164 // Only handle constant-sized or VLAs, but not flexible members. 8165 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 8166 // Only issue the FIXIT for arrays of size > 1. 8167 if (CAT->getSize().getSExtValue() <= 1) 8168 return false; 8169 } else if (!Ty->isVariableArrayType()) { 8170 return false; 8171 } 8172 return true; 8173 } 8174 8175 // Warn if the user has made the 'size' argument to strlcpy or strlcat 8176 // be the size of the source, instead of the destination. 8177 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 8178 IdentifierInfo *FnName) { 8179 8180 // Don't crash if the user has the wrong number of arguments 8181 unsigned NumArgs = Call->getNumArgs(); 8182 if ((NumArgs != 3) && (NumArgs != 4)) 8183 return; 8184 8185 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 8186 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 8187 const Expr *CompareWithSrc = nullptr; 8188 8189 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 8190 Call->getLocStart(), Call->getRParenLoc())) 8191 return; 8192 8193 // Look for 'strlcpy(dst, x, sizeof(x))' 8194 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 8195 CompareWithSrc = Ex; 8196 else { 8197 // Look for 'strlcpy(dst, x, strlen(x))' 8198 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 8199 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 8200 SizeCall->getNumArgs() == 1) 8201 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 8202 } 8203 } 8204 8205 if (!CompareWithSrc) 8206 return; 8207 8208 // Determine if the argument to sizeof/strlen is equal to the source 8209 // argument. In principle there's all kinds of things you could do 8210 // here, for instance creating an == expression and evaluating it with 8211 // EvaluateAsBooleanCondition, but this uses a more direct technique: 8212 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 8213 if (!SrcArgDRE) 8214 return; 8215 8216 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 8217 if (!CompareWithSrcDRE || 8218 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 8219 return; 8220 8221 const Expr *OriginalSizeArg = Call->getArg(2); 8222 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size) 8223 << OriginalSizeArg->getSourceRange() << FnName; 8224 8225 // Output a FIXIT hint if the destination is an array (rather than a 8226 // pointer to an array). This could be enhanced to handle some 8227 // pointers if we know the actual size, like if DstArg is 'array+2' 8228 // we could say 'sizeof(array)-2'. 8229 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 8230 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 8231 return; 8232 8233 SmallString<128> sizeString; 8234 llvm::raw_svector_ostream OS(sizeString); 8235 OS << "sizeof("; 8236 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8237 OS << ")"; 8238 8239 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size) 8240 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 8241 OS.str()); 8242 } 8243 8244 /// Check if two expressions refer to the same declaration. 8245 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 8246 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 8247 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 8248 return D1->getDecl() == D2->getDecl(); 8249 return false; 8250 } 8251 8252 static const Expr *getStrlenExprArg(const Expr *E) { 8253 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8254 const FunctionDecl *FD = CE->getDirectCallee(); 8255 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 8256 return nullptr; 8257 return CE->getArg(0)->IgnoreParenCasts(); 8258 } 8259 return nullptr; 8260 } 8261 8262 // Warn on anti-patterns as the 'size' argument to strncat. 8263 // The correct size argument should look like following: 8264 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 8265 void Sema::CheckStrncatArguments(const CallExpr *CE, 8266 IdentifierInfo *FnName) { 8267 // Don't crash if the user has the wrong number of arguments. 8268 if (CE->getNumArgs() < 3) 8269 return; 8270 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 8271 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 8272 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 8273 8274 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(), 8275 CE->getRParenLoc())) 8276 return; 8277 8278 // Identify common expressions, which are wrongly used as the size argument 8279 // to strncat and may lead to buffer overflows. 8280 unsigned PatternType = 0; 8281 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 8282 // - sizeof(dst) 8283 if (referToTheSameDecl(SizeOfArg, DstArg)) 8284 PatternType = 1; 8285 // - sizeof(src) 8286 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 8287 PatternType = 2; 8288 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 8289 if (BE->getOpcode() == BO_Sub) { 8290 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 8291 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 8292 // - sizeof(dst) - strlen(dst) 8293 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 8294 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 8295 PatternType = 1; 8296 // - sizeof(src) - (anything) 8297 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 8298 PatternType = 2; 8299 } 8300 } 8301 8302 if (PatternType == 0) 8303 return; 8304 8305 // Generate the diagnostic. 8306 SourceLocation SL = LenArg->getLocStart(); 8307 SourceRange SR = LenArg->getSourceRange(); 8308 SourceManager &SM = getSourceManager(); 8309 8310 // If the function is defined as a builtin macro, do not show macro expansion. 8311 if (SM.isMacroArgExpansion(SL)) { 8312 SL = SM.getSpellingLoc(SL); 8313 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 8314 SM.getSpellingLoc(SR.getEnd())); 8315 } 8316 8317 // Check if the destination is an array (rather than a pointer to an array). 8318 QualType DstTy = DstArg->getType(); 8319 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 8320 Context); 8321 if (!isKnownSizeArray) { 8322 if (PatternType == 1) 8323 Diag(SL, diag::warn_strncat_wrong_size) << SR; 8324 else 8325 Diag(SL, diag::warn_strncat_src_size) << SR; 8326 return; 8327 } 8328 8329 if (PatternType == 1) 8330 Diag(SL, diag::warn_strncat_large_size) << SR; 8331 else 8332 Diag(SL, diag::warn_strncat_src_size) << SR; 8333 8334 SmallString<128> sizeString; 8335 llvm::raw_svector_ostream OS(sizeString); 8336 OS << "sizeof("; 8337 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8338 OS << ") - "; 8339 OS << "strlen("; 8340 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 8341 OS << ") - 1"; 8342 8343 Diag(SL, diag::note_strncat_wrong_size) 8344 << FixItHint::CreateReplacement(SR, OS.str()); 8345 } 8346 8347 //===--- CHECK: Return Address of Stack Variable --------------------------===// 8348 8349 static const Expr *EvalVal(const Expr *E, 8350 SmallVectorImpl<const DeclRefExpr *> &refVars, 8351 const Decl *ParentDecl); 8352 static const Expr *EvalAddr(const Expr *E, 8353 SmallVectorImpl<const DeclRefExpr *> &refVars, 8354 const Decl *ParentDecl); 8355 8356 /// CheckReturnStackAddr - Check if a return statement returns the address 8357 /// of a stack variable. 8358 static void 8359 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, 8360 SourceLocation ReturnLoc) { 8361 const Expr *stackE = nullptr; 8362 SmallVector<const DeclRefExpr *, 8> refVars; 8363 8364 // Perform checking for returned stack addresses, local blocks, 8365 // label addresses or references to temporaries. 8366 if (lhsType->isPointerType() || 8367 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) { 8368 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr); 8369 } else if (lhsType->isReferenceType()) { 8370 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr); 8371 } 8372 8373 if (!stackE) 8374 return; // Nothing suspicious was found. 8375 8376 // Parameters are initialized in the calling scope, so taking the address 8377 // of a parameter reference doesn't need a warning. 8378 for (auto *DRE : refVars) 8379 if (isa<ParmVarDecl>(DRE->getDecl())) 8380 return; 8381 8382 SourceLocation diagLoc; 8383 SourceRange diagRange; 8384 if (refVars.empty()) { 8385 diagLoc = stackE->getLocStart(); 8386 diagRange = stackE->getSourceRange(); 8387 } else { 8388 // We followed through a reference variable. 'stackE' contains the 8389 // problematic expression but we will warn at the return statement pointing 8390 // at the reference variable. We will later display the "trail" of 8391 // reference variables using notes. 8392 diagLoc = refVars[0]->getLocStart(); 8393 diagRange = refVars[0]->getSourceRange(); 8394 } 8395 8396 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { 8397 // address of local var 8398 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType() 8399 << DR->getDecl()->getDeclName() << diagRange; 8400 } else if (isa<BlockExpr>(stackE)) { // local block. 8401 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange; 8402 } else if (isa<AddrLabelExpr>(stackE)) { // address of label. 8403 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange; 8404 } else { // local temporary. 8405 // If there is an LValue->RValue conversion, then the value of the 8406 // reference type is used, not the reference. 8407 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) { 8408 if (ICE->getCastKind() == CK_LValueToRValue) { 8409 return; 8410 } 8411 } 8412 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref) 8413 << lhsType->isReferenceType() << diagRange; 8414 } 8415 8416 // Display the "trail" of reference variables that we followed until we 8417 // found the problematic expression using notes. 8418 for (unsigned i = 0, e = refVars.size(); i != e; ++i) { 8419 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl()); 8420 // If this var binds to another reference var, show the range of the next 8421 // var, otherwise the var binds to the problematic expression, in which case 8422 // show the range of the expression. 8423 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange() 8424 : stackE->getSourceRange(); 8425 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind) 8426 << VD->getDeclName() << range; 8427 } 8428 } 8429 8430 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that 8431 /// check if the expression in a return statement evaluates to an address 8432 /// to a location on the stack, a local block, an address of a label, or a 8433 /// reference to local temporary. The recursion is used to traverse the 8434 /// AST of the return expression, with recursion backtracking when we 8435 /// encounter a subexpression that (1) clearly does not lead to one of the 8436 /// above problematic expressions (2) is something we cannot determine leads to 8437 /// a problematic expression based on such local checking. 8438 /// 8439 /// Both EvalAddr and EvalVal follow through reference variables to evaluate 8440 /// the expression that they point to. Such variables are added to the 8441 /// 'refVars' vector so that we know what the reference variable "trail" was. 8442 /// 8443 /// EvalAddr processes expressions that are pointers that are used as 8444 /// references (and not L-values). EvalVal handles all other values. 8445 /// At the base case of the recursion is a check for the above problematic 8446 /// expressions. 8447 /// 8448 /// This implementation handles: 8449 /// 8450 /// * pointer-to-pointer casts 8451 /// * implicit conversions from array references to pointers 8452 /// * taking the address of fields 8453 /// * arbitrary interplay between "&" and "*" operators 8454 /// * pointer arithmetic from an address of a stack variable 8455 /// * taking the address of an array element where the array is on the stack 8456 static const Expr *EvalAddr(const Expr *E, 8457 SmallVectorImpl<const DeclRefExpr *> &refVars, 8458 const Decl *ParentDecl) { 8459 if (E->isTypeDependent()) 8460 return nullptr; 8461 8462 // We should only be called for evaluating pointer expressions. 8463 assert((E->getType()->isAnyPointerType() || 8464 E->getType()->isBlockPointerType() || 8465 E->getType()->isObjCQualifiedIdType()) && 8466 "EvalAddr only works on pointers"); 8467 8468 E = E->IgnoreParens(); 8469 8470 // Our "symbolic interpreter" is just a dispatch off the currently 8471 // viewed AST node. We then recursively traverse the AST by calling 8472 // EvalAddr and EvalVal appropriately. 8473 switch (E->getStmtClass()) { 8474 case Stmt::DeclRefExprClass: { 8475 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8476 8477 // If we leave the immediate function, the lifetime isn't about to end. 8478 if (DR->refersToEnclosingVariableOrCapture()) 8479 return nullptr; 8480 8481 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) 8482 // If this is a reference variable, follow through to the expression that 8483 // it points to. 8484 if (V->hasLocalStorage() && 8485 V->getType()->isReferenceType() && V->hasInit()) { 8486 // Add the reference variable to the "trail". 8487 refVars.push_back(DR); 8488 return EvalAddr(V->getInit(), refVars, ParentDecl); 8489 } 8490 8491 return nullptr; 8492 } 8493 8494 case Stmt::UnaryOperatorClass: { 8495 // The only unary operator that make sense to handle here 8496 // is AddrOf. All others don't make sense as pointers. 8497 const UnaryOperator *U = cast<UnaryOperator>(E); 8498 8499 if (U->getOpcode() == UO_AddrOf) 8500 return EvalVal(U->getSubExpr(), refVars, ParentDecl); 8501 return nullptr; 8502 } 8503 8504 case Stmt::BinaryOperatorClass: { 8505 // Handle pointer arithmetic. All other binary operators are not valid 8506 // in this context. 8507 const BinaryOperator *B = cast<BinaryOperator>(E); 8508 BinaryOperatorKind op = B->getOpcode(); 8509 8510 if (op != BO_Add && op != BO_Sub) 8511 return nullptr; 8512 8513 const Expr *Base = B->getLHS(); 8514 8515 // Determine which argument is the real pointer base. It could be 8516 // the RHS argument instead of the LHS. 8517 if (!Base->getType()->isPointerType()) 8518 Base = B->getRHS(); 8519 8520 assert(Base->getType()->isPointerType()); 8521 return EvalAddr(Base, refVars, ParentDecl); 8522 } 8523 8524 // For conditional operators we need to see if either the LHS or RHS are 8525 // valid DeclRefExpr*s. If one of them is valid, we return it. 8526 case Stmt::ConditionalOperatorClass: { 8527 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8528 8529 // Handle the GNU extension for missing LHS. 8530 // FIXME: That isn't a ConditionalOperator, so doesn't get here. 8531 if (const Expr *LHSExpr = C->getLHS()) { 8532 // In C++, we can have a throw-expression, which has 'void' type. 8533 if (!LHSExpr->getType()->isVoidType()) 8534 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl)) 8535 return LHS; 8536 } 8537 8538 // In C++, we can have a throw-expression, which has 'void' type. 8539 if (C->getRHS()->getType()->isVoidType()) 8540 return nullptr; 8541 8542 return EvalAddr(C->getRHS(), refVars, ParentDecl); 8543 } 8544 8545 case Stmt::BlockExprClass: 8546 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures()) 8547 return E; // local block. 8548 return nullptr; 8549 8550 case Stmt::AddrLabelExprClass: 8551 return E; // address of label. 8552 8553 case Stmt::ExprWithCleanupsClass: 8554 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8555 ParentDecl); 8556 8557 // For casts, we need to handle conversions from arrays to 8558 // pointer values, and pointer-to-pointer conversions. 8559 case Stmt::ImplicitCastExprClass: 8560 case Stmt::CStyleCastExprClass: 8561 case Stmt::CXXFunctionalCastExprClass: 8562 case Stmt::ObjCBridgedCastExprClass: 8563 case Stmt::CXXStaticCastExprClass: 8564 case Stmt::CXXDynamicCastExprClass: 8565 case Stmt::CXXConstCastExprClass: 8566 case Stmt::CXXReinterpretCastExprClass: { 8567 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 8568 switch (cast<CastExpr>(E)->getCastKind()) { 8569 case CK_LValueToRValue: 8570 case CK_NoOp: 8571 case CK_BaseToDerived: 8572 case CK_DerivedToBase: 8573 case CK_UncheckedDerivedToBase: 8574 case CK_Dynamic: 8575 case CK_CPointerToObjCPointerCast: 8576 case CK_BlockPointerToObjCPointerCast: 8577 case CK_AnyPointerToBlockPointerCast: 8578 return EvalAddr(SubExpr, refVars, ParentDecl); 8579 8580 case CK_ArrayToPointerDecay: 8581 return EvalVal(SubExpr, refVars, ParentDecl); 8582 8583 case CK_BitCast: 8584 if (SubExpr->getType()->isAnyPointerType() || 8585 SubExpr->getType()->isBlockPointerType() || 8586 SubExpr->getType()->isObjCQualifiedIdType()) 8587 return EvalAddr(SubExpr, refVars, ParentDecl); 8588 else 8589 return nullptr; 8590 8591 default: 8592 return nullptr; 8593 } 8594 } 8595 8596 case Stmt::MaterializeTemporaryExprClass: 8597 if (const Expr *Result = 8598 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8599 refVars, ParentDecl)) 8600 return Result; 8601 return E; 8602 8603 // Everything else: we simply don't reason about them. 8604 default: 8605 return nullptr; 8606 } 8607 } 8608 8609 /// EvalVal - This function is complements EvalAddr in the mutual recursion. 8610 /// See the comments for EvalAddr for more details. 8611 static const Expr *EvalVal(const Expr *E, 8612 SmallVectorImpl<const DeclRefExpr *> &refVars, 8613 const Decl *ParentDecl) { 8614 do { 8615 // We should only be called for evaluating non-pointer expressions, or 8616 // expressions with a pointer type that are not used as references but 8617 // instead 8618 // are l-values (e.g., DeclRefExpr with a pointer type). 8619 8620 // Our "symbolic interpreter" is just a dispatch off the currently 8621 // viewed AST node. We then recursively traverse the AST by calling 8622 // EvalAddr and EvalVal appropriately. 8623 8624 E = E->IgnoreParens(); 8625 switch (E->getStmtClass()) { 8626 case Stmt::ImplicitCastExprClass: { 8627 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); 8628 if (IE->getValueKind() == VK_LValue) { 8629 E = IE->getSubExpr(); 8630 continue; 8631 } 8632 return nullptr; 8633 } 8634 8635 case Stmt::ExprWithCleanupsClass: 8636 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars, 8637 ParentDecl); 8638 8639 case Stmt::DeclRefExprClass: { 8640 // When we hit a DeclRefExpr we are looking at code that refers to a 8641 // variable's name. If it's not a reference variable we check if it has 8642 // local storage within the function, and if so, return the expression. 8643 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8644 8645 // If we leave the immediate function, the lifetime isn't about to end. 8646 if (DR->refersToEnclosingVariableOrCapture()) 8647 return nullptr; 8648 8649 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) { 8650 // Check if it refers to itself, e.g. "int& i = i;". 8651 if (V == ParentDecl) 8652 return DR; 8653 8654 if (V->hasLocalStorage()) { 8655 if (!V->getType()->isReferenceType()) 8656 return DR; 8657 8658 // Reference variable, follow through to the expression that 8659 // it points to. 8660 if (V->hasInit()) { 8661 // Add the reference variable to the "trail". 8662 refVars.push_back(DR); 8663 return EvalVal(V->getInit(), refVars, V); 8664 } 8665 } 8666 } 8667 8668 return nullptr; 8669 } 8670 8671 case Stmt::UnaryOperatorClass: { 8672 // The only unary operator that make sense to handle here 8673 // is Deref. All others don't resolve to a "name." This includes 8674 // handling all sorts of rvalues passed to a unary operator. 8675 const UnaryOperator *U = cast<UnaryOperator>(E); 8676 8677 if (U->getOpcode() == UO_Deref) 8678 return EvalAddr(U->getSubExpr(), refVars, ParentDecl); 8679 8680 return nullptr; 8681 } 8682 8683 case Stmt::ArraySubscriptExprClass: { 8684 // Array subscripts are potential references to data on the stack. We 8685 // retrieve the DeclRefExpr* for the array variable if it indeed 8686 // has local storage. 8687 const auto *ASE = cast<ArraySubscriptExpr>(E); 8688 if (ASE->isTypeDependent()) 8689 return nullptr; 8690 return EvalAddr(ASE->getBase(), refVars, ParentDecl); 8691 } 8692 8693 case Stmt::OMPArraySectionExprClass: { 8694 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars, 8695 ParentDecl); 8696 } 8697 8698 case Stmt::ConditionalOperatorClass: { 8699 // For conditional operators we need to see if either the LHS or RHS are 8700 // non-NULL Expr's. If one is non-NULL, we return it. 8701 const ConditionalOperator *C = cast<ConditionalOperator>(E); 8702 8703 // Handle the GNU extension for missing LHS. 8704 if (const Expr *LHSExpr = C->getLHS()) { 8705 // In C++, we can have a throw-expression, which has 'void' type. 8706 if (!LHSExpr->getType()->isVoidType()) 8707 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl)) 8708 return LHS; 8709 } 8710 8711 // In C++, we can have a throw-expression, which has 'void' type. 8712 if (C->getRHS()->getType()->isVoidType()) 8713 return nullptr; 8714 8715 return EvalVal(C->getRHS(), refVars, ParentDecl); 8716 } 8717 8718 // Accesses to members are potential references to data on the stack. 8719 case Stmt::MemberExprClass: { 8720 const MemberExpr *M = cast<MemberExpr>(E); 8721 8722 // Check for indirect access. We only want direct field accesses. 8723 if (M->isArrow()) 8724 return nullptr; 8725 8726 // Check whether the member type is itself a reference, in which case 8727 // we're not going to refer to the member, but to what the member refers 8728 // to. 8729 if (M->getMemberDecl()->getType()->isReferenceType()) 8730 return nullptr; 8731 8732 return EvalVal(M->getBase(), refVars, ParentDecl); 8733 } 8734 8735 case Stmt::MaterializeTemporaryExprClass: 8736 if (const Expr *Result = 8737 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(), 8738 refVars, ParentDecl)) 8739 return Result; 8740 return E; 8741 8742 default: 8743 // Check that we don't return or take the address of a reference to a 8744 // temporary. This is only useful in C++. 8745 if (!E->isTypeDependent() && E->isRValue()) 8746 return E; 8747 8748 // Everything else: we simply don't reason about them. 8749 return nullptr; 8750 } 8751 } while (true); 8752 } 8753 8754 void 8755 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8756 SourceLocation ReturnLoc, 8757 bool isObjCMethod, 8758 const AttrVec *Attrs, 8759 const FunctionDecl *FD) { 8760 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc); 8761 8762 // Check if the return value is null but should not be. 8763 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 8764 (!isObjCMethod && isNonNullType(Context, lhsType))) && 8765 CheckNonNullExpr(*this, RetValExp)) 8766 Diag(ReturnLoc, diag::warn_null_ret) 8767 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 8768 8769 // C++11 [basic.stc.dynamic.allocation]p4: 8770 // If an allocation function declared with a non-throwing 8771 // exception-specification fails to allocate storage, it shall return 8772 // a null pointer. Any other allocation function that fails to allocate 8773 // storage shall indicate failure only by throwing an exception [...] 8774 if (FD) { 8775 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 8776 if (Op == OO_New || Op == OO_Array_New) { 8777 const FunctionProtoType *Proto 8778 = FD->getType()->castAs<FunctionProtoType>(); 8779 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 8780 CheckNonNullExpr(*this, RetValExp)) 8781 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 8782 << FD << getLangOpts().CPlusPlus11; 8783 } 8784 } 8785 } 8786 8787 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 8788 8789 /// Check for comparisons of floating point operands using != and ==. 8790 /// Issue a warning if these are no self-comparisons, as they are not likely 8791 /// to do what the programmer intended. 8792 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 8793 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 8794 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 8795 8796 // Special case: check for x == x (which is OK). 8797 // Do not emit warnings for such cases. 8798 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 8799 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 8800 if (DRL->getDecl() == DRR->getDecl()) 8801 return; 8802 8803 // Special case: check for comparisons against literals that can be exactly 8804 // represented by APFloat. In such cases, do not emit a warning. This 8805 // is a heuristic: often comparison against such literals are used to 8806 // detect if a value in a variable has not changed. This clearly can 8807 // lead to false negatives. 8808 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 8809 if (FLL->isExact()) 8810 return; 8811 } else 8812 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 8813 if (FLR->isExact()) 8814 return; 8815 8816 // Check for comparisons with builtin types. 8817 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 8818 if (CL->getBuiltinCallee()) 8819 return; 8820 8821 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 8822 if (CR->getBuiltinCallee()) 8823 return; 8824 8825 // Emit the diagnostic. 8826 Diag(Loc, diag::warn_floatingpoint_eq) 8827 << LHS->getSourceRange() << RHS->getSourceRange(); 8828 } 8829 8830 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 8831 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 8832 8833 namespace { 8834 8835 /// Structure recording the 'active' range of an integer-valued 8836 /// expression. 8837 struct IntRange { 8838 /// The number of bits active in the int. 8839 unsigned Width; 8840 8841 /// True if the int is known not to have negative values. 8842 bool NonNegative; 8843 8844 IntRange(unsigned Width, bool NonNegative) 8845 : Width(Width), NonNegative(NonNegative) {} 8846 8847 /// Returns the range of the bool type. 8848 static IntRange forBoolType() { 8849 return IntRange(1, true); 8850 } 8851 8852 /// Returns the range of an opaque value of the given integral type. 8853 static IntRange forValueOfType(ASTContext &C, QualType T) { 8854 return forValueOfCanonicalType(C, 8855 T->getCanonicalTypeInternal().getTypePtr()); 8856 } 8857 8858 /// Returns the range of an opaque value of a canonical integral type. 8859 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 8860 assert(T->isCanonicalUnqualified()); 8861 8862 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8863 T = VT->getElementType().getTypePtr(); 8864 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8865 T = CT->getElementType().getTypePtr(); 8866 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8867 T = AT->getValueType().getTypePtr(); 8868 8869 if (!C.getLangOpts().CPlusPlus) { 8870 // For enum types in C code, use the underlying datatype. 8871 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8872 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 8873 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 8874 // For enum types in C++, use the known bit width of the enumerators. 8875 EnumDecl *Enum = ET->getDecl(); 8876 // In C++11, enums can have a fixed underlying type. Use this type to 8877 // compute the range. 8878 if (Enum->isFixed()) { 8879 return IntRange(C.getIntWidth(QualType(T, 0)), 8880 !ET->isSignedIntegerOrEnumerationType()); 8881 } 8882 8883 unsigned NumPositive = Enum->getNumPositiveBits(); 8884 unsigned NumNegative = Enum->getNumNegativeBits(); 8885 8886 if (NumNegative == 0) 8887 return IntRange(NumPositive, true/*NonNegative*/); 8888 else 8889 return IntRange(std::max(NumPositive + 1, NumNegative), 8890 false/*NonNegative*/); 8891 } 8892 8893 const BuiltinType *BT = cast<BuiltinType>(T); 8894 assert(BT->isInteger()); 8895 8896 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8897 } 8898 8899 /// Returns the "target" range of a canonical integral type, i.e. 8900 /// the range of values expressible in the type. 8901 /// 8902 /// This matches forValueOfCanonicalType except that enums have the 8903 /// full range of their type, not the range of their enumerators. 8904 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 8905 assert(T->isCanonicalUnqualified()); 8906 8907 if (const VectorType *VT = dyn_cast<VectorType>(T)) 8908 T = VT->getElementType().getTypePtr(); 8909 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 8910 T = CT->getElementType().getTypePtr(); 8911 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 8912 T = AT->getValueType().getTypePtr(); 8913 if (const EnumType *ET = dyn_cast<EnumType>(T)) 8914 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 8915 8916 const BuiltinType *BT = cast<BuiltinType>(T); 8917 assert(BT->isInteger()); 8918 8919 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 8920 } 8921 8922 /// Returns the supremum of two ranges: i.e. their conservative merge. 8923 static IntRange join(IntRange L, IntRange R) { 8924 return IntRange(std::max(L.Width, R.Width), 8925 L.NonNegative && R.NonNegative); 8926 } 8927 8928 /// Returns the infinum of two ranges: i.e. their aggressive merge. 8929 static IntRange meet(IntRange L, IntRange R) { 8930 return IntRange(std::min(L.Width, R.Width), 8931 L.NonNegative || R.NonNegative); 8932 } 8933 }; 8934 8935 } // namespace 8936 8937 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 8938 unsigned MaxWidth) { 8939 if (value.isSigned() && value.isNegative()) 8940 return IntRange(value.getMinSignedBits(), false); 8941 8942 if (value.getBitWidth() > MaxWidth) 8943 value = value.trunc(MaxWidth); 8944 8945 // isNonNegative() just checks the sign bit without considering 8946 // signedness. 8947 return IntRange(value.getActiveBits(), true); 8948 } 8949 8950 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 8951 unsigned MaxWidth) { 8952 if (result.isInt()) 8953 return GetValueRange(C, result.getInt(), MaxWidth); 8954 8955 if (result.isVector()) { 8956 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 8957 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 8958 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 8959 R = IntRange::join(R, El); 8960 } 8961 return R; 8962 } 8963 8964 if (result.isComplexInt()) { 8965 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 8966 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 8967 return IntRange::join(R, I); 8968 } 8969 8970 // This can happen with lossless casts to intptr_t of "based" lvalues. 8971 // Assume it might use arbitrary bits. 8972 // FIXME: The only reason we need to pass the type in here is to get 8973 // the sign right on this one case. It would be nice if APValue 8974 // preserved this. 8975 assert(result.isLValue() || result.isAddrLabelDiff()); 8976 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 8977 } 8978 8979 static QualType GetExprType(const Expr *E) { 8980 QualType Ty = E->getType(); 8981 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 8982 Ty = AtomicRHS->getValueType(); 8983 return Ty; 8984 } 8985 8986 /// Pseudo-evaluate the given integer expression, estimating the 8987 /// range of values it might take. 8988 /// 8989 /// \param MaxWidth - the width to which the value will be truncated 8990 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 8991 E = E->IgnoreParens(); 8992 8993 // Try a full evaluation first. 8994 Expr::EvalResult result; 8995 if (E->EvaluateAsRValue(result, C)) 8996 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 8997 8998 // I think we only want to look through implicit casts here; if the 8999 // user has an explicit widening cast, we should treat the value as 9000 // being of the new, wider type. 9001 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9002 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9003 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9004 9005 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9006 9007 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9008 CE->getCastKind() == CK_BooleanToSignedIntegral; 9009 9010 // Assume that non-integer casts can span the full range of the type. 9011 if (!isIntegerCast) 9012 return OutputTypeRange; 9013 9014 IntRange SubRange 9015 = GetExprRange(C, CE->getSubExpr(), 9016 std::min(MaxWidth, OutputTypeRange.Width)); 9017 9018 // Bail out if the subexpr's range is as wide as the cast type. 9019 if (SubRange.Width >= OutputTypeRange.Width) 9020 return OutputTypeRange; 9021 9022 // Otherwise, we take the smaller width, and we're non-negative if 9023 // either the output type or the subexpr is. 9024 return IntRange(SubRange.Width, 9025 SubRange.NonNegative || OutputTypeRange.NonNegative); 9026 } 9027 9028 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9029 // If we can fold the condition, just take that operand. 9030 bool CondResult; 9031 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9032 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9033 : CO->getFalseExpr(), 9034 MaxWidth); 9035 9036 // Otherwise, conservatively merge. 9037 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9038 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9039 return IntRange::join(L, R); 9040 } 9041 9042 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9043 switch (BO->getOpcode()) { 9044 case BO_Cmp: 9045 llvm_unreachable("builtin <=> should have class type"); 9046 9047 // Boolean-valued operations are single-bit and positive. 9048 case BO_LAnd: 9049 case BO_LOr: 9050 case BO_LT: 9051 case BO_GT: 9052 case BO_LE: 9053 case BO_GE: 9054 case BO_EQ: 9055 case BO_NE: 9056 return IntRange::forBoolType(); 9057 9058 // The type of the assignments is the type of the LHS, so the RHS 9059 // is not necessarily the same type. 9060 case BO_MulAssign: 9061 case BO_DivAssign: 9062 case BO_RemAssign: 9063 case BO_AddAssign: 9064 case BO_SubAssign: 9065 case BO_XorAssign: 9066 case BO_OrAssign: 9067 // TODO: bitfields? 9068 return IntRange::forValueOfType(C, GetExprType(E)); 9069 9070 // Simple assignments just pass through the RHS, which will have 9071 // been coerced to the LHS type. 9072 case BO_Assign: 9073 // TODO: bitfields? 9074 return GetExprRange(C, BO->getRHS(), MaxWidth); 9075 9076 // Operations with opaque sources are black-listed. 9077 case BO_PtrMemD: 9078 case BO_PtrMemI: 9079 return IntRange::forValueOfType(C, GetExprType(E)); 9080 9081 // Bitwise-and uses the *infinum* of the two source ranges. 9082 case BO_And: 9083 case BO_AndAssign: 9084 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9085 GetExprRange(C, BO->getRHS(), MaxWidth)); 9086 9087 // Left shift gets black-listed based on a judgement call. 9088 case BO_Shl: 9089 // ...except that we want to treat '1 << (blah)' as logically 9090 // positive. It's an important idiom. 9091 if (IntegerLiteral *I 9092 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9093 if (I->getValue() == 1) { 9094 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9095 return IntRange(R.Width, /*NonNegative*/ true); 9096 } 9097 } 9098 LLVM_FALLTHROUGH; 9099 9100 case BO_ShlAssign: 9101 return IntRange::forValueOfType(C, GetExprType(E)); 9102 9103 // Right shift by a constant can narrow its left argument. 9104 case BO_Shr: 9105 case BO_ShrAssign: { 9106 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9107 9108 // If the shift amount is a positive constant, drop the width by 9109 // that much. 9110 llvm::APSInt shift; 9111 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9112 shift.isNonNegative()) { 9113 unsigned zext = shift.getZExtValue(); 9114 if (zext >= L.Width) 9115 L.Width = (L.NonNegative ? 0 : 1); 9116 else 9117 L.Width -= zext; 9118 } 9119 9120 return L; 9121 } 9122 9123 // Comma acts as its right operand. 9124 case BO_Comma: 9125 return GetExprRange(C, BO->getRHS(), MaxWidth); 9126 9127 // Black-list pointer subtractions. 9128 case BO_Sub: 9129 if (BO->getLHS()->getType()->isPointerType()) 9130 return IntRange::forValueOfType(C, GetExprType(E)); 9131 break; 9132 9133 // The width of a division result is mostly determined by the size 9134 // of the LHS. 9135 case BO_Div: { 9136 // Don't 'pre-truncate' the operands. 9137 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9138 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9139 9140 // If the divisor is constant, use that. 9141 llvm::APSInt divisor; 9142 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9143 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9144 if (log2 >= L.Width) 9145 L.Width = (L.NonNegative ? 0 : 1); 9146 else 9147 L.Width = std::min(L.Width - log2, MaxWidth); 9148 return L; 9149 } 9150 9151 // Otherwise, just use the LHS's width. 9152 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9153 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9154 } 9155 9156 // The result of a remainder can't be larger than the result of 9157 // either side. 9158 case BO_Rem: { 9159 // Don't 'pre-truncate' the operands. 9160 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9161 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9162 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9163 9164 IntRange meet = IntRange::meet(L, R); 9165 meet.Width = std::min(meet.Width, MaxWidth); 9166 return meet; 9167 } 9168 9169 // The default behavior is okay for these. 9170 case BO_Mul: 9171 case BO_Add: 9172 case BO_Xor: 9173 case BO_Or: 9174 break; 9175 } 9176 9177 // The default case is to treat the operation as if it were closed 9178 // on the narrowest type that encompasses both operands. 9179 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9180 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9181 return IntRange::join(L, R); 9182 } 9183 9184 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9185 switch (UO->getOpcode()) { 9186 // Boolean-valued operations are white-listed. 9187 case UO_LNot: 9188 return IntRange::forBoolType(); 9189 9190 // Operations with opaque sources are black-listed. 9191 case UO_Deref: 9192 case UO_AddrOf: // should be impossible 9193 return IntRange::forValueOfType(C, GetExprType(E)); 9194 9195 default: 9196 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9197 } 9198 } 9199 9200 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9201 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9202 9203 if (const auto *BitField = E->getSourceBitField()) 9204 return IntRange(BitField->getBitWidthValue(C), 9205 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9206 9207 return IntRange::forValueOfType(C, GetExprType(E)); 9208 } 9209 9210 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9211 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9212 } 9213 9214 /// Checks whether the given value, which currently has the given 9215 /// source semantics, has the same value when coerced through the 9216 /// target semantics. 9217 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9218 const llvm::fltSemantics &Src, 9219 const llvm::fltSemantics &Tgt) { 9220 llvm::APFloat truncated = value; 9221 9222 bool ignored; 9223 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9224 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9225 9226 return truncated.bitwiseIsEqual(value); 9227 } 9228 9229 /// Checks whether the given value, which currently has the given 9230 /// source semantics, has the same value when coerced through the 9231 /// target semantics. 9232 /// 9233 /// The value might be a vector of floats (or a complex number). 9234 static bool IsSameFloatAfterCast(const APValue &value, 9235 const llvm::fltSemantics &Src, 9236 const llvm::fltSemantics &Tgt) { 9237 if (value.isFloat()) 9238 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9239 9240 if (value.isVector()) { 9241 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9242 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9243 return false; 9244 return true; 9245 } 9246 9247 assert(value.isComplexFloat()); 9248 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9249 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9250 } 9251 9252 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9253 9254 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9255 // Suppress cases where we are comparing against an enum constant. 9256 if (const DeclRefExpr *DR = 9257 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9258 if (isa<EnumConstantDecl>(DR->getDecl())) 9259 return true; 9260 9261 // Suppress cases where the '0' value is expanded from a macro. 9262 if (E->getLocStart().isMacroID()) 9263 return true; 9264 9265 return false; 9266 } 9267 9268 static bool isKnownToHaveUnsignedValue(Expr *E) { 9269 return E->getType()->isIntegerType() && 9270 (!E->getType()->isSignedIntegerType() || 9271 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9272 } 9273 9274 namespace { 9275 /// The promoted range of values of a type. In general this has the 9276 /// following structure: 9277 /// 9278 /// |-----------| . . . |-----------| 9279 /// ^ ^ ^ ^ 9280 /// Min HoleMin HoleMax Max 9281 /// 9282 /// ... where there is only a hole if a signed type is promoted to unsigned 9283 /// (in which case Min and Max are the smallest and largest representable 9284 /// values). 9285 struct PromotedRange { 9286 // Min, or HoleMax if there is a hole. 9287 llvm::APSInt PromotedMin; 9288 // Max, or HoleMin if there is a hole. 9289 llvm::APSInt PromotedMax; 9290 9291 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9292 if (R.Width == 0) 9293 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9294 else if (R.Width >= BitWidth && !Unsigned) { 9295 // Promotion made the type *narrower*. This happens when promoting 9296 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9297 // Treat all values of 'signed int' as being in range for now. 9298 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9299 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9300 } else { 9301 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9302 .extOrTrunc(BitWidth); 9303 PromotedMin.setIsUnsigned(Unsigned); 9304 9305 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9306 .extOrTrunc(BitWidth); 9307 PromotedMax.setIsUnsigned(Unsigned); 9308 } 9309 } 9310 9311 // Determine whether this range is contiguous (has no hole). 9312 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9313 9314 // Where a constant value is within the range. 9315 enum ComparisonResult { 9316 LT = 0x1, 9317 LE = 0x2, 9318 GT = 0x4, 9319 GE = 0x8, 9320 EQ = 0x10, 9321 NE = 0x20, 9322 InRangeFlag = 0x40, 9323 9324 Less = LE | LT | NE, 9325 Min = LE | InRangeFlag, 9326 InRange = InRangeFlag, 9327 Max = GE | InRangeFlag, 9328 Greater = GE | GT | NE, 9329 9330 OnlyValue = LE | GE | EQ | InRangeFlag, 9331 InHole = NE 9332 }; 9333 9334 ComparisonResult compare(const llvm::APSInt &Value) const { 9335 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9336 Value.isUnsigned() == PromotedMin.isUnsigned()); 9337 if (!isContiguous()) { 9338 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9339 if (Value.isMinValue()) return Min; 9340 if (Value.isMaxValue()) return Max; 9341 if (Value >= PromotedMin) return InRange; 9342 if (Value <= PromotedMax) return InRange; 9343 return InHole; 9344 } 9345 9346 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9347 case -1: return Less; 9348 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9349 case 1: 9350 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9351 case -1: return InRange; 9352 case 0: return Max; 9353 case 1: return Greater; 9354 } 9355 } 9356 9357 llvm_unreachable("impossible compare result"); 9358 } 9359 9360 static llvm::Optional<StringRef> 9361 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9362 if (Op == BO_Cmp) { 9363 ComparisonResult LTFlag = LT, GTFlag = GT; 9364 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9365 9366 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9367 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9368 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9369 return llvm::None; 9370 } 9371 9372 ComparisonResult TrueFlag, FalseFlag; 9373 if (Op == BO_EQ) { 9374 TrueFlag = EQ; 9375 FalseFlag = NE; 9376 } else if (Op == BO_NE) { 9377 TrueFlag = NE; 9378 FalseFlag = EQ; 9379 } else { 9380 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9381 TrueFlag = LT; 9382 FalseFlag = GE; 9383 } else { 9384 TrueFlag = GT; 9385 FalseFlag = LE; 9386 } 9387 if (Op == BO_GE || Op == BO_LE) 9388 std::swap(TrueFlag, FalseFlag); 9389 } 9390 if (R & TrueFlag) 9391 return StringRef("true"); 9392 if (R & FalseFlag) 9393 return StringRef("false"); 9394 return llvm::None; 9395 } 9396 }; 9397 } 9398 9399 static bool HasEnumType(Expr *E) { 9400 // Strip off implicit integral promotions. 9401 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9402 if (ICE->getCastKind() != CK_IntegralCast && 9403 ICE->getCastKind() != CK_NoOp) 9404 break; 9405 E = ICE->getSubExpr(); 9406 } 9407 9408 return E->getType()->isEnumeralType(); 9409 } 9410 9411 static int classifyConstantValue(Expr *Constant) { 9412 // The values of this enumeration are used in the diagnostics 9413 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9414 enum ConstantValueKind { 9415 Miscellaneous = 0, 9416 LiteralTrue, 9417 LiteralFalse 9418 }; 9419 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9420 return BL->getValue() ? ConstantValueKind::LiteralTrue 9421 : ConstantValueKind::LiteralFalse; 9422 return ConstantValueKind::Miscellaneous; 9423 } 9424 9425 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9426 Expr *Constant, Expr *Other, 9427 const llvm::APSInt &Value, 9428 bool RhsConstant) { 9429 if (S.inTemplateInstantiation()) 9430 return false; 9431 9432 Expr *OriginalOther = Other; 9433 9434 Constant = Constant->IgnoreParenImpCasts(); 9435 Other = Other->IgnoreParenImpCasts(); 9436 9437 // Suppress warnings on tautological comparisons between values of the same 9438 // enumeration type. There are only two ways we could warn on this: 9439 // - If the constant is outside the range of representable values of 9440 // the enumeration. In such a case, we should warn about the cast 9441 // to enumeration type, not about the comparison. 9442 // - If the constant is the maximum / minimum in-range value. For an 9443 // enumeratin type, such comparisons can be meaningful and useful. 9444 if (Constant->getType()->isEnumeralType() && 9445 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9446 return false; 9447 9448 // TODO: Investigate using GetExprRange() to get tighter bounds 9449 // on the bit ranges. 9450 QualType OtherT = Other->getType(); 9451 if (const auto *AT = OtherT->getAs<AtomicType>()) 9452 OtherT = AT->getValueType(); 9453 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9454 9455 // Whether we're treating Other as being a bool because of the form of 9456 // expression despite it having another type (typically 'int' in C). 9457 bool OtherIsBooleanDespiteType = 9458 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9459 if (OtherIsBooleanDespiteType) 9460 OtherRange = IntRange::forBoolType(); 9461 9462 // Determine the promoted range of the other type and see if a comparison of 9463 // the constant against that range is tautological. 9464 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9465 Value.isUnsigned()); 9466 auto Cmp = OtherPromotedRange.compare(Value); 9467 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9468 if (!Result) 9469 return false; 9470 9471 // Suppress the diagnostic for an in-range comparison if the constant comes 9472 // from a macro or enumerator. We don't want to diagnose 9473 // 9474 // some_long_value <= INT_MAX 9475 // 9476 // when sizeof(int) == sizeof(long). 9477 bool InRange = Cmp & PromotedRange::InRangeFlag; 9478 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 9479 return false; 9480 9481 // If this is a comparison to an enum constant, include that 9482 // constant in the diagnostic. 9483 const EnumConstantDecl *ED = nullptr; 9484 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 9485 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 9486 9487 // Should be enough for uint128 (39 decimal digits) 9488 SmallString<64> PrettySourceValue; 9489 llvm::raw_svector_ostream OS(PrettySourceValue); 9490 if (ED) 9491 OS << '\'' << *ED << "' (" << Value << ")"; 9492 else 9493 OS << Value; 9494 9495 // FIXME: We use a somewhat different formatting for the in-range cases and 9496 // cases involving boolean values for historical reasons. We should pick a 9497 // consistent way of presenting these diagnostics. 9498 if (!InRange || Other->isKnownToHaveBooleanValue()) { 9499 S.DiagRuntimeBehavior( 9500 E->getOperatorLoc(), E, 9501 S.PDiag(!InRange ? diag::warn_out_of_range_compare 9502 : diag::warn_tautological_bool_compare) 9503 << OS.str() << classifyConstantValue(Constant) 9504 << OtherT << OtherIsBooleanDespiteType << *Result 9505 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 9506 } else { 9507 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 9508 ? (HasEnumType(OriginalOther) 9509 ? diag::warn_unsigned_enum_always_true_comparison 9510 : diag::warn_unsigned_always_true_comparison) 9511 : diag::warn_tautological_constant_compare; 9512 9513 S.Diag(E->getOperatorLoc(), Diag) 9514 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 9515 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 9516 } 9517 9518 return true; 9519 } 9520 9521 /// Analyze the operands of the given comparison. Implements the 9522 /// fallback case from AnalyzeComparison. 9523 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 9524 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9525 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9526 } 9527 9528 /// Implements -Wsign-compare. 9529 /// 9530 /// \param E the binary operator to check for warnings 9531 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 9532 // The type the comparison is being performed in. 9533 QualType T = E->getLHS()->getType(); 9534 9535 // Only analyze comparison operators where both sides have been converted to 9536 // the same type. 9537 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 9538 return AnalyzeImpConvsInComparison(S, E); 9539 9540 // Don't analyze value-dependent comparisons directly. 9541 if (E->isValueDependent()) 9542 return AnalyzeImpConvsInComparison(S, E); 9543 9544 Expr *LHS = E->getLHS(); 9545 Expr *RHS = E->getRHS(); 9546 9547 if (T->isIntegralType(S.Context)) { 9548 llvm::APSInt RHSValue; 9549 llvm::APSInt LHSValue; 9550 9551 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 9552 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 9553 9554 // We don't care about expressions whose result is a constant. 9555 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 9556 return AnalyzeImpConvsInComparison(S, E); 9557 9558 // We only care about expressions where just one side is literal 9559 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 9560 // Is the constant on the RHS or LHS? 9561 const bool RhsConstant = IsRHSIntegralLiteral; 9562 Expr *Const = RhsConstant ? RHS : LHS; 9563 Expr *Other = RhsConstant ? LHS : RHS; 9564 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 9565 9566 // Check whether an integer constant comparison results in a value 9567 // of 'true' or 'false'. 9568 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 9569 return AnalyzeImpConvsInComparison(S, E); 9570 } 9571 } 9572 9573 if (!T->hasUnsignedIntegerRepresentation()) { 9574 // We don't do anything special if this isn't an unsigned integral 9575 // comparison: we're only interested in integral comparisons, and 9576 // signed comparisons only happen in cases we don't care to warn about. 9577 return AnalyzeImpConvsInComparison(S, E); 9578 } 9579 9580 LHS = LHS->IgnoreParenImpCasts(); 9581 RHS = RHS->IgnoreParenImpCasts(); 9582 9583 if (!S.getLangOpts().CPlusPlus) { 9584 // Avoid warning about comparison of integers with different signs when 9585 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 9586 // the type of `E`. 9587 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 9588 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9589 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 9590 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 9591 } 9592 9593 // Check to see if one of the (unmodified) operands is of different 9594 // signedness. 9595 Expr *signedOperand, *unsignedOperand; 9596 if (LHS->getType()->hasSignedIntegerRepresentation()) { 9597 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 9598 "unsigned comparison between two signed integer expressions?"); 9599 signedOperand = LHS; 9600 unsignedOperand = RHS; 9601 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 9602 signedOperand = RHS; 9603 unsignedOperand = LHS; 9604 } else { 9605 return AnalyzeImpConvsInComparison(S, E); 9606 } 9607 9608 // Otherwise, calculate the effective range of the signed operand. 9609 IntRange signedRange = GetExprRange(S.Context, signedOperand); 9610 9611 // Go ahead and analyze implicit conversions in the operands. Note 9612 // that we skip the implicit conversions on both sides. 9613 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 9614 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 9615 9616 // If the signed range is non-negative, -Wsign-compare won't fire. 9617 if (signedRange.NonNegative) 9618 return; 9619 9620 // For (in)equality comparisons, if the unsigned operand is a 9621 // constant which cannot collide with a overflowed signed operand, 9622 // then reinterpreting the signed operand as unsigned will not 9623 // change the result of the comparison. 9624 if (E->isEqualityOp()) { 9625 unsigned comparisonWidth = S.Context.getIntWidth(T); 9626 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 9627 9628 // We should never be unable to prove that the unsigned operand is 9629 // non-negative. 9630 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 9631 9632 if (unsignedRange.Width < comparisonWidth) 9633 return; 9634 } 9635 9636 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 9637 S.PDiag(diag::warn_mixed_sign_comparison) 9638 << LHS->getType() << RHS->getType() 9639 << LHS->getSourceRange() << RHS->getSourceRange()); 9640 } 9641 9642 /// Analyzes an attempt to assign the given value to a bitfield. 9643 /// 9644 /// Returns true if there was something fishy about the attempt. 9645 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 9646 SourceLocation InitLoc) { 9647 assert(Bitfield->isBitField()); 9648 if (Bitfield->isInvalidDecl()) 9649 return false; 9650 9651 // White-list bool bitfields. 9652 QualType BitfieldType = Bitfield->getType(); 9653 if (BitfieldType->isBooleanType()) 9654 return false; 9655 9656 if (BitfieldType->isEnumeralType()) { 9657 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 9658 // If the underlying enum type was not explicitly specified as an unsigned 9659 // type and the enum contain only positive values, MSVC++ will cause an 9660 // inconsistency by storing this as a signed type. 9661 if (S.getLangOpts().CPlusPlus11 && 9662 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 9663 BitfieldEnumDecl->getNumPositiveBits() > 0 && 9664 BitfieldEnumDecl->getNumNegativeBits() == 0) { 9665 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 9666 << BitfieldEnumDecl->getNameAsString(); 9667 } 9668 } 9669 9670 if (Bitfield->getType()->isBooleanType()) 9671 return false; 9672 9673 // Ignore value- or type-dependent expressions. 9674 if (Bitfield->getBitWidth()->isValueDependent() || 9675 Bitfield->getBitWidth()->isTypeDependent() || 9676 Init->isValueDependent() || 9677 Init->isTypeDependent()) 9678 return false; 9679 9680 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 9681 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 9682 9683 llvm::APSInt Value; 9684 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 9685 Expr::SE_AllowSideEffects)) { 9686 // The RHS is not constant. If the RHS has an enum type, make sure the 9687 // bitfield is wide enough to hold all the values of the enum without 9688 // truncation. 9689 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 9690 EnumDecl *ED = EnumTy->getDecl(); 9691 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 9692 9693 // Enum types are implicitly signed on Windows, so check if there are any 9694 // negative enumerators to see if the enum was intended to be signed or 9695 // not. 9696 bool SignedEnum = ED->getNumNegativeBits() > 0; 9697 9698 // Check for surprising sign changes when assigning enum values to a 9699 // bitfield of different signedness. If the bitfield is signed and we 9700 // have exactly the right number of bits to store this unsigned enum, 9701 // suggest changing the enum to an unsigned type. This typically happens 9702 // on Windows where unfixed enums always use an underlying type of 'int'. 9703 unsigned DiagID = 0; 9704 if (SignedEnum && !SignedBitfield) { 9705 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 9706 } else if (SignedBitfield && !SignedEnum && 9707 ED->getNumPositiveBits() == FieldWidth) { 9708 DiagID = diag::warn_signed_bitfield_enum_conversion; 9709 } 9710 9711 if (DiagID) { 9712 S.Diag(InitLoc, DiagID) << Bitfield << ED; 9713 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 9714 SourceRange TypeRange = 9715 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 9716 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 9717 << SignedEnum << TypeRange; 9718 } 9719 9720 // Compute the required bitwidth. If the enum has negative values, we need 9721 // one more bit than the normal number of positive bits to represent the 9722 // sign bit. 9723 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 9724 ED->getNumNegativeBits()) 9725 : ED->getNumPositiveBits(); 9726 9727 // Check the bitwidth. 9728 if (BitsNeeded > FieldWidth) { 9729 Expr *WidthExpr = Bitfield->getBitWidth(); 9730 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 9731 << Bitfield << ED; 9732 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 9733 << BitsNeeded << ED << WidthExpr->getSourceRange(); 9734 } 9735 } 9736 9737 return false; 9738 } 9739 9740 unsigned OriginalWidth = Value.getBitWidth(); 9741 9742 if (!Value.isSigned() || Value.isNegative()) 9743 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 9744 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 9745 OriginalWidth = Value.getMinSignedBits(); 9746 9747 if (OriginalWidth <= FieldWidth) 9748 return false; 9749 9750 // Compute the value which the bitfield will contain. 9751 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 9752 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 9753 9754 // Check whether the stored value is equal to the original value. 9755 TruncatedValue = TruncatedValue.extend(OriginalWidth); 9756 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 9757 return false; 9758 9759 // Special-case bitfields of width 1: booleans are naturally 0/1, and 9760 // therefore don't strictly fit into a signed bitfield of width 1. 9761 if (FieldWidth == 1 && Value == 1) 9762 return false; 9763 9764 std::string PrettyValue = Value.toString(10); 9765 std::string PrettyTrunc = TruncatedValue.toString(10); 9766 9767 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 9768 << PrettyValue << PrettyTrunc << OriginalInit->getType() 9769 << Init->getSourceRange(); 9770 9771 return true; 9772 } 9773 9774 /// Analyze the given simple or compound assignment for warning-worthy 9775 /// operations. 9776 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 9777 // Just recurse on the LHS. 9778 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9779 9780 // We want to recurse on the RHS as normal unless we're assigning to 9781 // a bitfield. 9782 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 9783 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 9784 E->getOperatorLoc())) { 9785 // Recurse, ignoring any implicit conversions on the RHS. 9786 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 9787 E->getOperatorLoc()); 9788 } 9789 } 9790 9791 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9792 } 9793 9794 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9795 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 9796 SourceLocation CContext, unsigned diag, 9797 bool pruneControlFlow = false) { 9798 if (pruneControlFlow) { 9799 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9800 S.PDiag(diag) 9801 << SourceType << T << E->getSourceRange() 9802 << SourceRange(CContext)); 9803 return; 9804 } 9805 S.Diag(E->getExprLoc(), diag) 9806 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 9807 } 9808 9809 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 9810 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 9811 SourceLocation CContext, 9812 unsigned diag, bool pruneControlFlow = false) { 9813 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 9814 } 9815 9816 /// Analyze the given compound assignment for the possible losing of 9817 /// floating-point precision. 9818 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 9819 assert(isa<CompoundAssignOperator>(E) && 9820 "Must be compound assignment operation"); 9821 // Recurse on the LHS and RHS in here 9822 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 9823 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 9824 9825 // Now check the outermost expression 9826 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 9827 const auto *RBT = cast<CompoundAssignOperator>(E) 9828 ->getComputationResultType() 9829 ->getAs<BuiltinType>(); 9830 9831 // If both source and target are floating points. 9832 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint()) 9833 // Builtin FP kinds are ordered by increasing FP rank. 9834 if (ResultBT->getKind() < RBT->getKind()) 9835 // We don't want to warn for system macro. 9836 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 9837 // warn about dropping FP rank. 9838 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), 9839 E->getOperatorLoc(), 9840 diag::warn_impcast_float_result_precision); 9841 } 9842 9843 /// Diagnose an implicit cast from a floating point value to an integer value. 9844 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 9845 SourceLocation CContext) { 9846 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 9847 const bool PruneWarnings = S.inTemplateInstantiation(); 9848 9849 Expr *InnerE = E->IgnoreParenImpCasts(); 9850 // We also want to warn on, e.g., "int i = -1.234" 9851 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 9852 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 9853 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 9854 9855 const bool IsLiteral = 9856 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 9857 9858 llvm::APFloat Value(0.0); 9859 bool IsConstant = 9860 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 9861 if (!IsConstant) { 9862 return DiagnoseImpCast(S, E, T, CContext, 9863 diag::warn_impcast_float_integer, PruneWarnings); 9864 } 9865 9866 bool isExact = false; 9867 9868 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 9869 T->hasUnsignedIntegerRepresentation()); 9870 llvm::APFloat::opStatus Result = Value.convertToInteger( 9871 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 9872 9873 if (Result == llvm::APFloat::opOK && isExact) { 9874 if (IsLiteral) return; 9875 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 9876 PruneWarnings); 9877 } 9878 9879 // Conversion of a floating-point value to a non-bool integer where the 9880 // integral part cannot be represented by the integer type is undefined. 9881 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 9882 return DiagnoseImpCast( 9883 S, E, T, CContext, 9884 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 9885 : diag::warn_impcast_float_to_integer_out_of_range, 9886 PruneWarnings); 9887 9888 unsigned DiagID = 0; 9889 if (IsLiteral) { 9890 // Warn on floating point literal to integer. 9891 DiagID = diag::warn_impcast_literal_float_to_integer; 9892 } else if (IntegerValue == 0) { 9893 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 9894 return DiagnoseImpCast(S, E, T, CContext, 9895 diag::warn_impcast_float_integer, PruneWarnings); 9896 } 9897 // Warn on non-zero to zero conversion. 9898 DiagID = diag::warn_impcast_float_to_integer_zero; 9899 } else { 9900 if (IntegerValue.isUnsigned()) { 9901 if (!IntegerValue.isMaxValue()) { 9902 return DiagnoseImpCast(S, E, T, CContext, 9903 diag::warn_impcast_float_integer, PruneWarnings); 9904 } 9905 } else { // IntegerValue.isSigned() 9906 if (!IntegerValue.isMaxSignedValue() && 9907 !IntegerValue.isMinSignedValue()) { 9908 return DiagnoseImpCast(S, E, T, CContext, 9909 diag::warn_impcast_float_integer, PruneWarnings); 9910 } 9911 } 9912 // Warn on evaluatable floating point expression to integer conversion. 9913 DiagID = diag::warn_impcast_float_to_integer; 9914 } 9915 9916 // FIXME: Force the precision of the source value down so we don't print 9917 // digits which are usually useless (we don't really care here if we 9918 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 9919 // would automatically print the shortest representation, but it's a bit 9920 // tricky to implement. 9921 SmallString<16> PrettySourceValue; 9922 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 9923 precision = (precision * 59 + 195) / 196; 9924 Value.toString(PrettySourceValue, precision); 9925 9926 SmallString<16> PrettyTargetValue; 9927 if (IsBool) 9928 PrettyTargetValue = Value.isZero() ? "false" : "true"; 9929 else 9930 IntegerValue.toString(PrettyTargetValue); 9931 9932 if (PruneWarnings) { 9933 S.DiagRuntimeBehavior(E->getExprLoc(), E, 9934 S.PDiag(DiagID) 9935 << E->getType() << T.getUnqualifiedType() 9936 << PrettySourceValue << PrettyTargetValue 9937 << E->getSourceRange() << SourceRange(CContext)); 9938 } else { 9939 S.Diag(E->getExprLoc(), DiagID) 9940 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 9941 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 9942 } 9943 } 9944 9945 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 9946 IntRange Range) { 9947 if (!Range.Width) return "0"; 9948 9949 llvm::APSInt ValueInRange = Value; 9950 ValueInRange.setIsSigned(!Range.NonNegative); 9951 ValueInRange = ValueInRange.trunc(Range.Width); 9952 return ValueInRange.toString(10); 9953 } 9954 9955 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 9956 if (!isa<ImplicitCastExpr>(Ex)) 9957 return false; 9958 9959 Expr *InnerE = Ex->IgnoreParenImpCasts(); 9960 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 9961 const Type *Source = 9962 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 9963 if (Target->isDependentType()) 9964 return false; 9965 9966 const BuiltinType *FloatCandidateBT = 9967 dyn_cast<BuiltinType>(ToBool ? Source : Target); 9968 const Type *BoolCandidateType = ToBool ? Target : Source; 9969 9970 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 9971 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 9972 } 9973 9974 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 9975 SourceLocation CC) { 9976 unsigned NumArgs = TheCall->getNumArgs(); 9977 for (unsigned i = 0; i < NumArgs; ++i) { 9978 Expr *CurrA = TheCall->getArg(i); 9979 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 9980 continue; 9981 9982 bool IsSwapped = ((i > 0) && 9983 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 9984 IsSwapped |= ((i < (NumArgs - 1)) && 9985 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 9986 if (IsSwapped) { 9987 // Warn on this floating-point to bool conversion. 9988 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 9989 CurrA->getType(), CC, 9990 diag::warn_impcast_floating_point_to_bool); 9991 } 9992 } 9993 } 9994 9995 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 9996 SourceLocation CC) { 9997 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 9998 E->getExprLoc())) 9999 return; 10000 10001 // Don't warn on functions which have return type nullptr_t. 10002 if (isa<CallExpr>(E)) 10003 return; 10004 10005 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10006 const Expr::NullPointerConstantKind NullKind = 10007 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10008 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10009 return; 10010 10011 // Return if target type is a safe conversion. 10012 if (T->isAnyPointerType() || T->isBlockPointerType() || 10013 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10014 return; 10015 10016 SourceLocation Loc = E->getSourceRange().getBegin(); 10017 10018 // Venture through the macro stacks to get to the source of macro arguments. 10019 // The new location is a better location than the complete location that was 10020 // passed in. 10021 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10022 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10023 10024 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10025 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10026 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10027 Loc, S.SourceMgr, S.getLangOpts()); 10028 if (MacroName == "NULL") 10029 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10030 } 10031 10032 // Only warn if the null and context location are in the same macro expansion. 10033 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10034 return; 10035 10036 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10037 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10038 << FixItHint::CreateReplacement(Loc, 10039 S.getFixItZeroLiteralForType(T, Loc)); 10040 } 10041 10042 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10043 ObjCArrayLiteral *ArrayLiteral); 10044 10045 static void 10046 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10047 ObjCDictionaryLiteral *DictionaryLiteral); 10048 10049 /// Check a single element within a collection literal against the 10050 /// target element type. 10051 static void checkObjCCollectionLiteralElement(Sema &S, 10052 QualType TargetElementType, 10053 Expr *Element, 10054 unsigned ElementKind) { 10055 // Skip a bitcast to 'id' or qualified 'id'. 10056 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10057 if (ICE->getCastKind() == CK_BitCast && 10058 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10059 Element = ICE->getSubExpr(); 10060 } 10061 10062 QualType ElementType = Element->getType(); 10063 ExprResult ElementResult(Element); 10064 if (ElementType->getAs<ObjCObjectPointerType>() && 10065 S.CheckSingleAssignmentConstraints(TargetElementType, 10066 ElementResult, 10067 false, false) 10068 != Sema::Compatible) { 10069 S.Diag(Element->getLocStart(), 10070 diag::warn_objc_collection_literal_element) 10071 << ElementType << ElementKind << TargetElementType 10072 << Element->getSourceRange(); 10073 } 10074 10075 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10076 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10077 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10078 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10079 } 10080 10081 /// Check an Objective-C array literal being converted to the given 10082 /// target type. 10083 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10084 ObjCArrayLiteral *ArrayLiteral) { 10085 if (!S.NSArrayDecl) 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.NSArrayDecl->getCanonicalDecl()) 10095 return; 10096 10097 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10098 if (TypeArgs.size() != 1) 10099 return; 10100 10101 QualType TargetElementType = TypeArgs[0]; 10102 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10103 checkObjCCollectionLiteralElement(S, TargetElementType, 10104 ArrayLiteral->getElement(I), 10105 0); 10106 } 10107 } 10108 10109 /// Check an Objective-C dictionary literal being converted to the given 10110 /// target type. 10111 static void 10112 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10113 ObjCDictionaryLiteral *DictionaryLiteral) { 10114 if (!S.NSDictionaryDecl) 10115 return; 10116 10117 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10118 if (!TargetObjCPtr) 10119 return; 10120 10121 if (TargetObjCPtr->isUnspecialized() || 10122 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10123 != S.NSDictionaryDecl->getCanonicalDecl()) 10124 return; 10125 10126 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10127 if (TypeArgs.size() != 2) 10128 return; 10129 10130 QualType TargetKeyType = TypeArgs[0]; 10131 QualType TargetObjectType = TypeArgs[1]; 10132 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10133 auto Element = DictionaryLiteral->getKeyValueElement(I); 10134 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10135 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10136 } 10137 } 10138 10139 // Helper function to filter out cases for constant width constant conversion. 10140 // Don't warn on char array initialization or for non-decimal values. 10141 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10142 SourceLocation CC) { 10143 // If initializing from a constant, and the constant starts with '0', 10144 // then it is a binary, octal, or hexadecimal. Allow these constants 10145 // to fill all the bits, even if there is a sign change. 10146 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10147 const char FirstLiteralCharacter = 10148 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0]; 10149 if (FirstLiteralCharacter == '0') 10150 return false; 10151 } 10152 10153 // If the CC location points to a '{', and the type is char, then assume 10154 // assume it is an array initialization. 10155 if (CC.isValid() && T->isCharType()) { 10156 const char FirstContextCharacter = 10157 S.getSourceManager().getCharacterData(CC)[0]; 10158 if (FirstContextCharacter == '{') 10159 return false; 10160 } 10161 10162 return true; 10163 } 10164 10165 static void 10166 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10167 bool *ICContext = nullptr) { 10168 if (E->isTypeDependent() || E->isValueDependent()) return; 10169 10170 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10171 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10172 if (Source == Target) return; 10173 if (Target->isDependentType()) return; 10174 10175 // If the conversion context location is invalid don't complain. We also 10176 // don't want to emit a warning if the issue occurs from the expansion of 10177 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10178 // delay this check as long as possible. Once we detect we are in that 10179 // scenario, we just return. 10180 if (CC.isInvalid()) 10181 return; 10182 10183 // Diagnose implicit casts to bool. 10184 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10185 if (isa<StringLiteral>(E)) 10186 // Warn on string literal to bool. Checks for string literals in logical 10187 // and expressions, for instance, assert(0 && "error here"), are 10188 // prevented by a check in AnalyzeImplicitConversions(). 10189 return DiagnoseImpCast(S, E, T, CC, 10190 diag::warn_impcast_string_literal_to_bool); 10191 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10192 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10193 // This covers the literal expressions that evaluate to Objective-C 10194 // objects. 10195 return DiagnoseImpCast(S, E, T, CC, 10196 diag::warn_impcast_objective_c_literal_to_bool); 10197 } 10198 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10199 // Warn on pointer to bool conversion that is always true. 10200 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10201 SourceRange(CC)); 10202 } 10203 } 10204 10205 // Check implicit casts from Objective-C collection literals to specialized 10206 // collection types, e.g., NSArray<NSString *> *. 10207 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10208 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10209 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10210 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10211 10212 // Strip vector types. 10213 if (isa<VectorType>(Source)) { 10214 if (!isa<VectorType>(Target)) { 10215 if (S.SourceMgr.isInSystemMacro(CC)) 10216 return; 10217 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10218 } 10219 10220 // If the vector cast is cast between two vectors of the same size, it is 10221 // a bitcast, not a conversion. 10222 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10223 return; 10224 10225 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10226 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10227 } 10228 if (auto VecTy = dyn_cast<VectorType>(Target)) 10229 Target = VecTy->getElementType().getTypePtr(); 10230 10231 // Strip complex types. 10232 if (isa<ComplexType>(Source)) { 10233 if (!isa<ComplexType>(Target)) { 10234 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10235 return; 10236 10237 return DiagnoseImpCast(S, E, T, CC, 10238 S.getLangOpts().CPlusPlus 10239 ? diag::err_impcast_complex_scalar 10240 : diag::warn_impcast_complex_scalar); 10241 } 10242 10243 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10244 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10245 } 10246 10247 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10248 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10249 10250 // If the source is floating point... 10251 if (SourceBT && SourceBT->isFloatingPoint()) { 10252 // ...and the target is floating point... 10253 if (TargetBT && TargetBT->isFloatingPoint()) { 10254 // ...then warn if we're dropping FP rank. 10255 10256 // Builtin FP kinds are ordered by increasing FP rank. 10257 if (SourceBT->getKind() > TargetBT->getKind()) { 10258 // Don't warn about float constants that are precisely 10259 // representable in the target type. 10260 Expr::EvalResult result; 10261 if (E->EvaluateAsRValue(result, S.Context)) { 10262 // Value might be a float, a float vector, or a float complex. 10263 if (IsSameFloatAfterCast(result.Val, 10264 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10265 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10266 return; 10267 } 10268 10269 if (S.SourceMgr.isInSystemMacro(CC)) 10270 return; 10271 10272 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10273 } 10274 // ... or possibly if we're increasing rank, too 10275 else if (TargetBT->getKind() > SourceBT->getKind()) { 10276 if (S.SourceMgr.isInSystemMacro(CC)) 10277 return; 10278 10279 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10280 } 10281 return; 10282 } 10283 10284 // If the target is integral, always warn. 10285 if (TargetBT && TargetBT->isInteger()) { 10286 if (S.SourceMgr.isInSystemMacro(CC)) 10287 return; 10288 10289 DiagnoseFloatingImpCast(S, E, T, CC); 10290 } 10291 10292 // Detect the case where a call result is converted from floating-point to 10293 // to bool, and the final argument to the call is converted from bool, to 10294 // discover this typo: 10295 // 10296 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10297 // 10298 // FIXME: This is an incredibly special case; is there some more general 10299 // way to detect this class of misplaced-parentheses bug? 10300 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10301 // Check last argument of function call to see if it is an 10302 // implicit cast from a type matching the type the result 10303 // is being cast to. 10304 CallExpr *CEx = cast<CallExpr>(E); 10305 if (unsigned NumArgs = CEx->getNumArgs()) { 10306 Expr *LastA = CEx->getArg(NumArgs - 1); 10307 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10308 if (isa<ImplicitCastExpr>(LastA) && 10309 InnerE->getType()->isBooleanType()) { 10310 // Warn on this floating-point to bool conversion 10311 DiagnoseImpCast(S, E, T, CC, 10312 diag::warn_impcast_floating_point_to_bool); 10313 } 10314 } 10315 } 10316 return; 10317 } 10318 10319 DiagnoseNullConversion(S, E, T, CC); 10320 10321 S.DiscardMisalignedMemberAddress(Target, E); 10322 10323 if (!Source->isIntegerType() || !Target->isIntegerType()) 10324 return; 10325 10326 // TODO: remove this early return once the false positives for constant->bool 10327 // in templates, macros, etc, are reduced or removed. 10328 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10329 return; 10330 10331 IntRange SourceRange = GetExprRange(S.Context, E); 10332 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10333 10334 if (SourceRange.Width > TargetRange.Width) { 10335 // If the source is a constant, use a default-on diagnostic. 10336 // TODO: this should happen for bitfield stores, too. 10337 llvm::APSInt Value(32); 10338 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10339 if (S.SourceMgr.isInSystemMacro(CC)) 10340 return; 10341 10342 std::string PrettySourceValue = Value.toString(10); 10343 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10344 10345 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10346 S.PDiag(diag::warn_impcast_integer_precision_constant) 10347 << PrettySourceValue << PrettyTargetValue 10348 << E->getType() << T << E->getSourceRange() 10349 << clang::SourceRange(CC)); 10350 return; 10351 } 10352 10353 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10354 if (S.SourceMgr.isInSystemMacro(CC)) 10355 return; 10356 10357 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10358 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10359 /* pruneControlFlow */ true); 10360 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10361 } 10362 10363 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10364 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10365 // Warn when doing a signed to signed conversion, warn if the positive 10366 // source value is exactly the width of the target type, which will 10367 // cause a negative value to be stored. 10368 10369 llvm::APSInt Value; 10370 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10371 !S.SourceMgr.isInSystemMacro(CC)) { 10372 if (isSameWidthConstantConversion(S, E, T, CC)) { 10373 std::string PrettySourceValue = Value.toString(10); 10374 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10375 10376 S.DiagRuntimeBehavior( 10377 E->getExprLoc(), E, 10378 S.PDiag(diag::warn_impcast_integer_precision_constant) 10379 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10380 << E->getSourceRange() << clang::SourceRange(CC)); 10381 return; 10382 } 10383 } 10384 10385 // Fall through for non-constants to give a sign conversion warning. 10386 } 10387 10388 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10389 (!TargetRange.NonNegative && SourceRange.NonNegative && 10390 SourceRange.Width == TargetRange.Width)) { 10391 if (S.SourceMgr.isInSystemMacro(CC)) 10392 return; 10393 10394 unsigned DiagID = diag::warn_impcast_integer_sign; 10395 10396 // Traditionally, gcc has warned about this under -Wsign-compare. 10397 // We also want to warn about it in -Wconversion. 10398 // So if -Wconversion is off, use a completely identical diagnostic 10399 // in the sign-compare group. 10400 // The conditional-checking code will 10401 if (ICContext) { 10402 DiagID = diag::warn_impcast_integer_sign_conditional; 10403 *ICContext = true; 10404 } 10405 10406 return DiagnoseImpCast(S, E, T, CC, DiagID); 10407 } 10408 10409 // Diagnose conversions between different enumeration types. 10410 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10411 // type, to give us better diagnostics. 10412 QualType SourceType = E->getType(); 10413 if (!S.getLangOpts().CPlusPlus) { 10414 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10415 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10416 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10417 SourceType = S.Context.getTypeDeclType(Enum); 10418 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10419 } 10420 } 10421 10422 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10423 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10424 if (SourceEnum->getDecl()->hasNameForLinkage() && 10425 TargetEnum->getDecl()->hasNameForLinkage() && 10426 SourceEnum != TargetEnum) { 10427 if (S.SourceMgr.isInSystemMacro(CC)) 10428 return; 10429 10430 return DiagnoseImpCast(S, E, SourceType, T, CC, 10431 diag::warn_impcast_different_enum_types); 10432 } 10433 } 10434 10435 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10436 SourceLocation CC, QualType T); 10437 10438 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10439 SourceLocation CC, bool &ICContext) { 10440 E = E->IgnoreParenImpCasts(); 10441 10442 if (isa<ConditionalOperator>(E)) 10443 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10444 10445 AnalyzeImplicitConversions(S, E, CC); 10446 if (E->getType() != T) 10447 return CheckImplicitConversion(S, E, T, CC, &ICContext); 10448 } 10449 10450 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10451 SourceLocation CC, QualType T) { 10452 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 10453 10454 bool Suspicious = false; 10455 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 10456 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 10457 10458 // If -Wconversion would have warned about either of the candidates 10459 // for a signedness conversion to the context type... 10460 if (!Suspicious) return; 10461 10462 // ...but it's currently ignored... 10463 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 10464 return; 10465 10466 // ...then check whether it would have warned about either of the 10467 // candidates for a signedness conversion to the condition type. 10468 if (E->getType() == T) return; 10469 10470 Suspicious = false; 10471 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 10472 E->getType(), CC, &Suspicious); 10473 if (!Suspicious) 10474 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 10475 E->getType(), CC, &Suspicious); 10476 } 10477 10478 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10479 /// Input argument E is a logical expression. 10480 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 10481 if (S.getLangOpts().Bool) 10482 return; 10483 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 10484 } 10485 10486 /// AnalyzeImplicitConversions - Find and report any interesting 10487 /// implicit conversions in the given expression. There are a couple 10488 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 10489 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 10490 SourceLocation CC) { 10491 QualType T = OrigE->getType(); 10492 Expr *E = OrigE->IgnoreParenImpCasts(); 10493 10494 if (E->isTypeDependent() || E->isValueDependent()) 10495 return; 10496 10497 // For conditional operators, we analyze the arguments as if they 10498 // were being fed directly into the output. 10499 if (isa<ConditionalOperator>(E)) { 10500 ConditionalOperator *CO = cast<ConditionalOperator>(E); 10501 CheckConditionalOperator(S, CO, CC, T); 10502 return; 10503 } 10504 10505 // Check implicit argument conversions for function calls. 10506 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 10507 CheckImplicitArgumentConversions(S, Call, CC); 10508 10509 // Go ahead and check any implicit conversions we might have skipped. 10510 // The non-canonical typecheck is just an optimization; 10511 // CheckImplicitConversion will filter out dead implicit conversions. 10512 if (E->getType() != T) 10513 CheckImplicitConversion(S, E, T, CC); 10514 10515 // Now continue drilling into this expression. 10516 10517 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 10518 // The bound subexpressions in a PseudoObjectExpr are not reachable 10519 // as transitive children. 10520 // FIXME: Use a more uniform representation for this. 10521 for (auto *SE : POE->semantics()) 10522 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 10523 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 10524 } 10525 10526 // Skip past explicit casts. 10527 if (isa<ExplicitCastExpr>(E)) { 10528 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts(); 10529 return AnalyzeImplicitConversions(S, E, CC); 10530 } 10531 10532 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10533 // Do a somewhat different check with comparison operators. 10534 if (BO->isComparisonOp()) 10535 return AnalyzeComparison(S, BO); 10536 10537 // And with simple assignments. 10538 if (BO->getOpcode() == BO_Assign) 10539 return AnalyzeAssignment(S, BO); 10540 // And with compound assignments. 10541 if (BO->isAssignmentOp()) 10542 return AnalyzeCompoundAssignment(S, BO); 10543 } 10544 10545 // These break the otherwise-useful invariant below. Fortunately, 10546 // we don't really need to recurse into them, because any internal 10547 // expressions should have been analyzed already when they were 10548 // built into statements. 10549 if (isa<StmtExpr>(E)) return; 10550 10551 // Don't descend into unevaluated contexts. 10552 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 10553 10554 // Now just recurse over the expression's children. 10555 CC = E->getExprLoc(); 10556 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 10557 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 10558 for (Stmt *SubStmt : E->children()) { 10559 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 10560 if (!ChildExpr) 10561 continue; 10562 10563 if (IsLogicalAndOperator && 10564 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 10565 // Ignore checking string literals that are in logical and operators. 10566 // This is a common pattern for asserts. 10567 continue; 10568 AnalyzeImplicitConversions(S, ChildExpr, CC); 10569 } 10570 10571 if (BO && BO->isLogicalOp()) { 10572 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 10573 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10574 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10575 10576 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 10577 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 10578 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 10579 } 10580 10581 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) 10582 if (U->getOpcode() == UO_LNot) 10583 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 10584 } 10585 10586 /// Diagnose integer type and any valid implicit conversion to it. 10587 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 10588 // Taking into account implicit conversions, 10589 // allow any integer. 10590 if (!E->getType()->isIntegerType()) { 10591 S.Diag(E->getLocStart(), 10592 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 10593 return true; 10594 } 10595 // Potentially emit standard warnings for implicit conversions if enabled 10596 // using -Wconversion. 10597 CheckImplicitConversion(S, E, IntT, E->getLocStart()); 10598 return false; 10599 } 10600 10601 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 10602 // Returns true when emitting a warning about taking the address of a reference. 10603 static bool CheckForReference(Sema &SemaRef, const Expr *E, 10604 const PartialDiagnostic &PD) { 10605 E = E->IgnoreParenImpCasts(); 10606 10607 const FunctionDecl *FD = nullptr; 10608 10609 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10610 if (!DRE->getDecl()->getType()->isReferenceType()) 10611 return false; 10612 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10613 if (!M->getMemberDecl()->getType()->isReferenceType()) 10614 return false; 10615 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 10616 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 10617 return false; 10618 FD = Call->getDirectCallee(); 10619 } else { 10620 return false; 10621 } 10622 10623 SemaRef.Diag(E->getExprLoc(), PD); 10624 10625 // If possible, point to location of function. 10626 if (FD) { 10627 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 10628 } 10629 10630 return true; 10631 } 10632 10633 // Returns true if the SourceLocation is expanded from any macro body. 10634 // Returns false if the SourceLocation is invalid, is from not in a macro 10635 // expansion, or is from expanded from a top-level macro argument. 10636 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 10637 if (Loc.isInvalid()) 10638 return false; 10639 10640 while (Loc.isMacroID()) { 10641 if (SM.isMacroBodyExpansion(Loc)) 10642 return true; 10643 Loc = SM.getImmediateMacroCallerLoc(Loc); 10644 } 10645 10646 return false; 10647 } 10648 10649 /// Diagnose pointers that are always non-null. 10650 /// \param E the expression containing the pointer 10651 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 10652 /// compared to a null pointer 10653 /// \param IsEqual True when the comparison is equal to a null pointer 10654 /// \param Range Extra SourceRange to highlight in the diagnostic 10655 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 10656 Expr::NullPointerConstantKind NullKind, 10657 bool IsEqual, SourceRange Range) { 10658 if (!E) 10659 return; 10660 10661 // Don't warn inside macros. 10662 if (E->getExprLoc().isMacroID()) { 10663 const SourceManager &SM = getSourceManager(); 10664 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 10665 IsInAnyMacroBody(SM, Range.getBegin())) 10666 return; 10667 } 10668 E = E->IgnoreImpCasts(); 10669 10670 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 10671 10672 if (isa<CXXThisExpr>(E)) { 10673 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 10674 : diag::warn_this_bool_conversion; 10675 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 10676 return; 10677 } 10678 10679 bool IsAddressOf = false; 10680 10681 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 10682 if (UO->getOpcode() != UO_AddrOf) 10683 return; 10684 IsAddressOf = true; 10685 E = UO->getSubExpr(); 10686 } 10687 10688 if (IsAddressOf) { 10689 unsigned DiagID = IsCompare 10690 ? diag::warn_address_of_reference_null_compare 10691 : diag::warn_address_of_reference_bool_conversion; 10692 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 10693 << IsEqual; 10694 if (CheckForReference(*this, E, PD)) { 10695 return; 10696 } 10697 } 10698 10699 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 10700 bool IsParam = isa<NonNullAttr>(NonnullAttr); 10701 std::string Str; 10702 llvm::raw_string_ostream S(Str); 10703 E->printPretty(S, nullptr, getPrintingPolicy()); 10704 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 10705 : diag::warn_cast_nonnull_to_bool; 10706 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 10707 << E->getSourceRange() << Range << IsEqual; 10708 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 10709 }; 10710 10711 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 10712 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 10713 if (auto *Callee = Call->getDirectCallee()) { 10714 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 10715 ComplainAboutNonnullParamOrCall(A); 10716 return; 10717 } 10718 } 10719 } 10720 10721 // Expect to find a single Decl. Skip anything more complicated. 10722 ValueDecl *D = nullptr; 10723 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 10724 D = R->getDecl(); 10725 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 10726 D = M->getMemberDecl(); 10727 } 10728 10729 // Weak Decls can be null. 10730 if (!D || D->isWeak()) 10731 return; 10732 10733 // Check for parameter decl with nonnull attribute 10734 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 10735 if (getCurFunction() && 10736 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 10737 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 10738 ComplainAboutNonnullParamOrCall(A); 10739 return; 10740 } 10741 10742 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 10743 auto ParamIter = llvm::find(FD->parameters(), PV); 10744 assert(ParamIter != FD->param_end()); 10745 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 10746 10747 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 10748 if (!NonNull->args_size()) { 10749 ComplainAboutNonnullParamOrCall(NonNull); 10750 return; 10751 } 10752 10753 for (const ParamIdx &ArgNo : NonNull->args()) { 10754 if (ArgNo.getASTIndex() == ParamNo) { 10755 ComplainAboutNonnullParamOrCall(NonNull); 10756 return; 10757 } 10758 } 10759 } 10760 } 10761 } 10762 } 10763 10764 QualType T = D->getType(); 10765 const bool IsArray = T->isArrayType(); 10766 const bool IsFunction = T->isFunctionType(); 10767 10768 // Address of function is used to silence the function warning. 10769 if (IsAddressOf && IsFunction) { 10770 return; 10771 } 10772 10773 // Found nothing. 10774 if (!IsAddressOf && !IsFunction && !IsArray) 10775 return; 10776 10777 // Pretty print the expression for the diagnostic. 10778 std::string Str; 10779 llvm::raw_string_ostream S(Str); 10780 E->printPretty(S, nullptr, getPrintingPolicy()); 10781 10782 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 10783 : diag::warn_impcast_pointer_to_bool; 10784 enum { 10785 AddressOf, 10786 FunctionPointer, 10787 ArrayPointer 10788 } DiagType; 10789 if (IsAddressOf) 10790 DiagType = AddressOf; 10791 else if (IsFunction) 10792 DiagType = FunctionPointer; 10793 else if (IsArray) 10794 DiagType = ArrayPointer; 10795 else 10796 llvm_unreachable("Could not determine diagnostic."); 10797 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 10798 << Range << IsEqual; 10799 10800 if (!IsFunction) 10801 return; 10802 10803 // Suggest '&' to silence the function warning. 10804 Diag(E->getExprLoc(), diag::note_function_warning_silence) 10805 << FixItHint::CreateInsertion(E->getLocStart(), "&"); 10806 10807 // Check to see if '()' fixit should be emitted. 10808 QualType ReturnType; 10809 UnresolvedSet<4> NonTemplateOverloads; 10810 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 10811 if (ReturnType.isNull()) 10812 return; 10813 10814 if (IsCompare) { 10815 // There are two cases here. If there is null constant, the only suggest 10816 // for a pointer return type. If the null is 0, then suggest if the return 10817 // type is a pointer or an integer type. 10818 if (!ReturnType->isPointerType()) { 10819 if (NullKind == Expr::NPCK_ZeroExpression || 10820 NullKind == Expr::NPCK_ZeroLiteral) { 10821 if (!ReturnType->isIntegerType()) 10822 return; 10823 } else { 10824 return; 10825 } 10826 } 10827 } else { // !IsCompare 10828 // For function to bool, only suggest if the function pointer has bool 10829 // return type. 10830 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 10831 return; 10832 } 10833 Diag(E->getExprLoc(), diag::note_function_to_function_call) 10834 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()"); 10835 } 10836 10837 /// Diagnoses "dangerous" implicit conversions within the given 10838 /// expression (which is a full expression). Implements -Wconversion 10839 /// and -Wsign-compare. 10840 /// 10841 /// \param CC the "context" location of the implicit conversion, i.e. 10842 /// the most location of the syntactic entity requiring the implicit 10843 /// conversion 10844 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 10845 // Don't diagnose in unevaluated contexts. 10846 if (isUnevaluatedContext()) 10847 return; 10848 10849 // Don't diagnose for value- or type-dependent expressions. 10850 if (E->isTypeDependent() || E->isValueDependent()) 10851 return; 10852 10853 // Check for array bounds violations in cases where the check isn't triggered 10854 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 10855 // ArraySubscriptExpr is on the RHS of a variable initialization. 10856 CheckArrayAccess(E); 10857 10858 // This is not the right CC for (e.g.) a variable initialization. 10859 AnalyzeImplicitConversions(*this, E, CC); 10860 } 10861 10862 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 10863 /// Input argument E is a logical expression. 10864 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 10865 ::CheckBoolLikeConversion(*this, E, CC); 10866 } 10867 10868 /// Diagnose when expression is an integer constant expression and its evaluation 10869 /// results in integer overflow 10870 void Sema::CheckForIntOverflow (Expr *E) { 10871 // Use a work list to deal with nested struct initializers. 10872 SmallVector<Expr *, 2> Exprs(1, E); 10873 10874 do { 10875 Expr *OriginalE = Exprs.pop_back_val(); 10876 Expr *E = OriginalE->IgnoreParenCasts(); 10877 10878 if (isa<BinaryOperator>(E)) { 10879 E->EvaluateForOverflow(Context); 10880 continue; 10881 } 10882 10883 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 10884 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 10885 else if (isa<ObjCBoxedExpr>(OriginalE)) 10886 E->EvaluateForOverflow(Context); 10887 else if (auto Call = dyn_cast<CallExpr>(E)) 10888 Exprs.append(Call->arg_begin(), Call->arg_end()); 10889 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 10890 Exprs.append(Message->arg_begin(), Message->arg_end()); 10891 } while (!Exprs.empty()); 10892 } 10893 10894 namespace { 10895 10896 /// Visitor for expressions which looks for unsequenced operations on the 10897 /// same object. 10898 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 10899 using Base = EvaluatedExprVisitor<SequenceChecker>; 10900 10901 /// A tree of sequenced regions within an expression. Two regions are 10902 /// unsequenced if one is an ancestor or a descendent of the other. When we 10903 /// finish processing an expression with sequencing, such as a comma 10904 /// expression, we fold its tree nodes into its parent, since they are 10905 /// unsequenced with respect to nodes we will visit later. 10906 class SequenceTree { 10907 struct Value { 10908 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 10909 unsigned Parent : 31; 10910 unsigned Merged : 1; 10911 }; 10912 SmallVector<Value, 8> Values; 10913 10914 public: 10915 /// A region within an expression which may be sequenced with respect 10916 /// to some other region. 10917 class Seq { 10918 friend class SequenceTree; 10919 10920 unsigned Index = 0; 10921 10922 explicit Seq(unsigned N) : Index(N) {} 10923 10924 public: 10925 Seq() = default; 10926 }; 10927 10928 SequenceTree() { Values.push_back(Value(0)); } 10929 Seq root() const { return Seq(0); } 10930 10931 /// Create a new sequence of operations, which is an unsequenced 10932 /// subset of \p Parent. This sequence of operations is sequenced with 10933 /// respect to other children of \p Parent. 10934 Seq allocate(Seq Parent) { 10935 Values.push_back(Value(Parent.Index)); 10936 return Seq(Values.size() - 1); 10937 } 10938 10939 /// Merge a sequence of operations into its parent. 10940 void merge(Seq S) { 10941 Values[S.Index].Merged = true; 10942 } 10943 10944 /// Determine whether two operations are unsequenced. This operation 10945 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 10946 /// should have been merged into its parent as appropriate. 10947 bool isUnsequenced(Seq Cur, Seq Old) { 10948 unsigned C = representative(Cur.Index); 10949 unsigned Target = representative(Old.Index); 10950 while (C >= Target) { 10951 if (C == Target) 10952 return true; 10953 C = Values[C].Parent; 10954 } 10955 return false; 10956 } 10957 10958 private: 10959 /// Pick a representative for a sequence. 10960 unsigned representative(unsigned K) { 10961 if (Values[K].Merged) 10962 // Perform path compression as we go. 10963 return Values[K].Parent = representative(Values[K].Parent); 10964 return K; 10965 } 10966 }; 10967 10968 /// An object for which we can track unsequenced uses. 10969 using Object = NamedDecl *; 10970 10971 /// Different flavors of object usage which we track. We only track the 10972 /// least-sequenced usage of each kind. 10973 enum UsageKind { 10974 /// A read of an object. Multiple unsequenced reads are OK. 10975 UK_Use, 10976 10977 /// A modification of an object which is sequenced before the value 10978 /// computation of the expression, such as ++n in C++. 10979 UK_ModAsValue, 10980 10981 /// A modification of an object which is not sequenced before the value 10982 /// computation of the expression, such as n++. 10983 UK_ModAsSideEffect, 10984 10985 UK_Count = UK_ModAsSideEffect + 1 10986 }; 10987 10988 struct Usage { 10989 Expr *Use = nullptr; 10990 SequenceTree::Seq Seq; 10991 10992 Usage() = default; 10993 }; 10994 10995 struct UsageInfo { 10996 Usage Uses[UK_Count]; 10997 10998 /// Have we issued a diagnostic for this variable already? 10999 bool Diagnosed = false; 11000 11001 UsageInfo() = default; 11002 }; 11003 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11004 11005 Sema &SemaRef; 11006 11007 /// Sequenced regions within the expression. 11008 SequenceTree Tree; 11009 11010 /// Declaration modifications and references which we have seen. 11011 UsageInfoMap UsageMap; 11012 11013 /// The region we are currently within. 11014 SequenceTree::Seq Region; 11015 11016 /// Filled in with declarations which were modified as a side-effect 11017 /// (that is, post-increment operations). 11018 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11019 11020 /// Expressions to check later. We defer checking these to reduce 11021 /// stack usage. 11022 SmallVectorImpl<Expr *> &WorkList; 11023 11024 /// RAII object wrapping the visitation of a sequenced subexpression of an 11025 /// expression. At the end of this process, the side-effects of the evaluation 11026 /// become sequenced with respect to the value computation of the result, so 11027 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11028 /// UK_ModAsValue. 11029 struct SequencedSubexpression { 11030 SequencedSubexpression(SequenceChecker &Self) 11031 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11032 Self.ModAsSideEffect = &ModAsSideEffect; 11033 } 11034 11035 ~SequencedSubexpression() { 11036 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11037 UsageInfo &U = Self.UsageMap[M.first]; 11038 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11039 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11040 SideEffectUsage = M.second; 11041 } 11042 Self.ModAsSideEffect = OldModAsSideEffect; 11043 } 11044 11045 SequenceChecker &Self; 11046 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11047 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11048 }; 11049 11050 /// RAII object wrapping the visitation of a subexpression which we might 11051 /// choose to evaluate as a constant. If any subexpression is evaluated and 11052 /// found to be non-constant, this allows us to suppress the evaluation of 11053 /// the outer expression. 11054 class EvaluationTracker { 11055 public: 11056 EvaluationTracker(SequenceChecker &Self) 11057 : Self(Self), Prev(Self.EvalTracker) { 11058 Self.EvalTracker = this; 11059 } 11060 11061 ~EvaluationTracker() { 11062 Self.EvalTracker = Prev; 11063 if (Prev) 11064 Prev->EvalOK &= EvalOK; 11065 } 11066 11067 bool evaluate(const Expr *E, bool &Result) { 11068 if (!EvalOK || E->isValueDependent()) 11069 return false; 11070 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11071 return EvalOK; 11072 } 11073 11074 private: 11075 SequenceChecker &Self; 11076 EvaluationTracker *Prev; 11077 bool EvalOK = true; 11078 } *EvalTracker = nullptr; 11079 11080 /// Find the object which is produced by the specified expression, 11081 /// if any. 11082 Object getObject(Expr *E, bool Mod) const { 11083 E = E->IgnoreParenCasts(); 11084 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11085 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11086 return getObject(UO->getSubExpr(), Mod); 11087 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11088 if (BO->getOpcode() == BO_Comma) 11089 return getObject(BO->getRHS(), Mod); 11090 if (Mod && BO->isAssignmentOp()) 11091 return getObject(BO->getLHS(), Mod); 11092 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11093 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11094 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11095 return ME->getMemberDecl(); 11096 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11097 // FIXME: If this is a reference, map through to its value. 11098 return DRE->getDecl(); 11099 return nullptr; 11100 } 11101 11102 /// Note that an object was modified or used by an expression. 11103 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11104 Usage &U = UI.Uses[UK]; 11105 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11106 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11107 ModAsSideEffect->push_back(std::make_pair(O, U)); 11108 U.Use = Ref; 11109 U.Seq = Region; 11110 } 11111 } 11112 11113 /// Check whether a modification or use conflicts with a prior usage. 11114 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11115 bool IsModMod) { 11116 if (UI.Diagnosed) 11117 return; 11118 11119 const Usage &U = UI.Uses[OtherKind]; 11120 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11121 return; 11122 11123 Expr *Mod = U.Use; 11124 Expr *ModOrUse = Ref; 11125 if (OtherKind == UK_Use) 11126 std::swap(Mod, ModOrUse); 11127 11128 SemaRef.Diag(Mod->getExprLoc(), 11129 IsModMod ? diag::warn_unsequenced_mod_mod 11130 : diag::warn_unsequenced_mod_use) 11131 << O << SourceRange(ModOrUse->getExprLoc()); 11132 UI.Diagnosed = true; 11133 } 11134 11135 void notePreUse(Object O, Expr *Use) { 11136 UsageInfo &U = UsageMap[O]; 11137 // Uses conflict with other modifications. 11138 checkUsage(O, U, Use, UK_ModAsValue, false); 11139 } 11140 11141 void notePostUse(Object O, Expr *Use) { 11142 UsageInfo &U = UsageMap[O]; 11143 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11144 addUsage(U, O, Use, UK_Use); 11145 } 11146 11147 void notePreMod(Object O, Expr *Mod) { 11148 UsageInfo &U = UsageMap[O]; 11149 // Modifications conflict with other modifications and with uses. 11150 checkUsage(O, U, Mod, UK_ModAsValue, true); 11151 checkUsage(O, U, Mod, UK_Use, false); 11152 } 11153 11154 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11155 UsageInfo &U = UsageMap[O]; 11156 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11157 addUsage(U, O, Use, UK); 11158 } 11159 11160 public: 11161 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11162 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11163 Visit(E); 11164 } 11165 11166 void VisitStmt(Stmt *S) { 11167 // Skip all statements which aren't expressions for now. 11168 } 11169 11170 void VisitExpr(Expr *E) { 11171 // By default, just recurse to evaluated subexpressions. 11172 Base::VisitStmt(E); 11173 } 11174 11175 void VisitCastExpr(CastExpr *E) { 11176 Object O = Object(); 11177 if (E->getCastKind() == CK_LValueToRValue) 11178 O = getObject(E->getSubExpr(), false); 11179 11180 if (O) 11181 notePreUse(O, E); 11182 VisitExpr(E); 11183 if (O) 11184 notePostUse(O, E); 11185 } 11186 11187 void VisitBinComma(BinaryOperator *BO) { 11188 // C++11 [expr.comma]p1: 11189 // Every value computation and side effect associated with the left 11190 // expression is sequenced before every value computation and side 11191 // effect associated with the right expression. 11192 SequenceTree::Seq LHS = Tree.allocate(Region); 11193 SequenceTree::Seq RHS = Tree.allocate(Region); 11194 SequenceTree::Seq OldRegion = Region; 11195 11196 { 11197 SequencedSubexpression SeqLHS(*this); 11198 Region = LHS; 11199 Visit(BO->getLHS()); 11200 } 11201 11202 Region = RHS; 11203 Visit(BO->getRHS()); 11204 11205 Region = OldRegion; 11206 11207 // Forget that LHS and RHS are sequenced. They are both unsequenced 11208 // with respect to other stuff. 11209 Tree.merge(LHS); 11210 Tree.merge(RHS); 11211 } 11212 11213 void VisitBinAssign(BinaryOperator *BO) { 11214 // The modification is sequenced after the value computation of the LHS 11215 // and RHS, so check it before inspecting the operands and update the 11216 // map afterwards. 11217 Object O = getObject(BO->getLHS(), true); 11218 if (!O) 11219 return VisitExpr(BO); 11220 11221 notePreMod(O, BO); 11222 11223 // C++11 [expr.ass]p7: 11224 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11225 // only once. 11226 // 11227 // Therefore, for a compound assignment operator, O is considered used 11228 // everywhere except within the evaluation of E1 itself. 11229 if (isa<CompoundAssignOperator>(BO)) 11230 notePreUse(O, BO); 11231 11232 Visit(BO->getLHS()); 11233 11234 if (isa<CompoundAssignOperator>(BO)) 11235 notePostUse(O, BO); 11236 11237 Visit(BO->getRHS()); 11238 11239 // C++11 [expr.ass]p1: 11240 // the assignment is sequenced [...] before the value computation of the 11241 // assignment expression. 11242 // C11 6.5.16/3 has no such rule. 11243 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11244 : UK_ModAsSideEffect); 11245 } 11246 11247 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11248 VisitBinAssign(CAO); 11249 } 11250 11251 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11252 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11253 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11254 Object O = getObject(UO->getSubExpr(), true); 11255 if (!O) 11256 return VisitExpr(UO); 11257 11258 notePreMod(O, UO); 11259 Visit(UO->getSubExpr()); 11260 // C++11 [expr.pre.incr]p1: 11261 // the expression ++x is equivalent to x+=1 11262 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11263 : UK_ModAsSideEffect); 11264 } 11265 11266 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11267 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11268 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11269 Object O = getObject(UO->getSubExpr(), true); 11270 if (!O) 11271 return VisitExpr(UO); 11272 11273 notePreMod(O, UO); 11274 Visit(UO->getSubExpr()); 11275 notePostMod(O, UO, UK_ModAsSideEffect); 11276 } 11277 11278 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11279 void VisitBinLOr(BinaryOperator *BO) { 11280 // The side-effects of the LHS of an '&&' are sequenced before the 11281 // value computation of the RHS, and hence before the value computation 11282 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11283 // as if they were unconditionally sequenced. 11284 EvaluationTracker Eval(*this); 11285 { 11286 SequencedSubexpression Sequenced(*this); 11287 Visit(BO->getLHS()); 11288 } 11289 11290 bool Result; 11291 if (Eval.evaluate(BO->getLHS(), Result)) { 11292 if (!Result) 11293 Visit(BO->getRHS()); 11294 } else { 11295 // Check for unsequenced operations in the RHS, treating it as an 11296 // entirely separate evaluation. 11297 // 11298 // FIXME: If there are operations in the RHS which are unsequenced 11299 // with respect to operations outside the RHS, and those operations 11300 // are unconditionally evaluated, diagnose them. 11301 WorkList.push_back(BO->getRHS()); 11302 } 11303 } 11304 void VisitBinLAnd(BinaryOperator *BO) { 11305 EvaluationTracker Eval(*this); 11306 { 11307 SequencedSubexpression Sequenced(*this); 11308 Visit(BO->getLHS()); 11309 } 11310 11311 bool Result; 11312 if (Eval.evaluate(BO->getLHS(), Result)) { 11313 if (Result) 11314 Visit(BO->getRHS()); 11315 } else { 11316 WorkList.push_back(BO->getRHS()); 11317 } 11318 } 11319 11320 // Only visit the condition, unless we can be sure which subexpression will 11321 // be chosen. 11322 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11323 EvaluationTracker Eval(*this); 11324 { 11325 SequencedSubexpression Sequenced(*this); 11326 Visit(CO->getCond()); 11327 } 11328 11329 bool Result; 11330 if (Eval.evaluate(CO->getCond(), Result)) 11331 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11332 else { 11333 WorkList.push_back(CO->getTrueExpr()); 11334 WorkList.push_back(CO->getFalseExpr()); 11335 } 11336 } 11337 11338 void VisitCallExpr(CallExpr *CE) { 11339 // C++11 [intro.execution]p15: 11340 // When calling a function [...], every value computation and side effect 11341 // associated with any argument expression, or with the postfix expression 11342 // designating the called function, is sequenced before execution of every 11343 // expression or statement in the body of the function [and thus before 11344 // the value computation of its result]. 11345 SequencedSubexpression Sequenced(*this); 11346 Base::VisitCallExpr(CE); 11347 11348 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11349 } 11350 11351 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11352 // This is a call, so all subexpressions are sequenced before the result. 11353 SequencedSubexpression Sequenced(*this); 11354 11355 if (!CCE->isListInitialization()) 11356 return VisitExpr(CCE); 11357 11358 // In C++11, list initializations are sequenced. 11359 SmallVector<SequenceTree::Seq, 32> Elts; 11360 SequenceTree::Seq Parent = Region; 11361 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11362 E = CCE->arg_end(); 11363 I != E; ++I) { 11364 Region = Tree.allocate(Parent); 11365 Elts.push_back(Region); 11366 Visit(*I); 11367 } 11368 11369 // Forget that the initializers are sequenced. 11370 Region = Parent; 11371 for (unsigned I = 0; I < Elts.size(); ++I) 11372 Tree.merge(Elts[I]); 11373 } 11374 11375 void VisitInitListExpr(InitListExpr *ILE) { 11376 if (!SemaRef.getLangOpts().CPlusPlus11) 11377 return VisitExpr(ILE); 11378 11379 // In C++11, list initializations are sequenced. 11380 SmallVector<SequenceTree::Seq, 32> Elts; 11381 SequenceTree::Seq Parent = Region; 11382 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11383 Expr *E = ILE->getInit(I); 11384 if (!E) continue; 11385 Region = Tree.allocate(Parent); 11386 Elts.push_back(Region); 11387 Visit(E); 11388 } 11389 11390 // Forget that the initializers are sequenced. 11391 Region = Parent; 11392 for (unsigned I = 0; I < Elts.size(); ++I) 11393 Tree.merge(Elts[I]); 11394 } 11395 }; 11396 11397 } // namespace 11398 11399 void Sema::CheckUnsequencedOperations(Expr *E) { 11400 SmallVector<Expr *, 8> WorkList; 11401 WorkList.push_back(E); 11402 while (!WorkList.empty()) { 11403 Expr *Item = WorkList.pop_back_val(); 11404 SequenceChecker(*this, Item, WorkList); 11405 } 11406 } 11407 11408 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11409 bool IsConstexpr) { 11410 CheckImplicitConversions(E, CheckLoc); 11411 if (!E->isInstantiationDependent()) 11412 CheckUnsequencedOperations(E); 11413 if (!IsConstexpr && !E->isValueDependent()) 11414 CheckForIntOverflow(E); 11415 DiagnoseMisalignedMembers(); 11416 } 11417 11418 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11419 FieldDecl *BitField, 11420 Expr *Init) { 11421 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11422 } 11423 11424 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11425 SourceLocation Loc) { 11426 if (!PType->isVariablyModifiedType()) 11427 return; 11428 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11429 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11430 return; 11431 } 11432 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 11433 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 11434 return; 11435 } 11436 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 11437 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 11438 return; 11439 } 11440 11441 const ArrayType *AT = S.Context.getAsArrayType(PType); 11442 if (!AT) 11443 return; 11444 11445 if (AT->getSizeModifier() != ArrayType::Star) { 11446 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 11447 return; 11448 } 11449 11450 S.Diag(Loc, diag::err_array_star_in_function_definition); 11451 } 11452 11453 /// CheckParmsForFunctionDef - Check that the parameters of the given 11454 /// function are appropriate for the definition of a function. This 11455 /// takes care of any checks that cannot be performed on the 11456 /// declaration itself, e.g., that the types of each of the function 11457 /// parameters are complete. 11458 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 11459 bool CheckParameterNames) { 11460 bool HasInvalidParm = false; 11461 for (ParmVarDecl *Param : Parameters) { 11462 // C99 6.7.5.3p4: the parameters in a parameter type list in a 11463 // function declarator that is part of a function definition of 11464 // that function shall not have incomplete type. 11465 // 11466 // This is also C++ [dcl.fct]p6. 11467 if (!Param->isInvalidDecl() && 11468 RequireCompleteType(Param->getLocation(), Param->getType(), 11469 diag::err_typecheck_decl_incomplete_type)) { 11470 Param->setInvalidDecl(); 11471 HasInvalidParm = true; 11472 } 11473 11474 // C99 6.9.1p5: If the declarator includes a parameter type list, the 11475 // declaration of each parameter shall include an identifier. 11476 if (CheckParameterNames && 11477 Param->getIdentifier() == nullptr && 11478 !Param->isImplicit() && 11479 !getLangOpts().CPlusPlus) 11480 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11481 11482 // C99 6.7.5.3p12: 11483 // If the function declarator is not part of a definition of that 11484 // function, parameters may have incomplete type and may use the [*] 11485 // notation in their sequences of declarator specifiers to specify 11486 // variable length array types. 11487 QualType PType = Param->getOriginalType(); 11488 // FIXME: This diagnostic should point the '[*]' if source-location 11489 // information is added for it. 11490 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 11491 11492 // If the parameter is a c++ class type and it has to be destructed in the 11493 // callee function, declare the destructor so that it can be called by the 11494 // callee function. Do not perform any direct access check on the dtor here. 11495 if (!Param->isInvalidDecl()) { 11496 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 11497 if (!ClassDecl->isInvalidDecl() && 11498 !ClassDecl->hasIrrelevantDestructor() && 11499 !ClassDecl->isDependentContext() && 11500 ClassDecl->isParamDestroyedInCallee()) { 11501 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11502 MarkFunctionReferenced(Param->getLocation(), Destructor); 11503 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 11504 } 11505 } 11506 } 11507 11508 // Parameters with the pass_object_size attribute only need to be marked 11509 // constant at function definitions. Because we lack information about 11510 // whether we're on a declaration or definition when we're instantiating the 11511 // attribute, we need to check for constness here. 11512 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 11513 if (!Param->getType().isConstQualified()) 11514 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 11515 << Attr->getSpelling() << 1; 11516 } 11517 11518 return HasInvalidParm; 11519 } 11520 11521 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 11522 /// or MemberExpr. 11523 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 11524 ASTContext &Context) { 11525 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 11526 return Context.getDeclAlign(DRE->getDecl()); 11527 11528 if (const auto *ME = dyn_cast<MemberExpr>(E)) 11529 return Context.getDeclAlign(ME->getMemberDecl()); 11530 11531 return TypeAlign; 11532 } 11533 11534 /// CheckCastAlign - Implements -Wcast-align, which warns when a 11535 /// pointer cast increases the alignment requirements. 11536 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 11537 // This is actually a lot of work to potentially be doing on every 11538 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 11539 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 11540 return; 11541 11542 // Ignore dependent types. 11543 if (T->isDependentType() || Op->getType()->isDependentType()) 11544 return; 11545 11546 // Require that the destination be a pointer type. 11547 const PointerType *DestPtr = T->getAs<PointerType>(); 11548 if (!DestPtr) return; 11549 11550 // If the destination has alignment 1, we're done. 11551 QualType DestPointee = DestPtr->getPointeeType(); 11552 if (DestPointee->isIncompleteType()) return; 11553 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 11554 if (DestAlign.isOne()) return; 11555 11556 // Require that the source be a pointer type. 11557 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 11558 if (!SrcPtr) return; 11559 QualType SrcPointee = SrcPtr->getPointeeType(); 11560 11561 // Whitelist casts from cv void*. We already implicitly 11562 // whitelisted casts to cv void*, since they have alignment 1. 11563 // Also whitelist casts involving incomplete types, which implicitly 11564 // includes 'void'. 11565 if (SrcPointee->isIncompleteType()) return; 11566 11567 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 11568 11569 if (auto *CE = dyn_cast<CastExpr>(Op)) { 11570 if (CE->getCastKind() == CK_ArrayToPointerDecay) 11571 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 11572 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 11573 if (UO->getOpcode() == UO_AddrOf) 11574 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 11575 } 11576 11577 if (SrcAlign >= DestAlign) return; 11578 11579 Diag(TRange.getBegin(), diag::warn_cast_align) 11580 << Op->getType() << T 11581 << static_cast<unsigned>(SrcAlign.getQuantity()) 11582 << static_cast<unsigned>(DestAlign.getQuantity()) 11583 << TRange << Op->getSourceRange(); 11584 } 11585 11586 /// Check whether this array fits the idiom of a size-one tail padded 11587 /// array member of a struct. 11588 /// 11589 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 11590 /// commonly used to emulate flexible arrays in C89 code. 11591 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 11592 const NamedDecl *ND) { 11593 if (Size != 1 || !ND) return false; 11594 11595 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 11596 if (!FD) return false; 11597 11598 // Don't consider sizes resulting from macro expansions or template argument 11599 // substitution to form C89 tail-padded arrays. 11600 11601 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 11602 while (TInfo) { 11603 TypeLoc TL = TInfo->getTypeLoc(); 11604 // Look through typedefs. 11605 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 11606 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 11607 TInfo = TDL->getTypeSourceInfo(); 11608 continue; 11609 } 11610 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 11611 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 11612 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 11613 return false; 11614 } 11615 break; 11616 } 11617 11618 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 11619 if (!RD) return false; 11620 if (RD->isUnion()) return false; 11621 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11622 if (!CRD->isStandardLayout()) return false; 11623 } 11624 11625 // See if this is the last field decl in the record. 11626 const Decl *D = FD; 11627 while ((D = D->getNextDeclInContext())) 11628 if (isa<FieldDecl>(D)) 11629 return false; 11630 return true; 11631 } 11632 11633 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 11634 const ArraySubscriptExpr *ASE, 11635 bool AllowOnePastEnd, bool IndexNegated) { 11636 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 11637 if (IndexExpr->isValueDependent()) 11638 return; 11639 11640 const Type *EffectiveType = 11641 BaseExpr->getType()->getPointeeOrArrayElementType(); 11642 BaseExpr = BaseExpr->IgnoreParenCasts(); 11643 const ConstantArrayType *ArrayTy = 11644 Context.getAsConstantArrayType(BaseExpr->getType()); 11645 if (!ArrayTy) 11646 return; 11647 11648 llvm::APSInt index; 11649 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 11650 return; 11651 if (IndexNegated) 11652 index = -index; 11653 11654 const NamedDecl *ND = nullptr; 11655 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11656 ND = DRE->getDecl(); 11657 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11658 ND = ME->getMemberDecl(); 11659 11660 if (index.isUnsigned() || !index.isNegative()) { 11661 llvm::APInt size = ArrayTy->getSize(); 11662 if (!size.isStrictlyPositive()) 11663 return; 11664 11665 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 11666 if (BaseType != EffectiveType) { 11667 // Make sure we're comparing apples to apples when comparing index to size 11668 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 11669 uint64_t array_typesize = Context.getTypeSize(BaseType); 11670 // Handle ptrarith_typesize being zero, such as when casting to void* 11671 if (!ptrarith_typesize) ptrarith_typesize = 1; 11672 if (ptrarith_typesize != array_typesize) { 11673 // There's a cast to a different size type involved 11674 uint64_t ratio = array_typesize / ptrarith_typesize; 11675 // TODO: Be smarter about handling cases where array_typesize is not a 11676 // multiple of ptrarith_typesize 11677 if (ptrarith_typesize * ratio == array_typesize) 11678 size *= llvm::APInt(size.getBitWidth(), ratio); 11679 } 11680 } 11681 11682 if (size.getBitWidth() > index.getBitWidth()) 11683 index = index.zext(size.getBitWidth()); 11684 else if (size.getBitWidth() < index.getBitWidth()) 11685 size = size.zext(index.getBitWidth()); 11686 11687 // For array subscripting the index must be less than size, but for pointer 11688 // arithmetic also allow the index (offset) to be equal to size since 11689 // computing the next address after the end of the array is legal and 11690 // commonly done e.g. in C++ iterators and range-based for loops. 11691 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 11692 return; 11693 11694 // Also don't warn for arrays of size 1 which are members of some 11695 // structure. These are often used to approximate flexible arrays in C89 11696 // code. 11697 if (IsTailPaddedMemberArray(*this, size, ND)) 11698 return; 11699 11700 // Suppress the warning if the subscript expression (as identified by the 11701 // ']' location) and the index expression are both from macro expansions 11702 // within a system header. 11703 if (ASE) { 11704 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 11705 ASE->getRBracketLoc()); 11706 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 11707 SourceLocation IndexLoc = SourceMgr.getSpellingLoc( 11708 IndexExpr->getLocStart()); 11709 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 11710 return; 11711 } 11712 } 11713 11714 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 11715 if (ASE) 11716 DiagID = diag::warn_array_index_exceeds_bounds; 11717 11718 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11719 PDiag(DiagID) << index.toString(10, true) 11720 << size.toString(10, true) 11721 << (unsigned)size.getLimitedValue(~0U) 11722 << IndexExpr->getSourceRange()); 11723 } else { 11724 unsigned DiagID = diag::warn_array_index_precedes_bounds; 11725 if (!ASE) { 11726 DiagID = diag::warn_ptr_arith_precedes_bounds; 11727 if (index.isNegative()) index = -index; 11728 } 11729 11730 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr, 11731 PDiag(DiagID) << index.toString(10, true) 11732 << IndexExpr->getSourceRange()); 11733 } 11734 11735 if (!ND) { 11736 // Try harder to find a NamedDecl to point at in the note. 11737 while (const ArraySubscriptExpr *ASE = 11738 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 11739 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 11740 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 11741 ND = DRE->getDecl(); 11742 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 11743 ND = ME->getMemberDecl(); 11744 } 11745 11746 if (ND) 11747 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr, 11748 PDiag(diag::note_array_index_out_of_bounds) 11749 << ND->getDeclName()); 11750 } 11751 11752 void Sema::CheckArrayAccess(const Expr *expr) { 11753 int AllowOnePastEnd = 0; 11754 while (expr) { 11755 expr = expr->IgnoreParenImpCasts(); 11756 switch (expr->getStmtClass()) { 11757 case Stmt::ArraySubscriptExprClass: { 11758 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 11759 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 11760 AllowOnePastEnd > 0); 11761 expr = ASE->getBase(); 11762 break; 11763 } 11764 case Stmt::MemberExprClass: { 11765 expr = cast<MemberExpr>(expr)->getBase(); 11766 break; 11767 } 11768 case Stmt::OMPArraySectionExprClass: { 11769 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 11770 if (ASE->getLowerBound()) 11771 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 11772 /*ASE=*/nullptr, AllowOnePastEnd > 0); 11773 return; 11774 } 11775 case Stmt::UnaryOperatorClass: { 11776 // Only unwrap the * and & unary operators 11777 const UnaryOperator *UO = cast<UnaryOperator>(expr); 11778 expr = UO->getSubExpr(); 11779 switch (UO->getOpcode()) { 11780 case UO_AddrOf: 11781 AllowOnePastEnd++; 11782 break; 11783 case UO_Deref: 11784 AllowOnePastEnd--; 11785 break; 11786 default: 11787 return; 11788 } 11789 break; 11790 } 11791 case Stmt::ConditionalOperatorClass: { 11792 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 11793 if (const Expr *lhs = cond->getLHS()) 11794 CheckArrayAccess(lhs); 11795 if (const Expr *rhs = cond->getRHS()) 11796 CheckArrayAccess(rhs); 11797 return; 11798 } 11799 case Stmt::CXXOperatorCallExprClass: { 11800 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 11801 for (const auto *Arg : OCE->arguments()) 11802 CheckArrayAccess(Arg); 11803 return; 11804 } 11805 default: 11806 return; 11807 } 11808 } 11809 } 11810 11811 //===--- CHECK: Objective-C retain cycles ----------------------------------// 11812 11813 namespace { 11814 11815 struct RetainCycleOwner { 11816 VarDecl *Variable = nullptr; 11817 SourceRange Range; 11818 SourceLocation Loc; 11819 bool Indirect = false; 11820 11821 RetainCycleOwner() = default; 11822 11823 void setLocsFrom(Expr *e) { 11824 Loc = e->getExprLoc(); 11825 Range = e->getSourceRange(); 11826 } 11827 }; 11828 11829 } // namespace 11830 11831 /// Consider whether capturing the given variable can possibly lead to 11832 /// a retain cycle. 11833 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 11834 // In ARC, it's captured strongly iff the variable has __strong 11835 // lifetime. In MRR, it's captured strongly if the variable is 11836 // __block and has an appropriate type. 11837 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11838 return false; 11839 11840 owner.Variable = var; 11841 if (ref) 11842 owner.setLocsFrom(ref); 11843 return true; 11844 } 11845 11846 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 11847 while (true) { 11848 e = e->IgnoreParens(); 11849 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 11850 switch (cast->getCastKind()) { 11851 case CK_BitCast: 11852 case CK_LValueBitCast: 11853 case CK_LValueToRValue: 11854 case CK_ARCReclaimReturnedObject: 11855 e = cast->getSubExpr(); 11856 continue; 11857 11858 default: 11859 return false; 11860 } 11861 } 11862 11863 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 11864 ObjCIvarDecl *ivar = ref->getDecl(); 11865 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 11866 return false; 11867 11868 // Try to find a retain cycle in the base. 11869 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 11870 return false; 11871 11872 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 11873 owner.Indirect = true; 11874 return true; 11875 } 11876 11877 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 11878 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 11879 if (!var) return false; 11880 return considerVariable(var, ref, owner); 11881 } 11882 11883 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 11884 if (member->isArrow()) return false; 11885 11886 // Don't count this as an indirect ownership. 11887 e = member->getBase(); 11888 continue; 11889 } 11890 11891 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 11892 // Only pay attention to pseudo-objects on property references. 11893 ObjCPropertyRefExpr *pre 11894 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 11895 ->IgnoreParens()); 11896 if (!pre) return false; 11897 if (pre->isImplicitProperty()) return false; 11898 ObjCPropertyDecl *property = pre->getExplicitProperty(); 11899 if (!property->isRetaining() && 11900 !(property->getPropertyIvarDecl() && 11901 property->getPropertyIvarDecl()->getType() 11902 .getObjCLifetime() == Qualifiers::OCL_Strong)) 11903 return false; 11904 11905 owner.Indirect = true; 11906 if (pre->isSuperReceiver()) { 11907 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 11908 if (!owner.Variable) 11909 return false; 11910 owner.Loc = pre->getLocation(); 11911 owner.Range = pre->getSourceRange(); 11912 return true; 11913 } 11914 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 11915 ->getSourceExpr()); 11916 continue; 11917 } 11918 11919 // Array ivars? 11920 11921 return false; 11922 } 11923 } 11924 11925 namespace { 11926 11927 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 11928 ASTContext &Context; 11929 VarDecl *Variable; 11930 Expr *Capturer = nullptr; 11931 bool VarWillBeReased = false; 11932 11933 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 11934 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 11935 Context(Context), Variable(variable) {} 11936 11937 void VisitDeclRefExpr(DeclRefExpr *ref) { 11938 if (ref->getDecl() == Variable && !Capturer) 11939 Capturer = ref; 11940 } 11941 11942 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 11943 if (Capturer) return; 11944 Visit(ref->getBase()); 11945 if (Capturer && ref->isFreeIvar()) 11946 Capturer = ref; 11947 } 11948 11949 void VisitBlockExpr(BlockExpr *block) { 11950 // Look inside nested blocks 11951 if (block->getBlockDecl()->capturesVariable(Variable)) 11952 Visit(block->getBlockDecl()->getBody()); 11953 } 11954 11955 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 11956 if (Capturer) return; 11957 if (OVE->getSourceExpr()) 11958 Visit(OVE->getSourceExpr()); 11959 } 11960 11961 void VisitBinaryOperator(BinaryOperator *BinOp) { 11962 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 11963 return; 11964 Expr *LHS = BinOp->getLHS(); 11965 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 11966 if (DRE->getDecl() != Variable) 11967 return; 11968 if (Expr *RHS = BinOp->getRHS()) { 11969 RHS = RHS->IgnoreParenCasts(); 11970 llvm::APSInt Value; 11971 VarWillBeReased = 11972 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 11973 } 11974 } 11975 } 11976 }; 11977 11978 } // namespace 11979 11980 /// Check whether the given argument is a block which captures a 11981 /// variable. 11982 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 11983 assert(owner.Variable && owner.Loc.isValid()); 11984 11985 e = e->IgnoreParenCasts(); 11986 11987 // Look through [^{...} copy] and Block_copy(^{...}). 11988 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 11989 Selector Cmd = ME->getSelector(); 11990 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 11991 e = ME->getInstanceReceiver(); 11992 if (!e) 11993 return nullptr; 11994 e = e->IgnoreParenCasts(); 11995 } 11996 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 11997 if (CE->getNumArgs() == 1) { 11998 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 11999 if (Fn) { 12000 const IdentifierInfo *FnI = Fn->getIdentifier(); 12001 if (FnI && FnI->isStr("_Block_copy")) { 12002 e = CE->getArg(0)->IgnoreParenCasts(); 12003 } 12004 } 12005 } 12006 } 12007 12008 BlockExpr *block = dyn_cast<BlockExpr>(e); 12009 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12010 return nullptr; 12011 12012 FindCaptureVisitor visitor(S.Context, owner.Variable); 12013 visitor.Visit(block->getBlockDecl()->getBody()); 12014 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12015 } 12016 12017 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12018 RetainCycleOwner &owner) { 12019 assert(capturer); 12020 assert(owner.Variable && owner.Loc.isValid()); 12021 12022 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12023 << owner.Variable << capturer->getSourceRange(); 12024 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12025 << owner.Indirect << owner.Range; 12026 } 12027 12028 /// Check for a keyword selector that starts with the word 'add' or 12029 /// 'set'. 12030 static bool isSetterLikeSelector(Selector sel) { 12031 if (sel.isUnarySelector()) return false; 12032 12033 StringRef str = sel.getNameForSlot(0); 12034 while (!str.empty() && str.front() == '_') str = str.substr(1); 12035 if (str.startswith("set")) 12036 str = str.substr(3); 12037 else if (str.startswith("add")) { 12038 // Specially whitelist 'addOperationWithBlock:'. 12039 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12040 return false; 12041 str = str.substr(3); 12042 } 12043 else 12044 return false; 12045 12046 if (str.empty()) return true; 12047 return !isLowercase(str.front()); 12048 } 12049 12050 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12051 ObjCMessageExpr *Message) { 12052 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12053 Message->getReceiverInterface(), 12054 NSAPI::ClassId_NSMutableArray); 12055 if (!IsMutableArray) { 12056 return None; 12057 } 12058 12059 Selector Sel = Message->getSelector(); 12060 12061 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12062 S.NSAPIObj->getNSArrayMethodKind(Sel); 12063 if (!MKOpt) { 12064 return None; 12065 } 12066 12067 NSAPI::NSArrayMethodKind MK = *MKOpt; 12068 12069 switch (MK) { 12070 case NSAPI::NSMutableArr_addObject: 12071 case NSAPI::NSMutableArr_insertObjectAtIndex: 12072 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12073 return 0; 12074 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12075 return 1; 12076 12077 default: 12078 return None; 12079 } 12080 12081 return None; 12082 } 12083 12084 static 12085 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12086 ObjCMessageExpr *Message) { 12087 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12088 Message->getReceiverInterface(), 12089 NSAPI::ClassId_NSMutableDictionary); 12090 if (!IsMutableDictionary) { 12091 return None; 12092 } 12093 12094 Selector Sel = Message->getSelector(); 12095 12096 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12097 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12098 if (!MKOpt) { 12099 return None; 12100 } 12101 12102 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12103 12104 switch (MK) { 12105 case NSAPI::NSMutableDict_setObjectForKey: 12106 case NSAPI::NSMutableDict_setValueForKey: 12107 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12108 return 0; 12109 12110 default: 12111 return None; 12112 } 12113 12114 return None; 12115 } 12116 12117 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12118 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12119 Message->getReceiverInterface(), 12120 NSAPI::ClassId_NSMutableSet); 12121 12122 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12123 Message->getReceiverInterface(), 12124 NSAPI::ClassId_NSMutableOrderedSet); 12125 if (!IsMutableSet && !IsMutableOrderedSet) { 12126 return None; 12127 } 12128 12129 Selector Sel = Message->getSelector(); 12130 12131 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12132 if (!MKOpt) { 12133 return None; 12134 } 12135 12136 NSAPI::NSSetMethodKind MK = *MKOpt; 12137 12138 switch (MK) { 12139 case NSAPI::NSMutableSet_addObject: 12140 case NSAPI::NSOrderedSet_setObjectAtIndex: 12141 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12142 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12143 return 0; 12144 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12145 return 1; 12146 } 12147 12148 return None; 12149 } 12150 12151 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12152 if (!Message->isInstanceMessage()) { 12153 return; 12154 } 12155 12156 Optional<int> ArgOpt; 12157 12158 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12159 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12160 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12161 return; 12162 } 12163 12164 int ArgIndex = *ArgOpt; 12165 12166 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12167 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12168 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12169 } 12170 12171 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12172 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12173 if (ArgRE->isObjCSelfExpr()) { 12174 Diag(Message->getSourceRange().getBegin(), 12175 diag::warn_objc_circular_container) 12176 << ArgRE->getDecl() << StringRef("'super'"); 12177 } 12178 } 12179 } else { 12180 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12181 12182 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12183 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12184 } 12185 12186 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12187 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12188 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12189 ValueDecl *Decl = ReceiverRE->getDecl(); 12190 Diag(Message->getSourceRange().getBegin(), 12191 diag::warn_objc_circular_container) 12192 << Decl << Decl; 12193 if (!ArgRE->isObjCSelfExpr()) { 12194 Diag(Decl->getLocation(), 12195 diag::note_objc_circular_container_declared_here) 12196 << Decl; 12197 } 12198 } 12199 } 12200 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12201 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12202 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12203 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12204 Diag(Message->getSourceRange().getBegin(), 12205 diag::warn_objc_circular_container) 12206 << Decl << Decl; 12207 Diag(Decl->getLocation(), 12208 diag::note_objc_circular_container_declared_here) 12209 << Decl; 12210 } 12211 } 12212 } 12213 } 12214 } 12215 12216 /// Check a message send to see if it's likely to cause a retain cycle. 12217 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12218 // Only check instance methods whose selector looks like a setter. 12219 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12220 return; 12221 12222 // Try to find a variable that the receiver is strongly owned by. 12223 RetainCycleOwner owner; 12224 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12225 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12226 return; 12227 } else { 12228 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12229 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12230 owner.Loc = msg->getSuperLoc(); 12231 owner.Range = msg->getSuperLoc(); 12232 } 12233 12234 // Check whether the receiver is captured by any of the arguments. 12235 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12236 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12237 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12238 // noescape blocks should not be retained by the method. 12239 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12240 continue; 12241 return diagnoseRetainCycle(*this, capturer, owner); 12242 } 12243 } 12244 } 12245 12246 /// Check a property assign to see if it's likely to cause a retain cycle. 12247 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12248 RetainCycleOwner owner; 12249 if (!findRetainCycleOwner(*this, receiver, owner)) 12250 return; 12251 12252 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12253 diagnoseRetainCycle(*this, capturer, owner); 12254 } 12255 12256 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12257 RetainCycleOwner Owner; 12258 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12259 return; 12260 12261 // Because we don't have an expression for the variable, we have to set the 12262 // location explicitly here. 12263 Owner.Loc = Var->getLocation(); 12264 Owner.Range = Var->getSourceRange(); 12265 12266 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12267 diagnoseRetainCycle(*this, Capturer, Owner); 12268 } 12269 12270 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12271 Expr *RHS, bool isProperty) { 12272 // Check if RHS is an Objective-C object literal, which also can get 12273 // immediately zapped in a weak reference. Note that we explicitly 12274 // allow ObjCStringLiterals, since those are designed to never really die. 12275 RHS = RHS->IgnoreParenImpCasts(); 12276 12277 // This enum needs to match with the 'select' in 12278 // warn_objc_arc_literal_assign (off-by-1). 12279 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12280 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12281 return false; 12282 12283 S.Diag(Loc, diag::warn_arc_literal_assign) 12284 << (unsigned) Kind 12285 << (isProperty ? 0 : 1) 12286 << RHS->getSourceRange(); 12287 12288 return true; 12289 } 12290 12291 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12292 Qualifiers::ObjCLifetime LT, 12293 Expr *RHS, bool isProperty) { 12294 // Strip off any implicit cast added to get to the one ARC-specific. 12295 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12296 if (cast->getCastKind() == CK_ARCConsumeObject) { 12297 S.Diag(Loc, diag::warn_arc_retained_assign) 12298 << (LT == Qualifiers::OCL_ExplicitNone) 12299 << (isProperty ? 0 : 1) 12300 << RHS->getSourceRange(); 12301 return true; 12302 } 12303 RHS = cast->getSubExpr(); 12304 } 12305 12306 if (LT == Qualifiers::OCL_Weak && 12307 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12308 return true; 12309 12310 return false; 12311 } 12312 12313 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12314 QualType LHS, Expr *RHS) { 12315 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12316 12317 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12318 return false; 12319 12320 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12321 return true; 12322 12323 return false; 12324 } 12325 12326 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12327 Expr *LHS, Expr *RHS) { 12328 QualType LHSType; 12329 // PropertyRef on LHS type need be directly obtained from 12330 // its declaration as it has a PseudoType. 12331 ObjCPropertyRefExpr *PRE 12332 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12333 if (PRE && !PRE->isImplicitProperty()) { 12334 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12335 if (PD) 12336 LHSType = PD->getType(); 12337 } 12338 12339 if (LHSType.isNull()) 12340 LHSType = LHS->getType(); 12341 12342 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12343 12344 if (LT == Qualifiers::OCL_Weak) { 12345 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12346 getCurFunction()->markSafeWeakUse(LHS); 12347 } 12348 12349 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12350 return; 12351 12352 // FIXME. Check for other life times. 12353 if (LT != Qualifiers::OCL_None) 12354 return; 12355 12356 if (PRE) { 12357 if (PRE->isImplicitProperty()) 12358 return; 12359 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12360 if (!PD) 12361 return; 12362 12363 unsigned Attributes = PD->getPropertyAttributes(); 12364 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12365 // when 'assign' attribute was not explicitly specified 12366 // by user, ignore it and rely on property type itself 12367 // for lifetime info. 12368 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12369 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12370 LHSType->isObjCRetainableType()) 12371 return; 12372 12373 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12374 if (cast->getCastKind() == CK_ARCConsumeObject) { 12375 Diag(Loc, diag::warn_arc_retained_property_assign) 12376 << RHS->getSourceRange(); 12377 return; 12378 } 12379 RHS = cast->getSubExpr(); 12380 } 12381 } 12382 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12383 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12384 return; 12385 } 12386 } 12387 } 12388 12389 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12390 12391 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12392 SourceLocation StmtLoc, 12393 const NullStmt *Body) { 12394 // Do not warn if the body is a macro that expands to nothing, e.g: 12395 // 12396 // #define CALL(x) 12397 // if (condition) 12398 // CALL(0); 12399 if (Body->hasLeadingEmptyMacro()) 12400 return false; 12401 12402 // Get line numbers of statement and body. 12403 bool StmtLineInvalid; 12404 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12405 &StmtLineInvalid); 12406 if (StmtLineInvalid) 12407 return false; 12408 12409 bool BodyLineInvalid; 12410 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12411 &BodyLineInvalid); 12412 if (BodyLineInvalid) 12413 return false; 12414 12415 // Warn if null statement and body are on the same line. 12416 if (StmtLine != BodyLine) 12417 return false; 12418 12419 return true; 12420 } 12421 12422 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12423 const Stmt *Body, 12424 unsigned DiagID) { 12425 // Since this is a syntactic check, don't emit diagnostic for template 12426 // instantiations, this just adds noise. 12427 if (CurrentInstantiationScope) 12428 return; 12429 12430 // The body should be a null statement. 12431 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12432 if (!NBody) 12433 return; 12434 12435 // Do the usual checks. 12436 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12437 return; 12438 12439 Diag(NBody->getSemiLoc(), DiagID); 12440 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12441 } 12442 12443 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 12444 const Stmt *PossibleBody) { 12445 assert(!CurrentInstantiationScope); // Ensured by caller 12446 12447 SourceLocation StmtLoc; 12448 const Stmt *Body; 12449 unsigned DiagID; 12450 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 12451 StmtLoc = FS->getRParenLoc(); 12452 Body = FS->getBody(); 12453 DiagID = diag::warn_empty_for_body; 12454 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 12455 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 12456 Body = WS->getBody(); 12457 DiagID = diag::warn_empty_while_body; 12458 } else 12459 return; // Neither `for' nor `while'. 12460 12461 // The body should be a null statement. 12462 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12463 if (!NBody) 12464 return; 12465 12466 // Skip expensive checks if diagnostic is disabled. 12467 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 12468 return; 12469 12470 // Do the usual checks. 12471 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12472 return; 12473 12474 // `for(...);' and `while(...);' are popular idioms, so in order to keep 12475 // noise level low, emit diagnostics only if for/while is followed by a 12476 // CompoundStmt, e.g.: 12477 // for (int i = 0; i < n; i++); 12478 // { 12479 // a(i); 12480 // } 12481 // or if for/while is followed by a statement with more indentation 12482 // than for/while itself: 12483 // for (int i = 0; i < n; i++); 12484 // a(i); 12485 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 12486 if (!ProbableTypo) { 12487 bool BodyColInvalid; 12488 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 12489 PossibleBody->getLocStart(), 12490 &BodyColInvalid); 12491 if (BodyColInvalid) 12492 return; 12493 12494 bool StmtColInvalid; 12495 unsigned StmtCol = SourceMgr.getPresumedColumnNumber( 12496 S->getLocStart(), 12497 &StmtColInvalid); 12498 if (StmtColInvalid) 12499 return; 12500 12501 if (BodyCol > StmtCol) 12502 ProbableTypo = true; 12503 } 12504 12505 if (ProbableTypo) { 12506 Diag(NBody->getSemiLoc(), DiagID); 12507 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 12508 } 12509 } 12510 12511 //===--- CHECK: Warn on self move with std::move. -------------------------===// 12512 12513 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 12514 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 12515 SourceLocation OpLoc) { 12516 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 12517 return; 12518 12519 if (inTemplateInstantiation()) 12520 return; 12521 12522 // Strip parens and casts away. 12523 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12524 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12525 12526 // Check for a call expression 12527 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 12528 if (!CE || CE->getNumArgs() != 1) 12529 return; 12530 12531 // Check for a call to std::move 12532 if (!CE->isCallToStdMove()) 12533 return; 12534 12535 // Get argument from std::move 12536 RHSExpr = CE->getArg(0); 12537 12538 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12539 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12540 12541 // Two DeclRefExpr's, check that the decls are the same. 12542 if (LHSDeclRef && RHSDeclRef) { 12543 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12544 return; 12545 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12546 RHSDeclRef->getDecl()->getCanonicalDecl()) 12547 return; 12548 12549 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12550 << LHSExpr->getSourceRange() 12551 << RHSExpr->getSourceRange(); 12552 return; 12553 } 12554 12555 // Member variables require a different approach to check for self moves. 12556 // MemberExpr's are the same if every nested MemberExpr refers to the same 12557 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 12558 // the base Expr's are CXXThisExpr's. 12559 const Expr *LHSBase = LHSExpr; 12560 const Expr *RHSBase = RHSExpr; 12561 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 12562 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 12563 if (!LHSME || !RHSME) 12564 return; 12565 12566 while (LHSME && RHSME) { 12567 if (LHSME->getMemberDecl()->getCanonicalDecl() != 12568 RHSME->getMemberDecl()->getCanonicalDecl()) 12569 return; 12570 12571 LHSBase = LHSME->getBase(); 12572 RHSBase = RHSME->getBase(); 12573 LHSME = dyn_cast<MemberExpr>(LHSBase); 12574 RHSME = dyn_cast<MemberExpr>(RHSBase); 12575 } 12576 12577 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 12578 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 12579 if (LHSDeclRef && RHSDeclRef) { 12580 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 12581 return; 12582 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 12583 RHSDeclRef->getDecl()->getCanonicalDecl()) 12584 return; 12585 12586 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12587 << LHSExpr->getSourceRange() 12588 << RHSExpr->getSourceRange(); 12589 return; 12590 } 12591 12592 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 12593 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 12594 << LHSExpr->getSourceRange() 12595 << RHSExpr->getSourceRange(); 12596 } 12597 12598 //===--- Layout compatibility ----------------------------------------------// 12599 12600 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 12601 12602 /// Check if two enumeration types are layout-compatible. 12603 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 12604 // C++11 [dcl.enum] p8: 12605 // Two enumeration types are layout-compatible if they have the same 12606 // underlying type. 12607 return ED1->isComplete() && ED2->isComplete() && 12608 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 12609 } 12610 12611 /// Check if two fields are layout-compatible. 12612 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 12613 FieldDecl *Field2) { 12614 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 12615 return false; 12616 12617 if (Field1->isBitField() != Field2->isBitField()) 12618 return false; 12619 12620 if (Field1->isBitField()) { 12621 // Make sure that the bit-fields are the same length. 12622 unsigned Bits1 = Field1->getBitWidthValue(C); 12623 unsigned Bits2 = Field2->getBitWidthValue(C); 12624 12625 if (Bits1 != Bits2) 12626 return false; 12627 } 12628 12629 return true; 12630 } 12631 12632 /// Check if two standard-layout structs are layout-compatible. 12633 /// (C++11 [class.mem] p17) 12634 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 12635 RecordDecl *RD2) { 12636 // If both records are C++ classes, check that base classes match. 12637 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 12638 // If one of records is a CXXRecordDecl we are in C++ mode, 12639 // thus the other one is a CXXRecordDecl, too. 12640 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 12641 // Check number of base classes. 12642 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 12643 return false; 12644 12645 // Check the base classes. 12646 for (CXXRecordDecl::base_class_const_iterator 12647 Base1 = D1CXX->bases_begin(), 12648 BaseEnd1 = D1CXX->bases_end(), 12649 Base2 = D2CXX->bases_begin(); 12650 Base1 != BaseEnd1; 12651 ++Base1, ++Base2) { 12652 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 12653 return false; 12654 } 12655 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 12656 // If only RD2 is a C++ class, it should have zero base classes. 12657 if (D2CXX->getNumBases() > 0) 12658 return false; 12659 } 12660 12661 // Check the fields. 12662 RecordDecl::field_iterator Field2 = RD2->field_begin(), 12663 Field2End = RD2->field_end(), 12664 Field1 = RD1->field_begin(), 12665 Field1End = RD1->field_end(); 12666 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 12667 if (!isLayoutCompatible(C, *Field1, *Field2)) 12668 return false; 12669 } 12670 if (Field1 != Field1End || Field2 != Field2End) 12671 return false; 12672 12673 return true; 12674 } 12675 12676 /// Check if two standard-layout unions are layout-compatible. 12677 /// (C++11 [class.mem] p18) 12678 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 12679 RecordDecl *RD2) { 12680 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 12681 for (auto *Field2 : RD2->fields()) 12682 UnmatchedFields.insert(Field2); 12683 12684 for (auto *Field1 : RD1->fields()) { 12685 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 12686 I = UnmatchedFields.begin(), 12687 E = UnmatchedFields.end(); 12688 12689 for ( ; I != E; ++I) { 12690 if (isLayoutCompatible(C, Field1, *I)) { 12691 bool Result = UnmatchedFields.erase(*I); 12692 (void) Result; 12693 assert(Result); 12694 break; 12695 } 12696 } 12697 if (I == E) 12698 return false; 12699 } 12700 12701 return UnmatchedFields.empty(); 12702 } 12703 12704 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 12705 RecordDecl *RD2) { 12706 if (RD1->isUnion() != RD2->isUnion()) 12707 return false; 12708 12709 if (RD1->isUnion()) 12710 return isLayoutCompatibleUnion(C, RD1, RD2); 12711 else 12712 return isLayoutCompatibleStruct(C, RD1, RD2); 12713 } 12714 12715 /// Check if two types are layout-compatible in C++11 sense. 12716 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 12717 if (T1.isNull() || T2.isNull()) 12718 return false; 12719 12720 // C++11 [basic.types] p11: 12721 // If two types T1 and T2 are the same type, then T1 and T2 are 12722 // layout-compatible types. 12723 if (C.hasSameType(T1, T2)) 12724 return true; 12725 12726 T1 = T1.getCanonicalType().getUnqualifiedType(); 12727 T2 = T2.getCanonicalType().getUnqualifiedType(); 12728 12729 const Type::TypeClass TC1 = T1->getTypeClass(); 12730 const Type::TypeClass TC2 = T2->getTypeClass(); 12731 12732 if (TC1 != TC2) 12733 return false; 12734 12735 if (TC1 == Type::Enum) { 12736 return isLayoutCompatible(C, 12737 cast<EnumType>(T1)->getDecl(), 12738 cast<EnumType>(T2)->getDecl()); 12739 } else if (TC1 == Type::Record) { 12740 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 12741 return false; 12742 12743 return isLayoutCompatible(C, 12744 cast<RecordType>(T1)->getDecl(), 12745 cast<RecordType>(T2)->getDecl()); 12746 } 12747 12748 return false; 12749 } 12750 12751 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 12752 12753 /// Given a type tag expression find the type tag itself. 12754 /// 12755 /// \param TypeExpr Type tag expression, as it appears in user's code. 12756 /// 12757 /// \param VD Declaration of an identifier that appears in a type tag. 12758 /// 12759 /// \param MagicValue Type tag magic value. 12760 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 12761 const ValueDecl **VD, uint64_t *MagicValue) { 12762 while(true) { 12763 if (!TypeExpr) 12764 return false; 12765 12766 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 12767 12768 switch (TypeExpr->getStmtClass()) { 12769 case Stmt::UnaryOperatorClass: { 12770 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 12771 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 12772 TypeExpr = UO->getSubExpr(); 12773 continue; 12774 } 12775 return false; 12776 } 12777 12778 case Stmt::DeclRefExprClass: { 12779 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 12780 *VD = DRE->getDecl(); 12781 return true; 12782 } 12783 12784 case Stmt::IntegerLiteralClass: { 12785 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 12786 llvm::APInt MagicValueAPInt = IL->getValue(); 12787 if (MagicValueAPInt.getActiveBits() <= 64) { 12788 *MagicValue = MagicValueAPInt.getZExtValue(); 12789 return true; 12790 } else 12791 return false; 12792 } 12793 12794 case Stmt::BinaryConditionalOperatorClass: 12795 case Stmt::ConditionalOperatorClass: { 12796 const AbstractConditionalOperator *ACO = 12797 cast<AbstractConditionalOperator>(TypeExpr); 12798 bool Result; 12799 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 12800 if (Result) 12801 TypeExpr = ACO->getTrueExpr(); 12802 else 12803 TypeExpr = ACO->getFalseExpr(); 12804 continue; 12805 } 12806 return false; 12807 } 12808 12809 case Stmt::BinaryOperatorClass: { 12810 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 12811 if (BO->getOpcode() == BO_Comma) { 12812 TypeExpr = BO->getRHS(); 12813 continue; 12814 } 12815 return false; 12816 } 12817 12818 default: 12819 return false; 12820 } 12821 } 12822 } 12823 12824 /// Retrieve the C type corresponding to type tag TypeExpr. 12825 /// 12826 /// \param TypeExpr Expression that specifies a type tag. 12827 /// 12828 /// \param MagicValues Registered magic values. 12829 /// 12830 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 12831 /// kind. 12832 /// 12833 /// \param TypeInfo Information about the corresponding C type. 12834 /// 12835 /// \returns true if the corresponding C type was found. 12836 static bool GetMatchingCType( 12837 const IdentifierInfo *ArgumentKind, 12838 const Expr *TypeExpr, const ASTContext &Ctx, 12839 const llvm::DenseMap<Sema::TypeTagMagicValue, 12840 Sema::TypeTagData> *MagicValues, 12841 bool &FoundWrongKind, 12842 Sema::TypeTagData &TypeInfo) { 12843 FoundWrongKind = false; 12844 12845 // Variable declaration that has type_tag_for_datatype attribute. 12846 const ValueDecl *VD = nullptr; 12847 12848 uint64_t MagicValue; 12849 12850 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 12851 return false; 12852 12853 if (VD) { 12854 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 12855 if (I->getArgumentKind() != ArgumentKind) { 12856 FoundWrongKind = true; 12857 return false; 12858 } 12859 TypeInfo.Type = I->getMatchingCType(); 12860 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 12861 TypeInfo.MustBeNull = I->getMustBeNull(); 12862 return true; 12863 } 12864 return false; 12865 } 12866 12867 if (!MagicValues) 12868 return false; 12869 12870 llvm::DenseMap<Sema::TypeTagMagicValue, 12871 Sema::TypeTagData>::const_iterator I = 12872 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 12873 if (I == MagicValues->end()) 12874 return false; 12875 12876 TypeInfo = I->second; 12877 return true; 12878 } 12879 12880 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12881 uint64_t MagicValue, QualType Type, 12882 bool LayoutCompatible, 12883 bool MustBeNull) { 12884 if (!TypeTagForDatatypeMagicValues) 12885 TypeTagForDatatypeMagicValues.reset( 12886 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 12887 12888 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 12889 (*TypeTagForDatatypeMagicValues)[Magic] = 12890 TypeTagData(Type, LayoutCompatible, MustBeNull); 12891 } 12892 12893 static bool IsSameCharType(QualType T1, QualType T2) { 12894 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 12895 if (!BT1) 12896 return false; 12897 12898 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 12899 if (!BT2) 12900 return false; 12901 12902 BuiltinType::Kind T1Kind = BT1->getKind(); 12903 BuiltinType::Kind T2Kind = BT2->getKind(); 12904 12905 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 12906 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 12907 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 12908 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 12909 } 12910 12911 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12912 const ArrayRef<const Expr *> ExprArgs, 12913 SourceLocation CallSiteLoc) { 12914 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 12915 bool IsPointerAttr = Attr->getIsPointer(); 12916 12917 // Retrieve the argument representing the 'type_tag'. 12918 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 12919 if (TypeTagIdxAST >= ExprArgs.size()) { 12920 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12921 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 12922 return; 12923 } 12924 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 12925 bool FoundWrongKind; 12926 TypeTagData TypeInfo; 12927 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 12928 TypeTagForDatatypeMagicValues.get(), 12929 FoundWrongKind, TypeInfo)) { 12930 if (FoundWrongKind) 12931 Diag(TypeTagExpr->getExprLoc(), 12932 diag::warn_type_tag_for_datatype_wrong_kind) 12933 << TypeTagExpr->getSourceRange(); 12934 return; 12935 } 12936 12937 // Retrieve the argument representing the 'arg_idx'. 12938 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 12939 if (ArgumentIdxAST >= ExprArgs.size()) { 12940 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 12941 << 1 << Attr->getArgumentIdx().getSourceIndex(); 12942 return; 12943 } 12944 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 12945 if (IsPointerAttr) { 12946 // Skip implicit cast of pointer to `void *' (as a function argument). 12947 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 12948 if (ICE->getType()->isVoidPointerType() && 12949 ICE->getCastKind() == CK_BitCast) 12950 ArgumentExpr = ICE->getSubExpr(); 12951 } 12952 QualType ArgumentType = ArgumentExpr->getType(); 12953 12954 // Passing a `void*' pointer shouldn't trigger a warning. 12955 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 12956 return; 12957 12958 if (TypeInfo.MustBeNull) { 12959 // Type tag with matching void type requires a null pointer. 12960 if (!ArgumentExpr->isNullPointerConstant(Context, 12961 Expr::NPC_ValueDependentIsNotNull)) { 12962 Diag(ArgumentExpr->getExprLoc(), 12963 diag::warn_type_safety_null_pointer_required) 12964 << ArgumentKind->getName() 12965 << ArgumentExpr->getSourceRange() 12966 << TypeTagExpr->getSourceRange(); 12967 } 12968 return; 12969 } 12970 12971 QualType RequiredType = TypeInfo.Type; 12972 if (IsPointerAttr) 12973 RequiredType = Context.getPointerType(RequiredType); 12974 12975 bool mismatch = false; 12976 if (!TypeInfo.LayoutCompatible) { 12977 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 12978 12979 // C++11 [basic.fundamental] p1: 12980 // Plain char, signed char, and unsigned char are three distinct types. 12981 // 12982 // But we treat plain `char' as equivalent to `signed char' or `unsigned 12983 // char' depending on the current char signedness mode. 12984 if (mismatch) 12985 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 12986 RequiredType->getPointeeType())) || 12987 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 12988 mismatch = false; 12989 } else 12990 if (IsPointerAttr) 12991 mismatch = !isLayoutCompatible(Context, 12992 ArgumentType->getPointeeType(), 12993 RequiredType->getPointeeType()); 12994 else 12995 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 12996 12997 if (mismatch) 12998 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 12999 << ArgumentType << ArgumentKind 13000 << TypeInfo.LayoutCompatible << RequiredType 13001 << ArgumentExpr->getSourceRange() 13002 << TypeTagExpr->getSourceRange(); 13003 } 13004 13005 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13006 CharUnits Alignment) { 13007 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13008 } 13009 13010 void Sema::DiagnoseMisalignedMembers() { 13011 for (MisalignedMember &m : MisalignedMembers) { 13012 const NamedDecl *ND = m.RD; 13013 if (ND->getName().empty()) { 13014 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13015 ND = TD; 13016 } 13017 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member) 13018 << m.MD << ND << m.E->getSourceRange(); 13019 } 13020 MisalignedMembers.clear(); 13021 } 13022 13023 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13024 E = E->IgnoreParens(); 13025 if (!T->isPointerType() && !T->isIntegerType()) 13026 return; 13027 if (isa<UnaryOperator>(E) && 13028 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13029 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13030 if (isa<MemberExpr>(Op)) { 13031 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13032 MisalignedMember(Op)); 13033 if (MA != MisalignedMembers.end() && 13034 (T->isIntegerType() || 13035 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13036 Context.getTypeAlignInChars( 13037 T->getPointeeType()) <= MA->Alignment)))) 13038 MisalignedMembers.erase(MA); 13039 } 13040 } 13041 } 13042 13043 void Sema::RefersToMemberWithReducedAlignment( 13044 Expr *E, 13045 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13046 Action) { 13047 const auto *ME = dyn_cast<MemberExpr>(E); 13048 if (!ME) 13049 return; 13050 13051 // No need to check expressions with an __unaligned-qualified type. 13052 if (E->getType().getQualifiers().hasUnaligned()) 13053 return; 13054 13055 // For a chain of MemberExpr like "a.b.c.d" this list 13056 // will keep FieldDecl's like [d, c, b]. 13057 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13058 const MemberExpr *TopME = nullptr; 13059 bool AnyIsPacked = false; 13060 do { 13061 QualType BaseType = ME->getBase()->getType(); 13062 if (ME->isArrow()) 13063 BaseType = BaseType->getPointeeType(); 13064 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13065 if (RD->isInvalidDecl()) 13066 return; 13067 13068 ValueDecl *MD = ME->getMemberDecl(); 13069 auto *FD = dyn_cast<FieldDecl>(MD); 13070 // We do not care about non-data members. 13071 if (!FD || FD->isInvalidDecl()) 13072 return; 13073 13074 AnyIsPacked = 13075 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13076 ReverseMemberChain.push_back(FD); 13077 13078 TopME = ME; 13079 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13080 } while (ME); 13081 assert(TopME && "We did not compute a topmost MemberExpr!"); 13082 13083 // Not the scope of this diagnostic. 13084 if (!AnyIsPacked) 13085 return; 13086 13087 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13088 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13089 // TODO: The innermost base of the member expression may be too complicated. 13090 // For now, just disregard these cases. This is left for future 13091 // improvement. 13092 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13093 return; 13094 13095 // Alignment expected by the whole expression. 13096 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13097 13098 // No need to do anything else with this case. 13099 if (ExpectedAlignment.isOne()) 13100 return; 13101 13102 // Synthesize offset of the whole access. 13103 CharUnits Offset; 13104 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13105 I++) { 13106 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13107 } 13108 13109 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13110 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13111 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13112 13113 // The base expression of the innermost MemberExpr may give 13114 // stronger guarantees than the class containing the member. 13115 if (DRE && !TopME->isArrow()) { 13116 const ValueDecl *VD = DRE->getDecl(); 13117 if (!VD->getType()->isReferenceType()) 13118 CompleteObjectAlignment = 13119 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13120 } 13121 13122 // Check if the synthesized offset fulfills the alignment. 13123 if (Offset % ExpectedAlignment != 0 || 13124 // It may fulfill the offset it but the effective alignment may still be 13125 // lower than the expected expression alignment. 13126 CompleteObjectAlignment < ExpectedAlignment) { 13127 // If this happens, we want to determine a sensible culprit of this. 13128 // Intuitively, watching the chain of member expressions from right to 13129 // left, we start with the required alignment (as required by the field 13130 // type) but some packed attribute in that chain has reduced the alignment. 13131 // It may happen that another packed structure increases it again. But if 13132 // we are here such increase has not been enough. So pointing the first 13133 // FieldDecl that either is packed or else its RecordDecl is, 13134 // seems reasonable. 13135 FieldDecl *FD = nullptr; 13136 CharUnits Alignment; 13137 for (FieldDecl *FDI : ReverseMemberChain) { 13138 if (FDI->hasAttr<PackedAttr>() || 13139 FDI->getParent()->hasAttr<PackedAttr>()) { 13140 FD = FDI; 13141 Alignment = std::min( 13142 Context.getTypeAlignInChars(FD->getType()), 13143 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13144 break; 13145 } 13146 } 13147 assert(FD && "We did not find a packed FieldDecl!"); 13148 Action(E, FD->getParent(), FD, Alignment); 13149 } 13150 } 13151 13152 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13153 using namespace std::placeholders; 13154 13155 RefersToMemberWithReducedAlignment( 13156 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13157 _2, _3, _4)); 13158 } 13159