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->getEndLoc(), 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)->getBeginLoc(), 121 call->getArg(argCount - 1)->getEndLoc()); 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->getBeginLoc(), 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->getBeginLoc(), 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->getEndLoc(), 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->getBeginLoc(), 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->getBeginLoc()); 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()->getBeginLoc(), 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()->getBeginLoc(), 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 StringRef LikelyMacroName) { 243 if (TheCall->getNumArgs() <= SizeIdx || 244 TheCall->getNumArgs() <= DstSizeIdx) 245 return; 246 247 const Expr *SizeArg = TheCall->getArg(SizeIdx); 248 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx); 249 250 llvm::APSInt Size, DstSize; 251 252 // find out if both sizes are known at compile time 253 if (!SizeArg->EvaluateAsInt(Size, S.Context) || 254 !DstSizeArg->EvaluateAsInt(DstSize, S.Context)) 255 return; 256 257 if (Size.ule(DstSize)) 258 return; 259 260 // Confirmed overflow, so generate the diagnostic. 261 StringRef FunctionName = FDecl->getName(); 262 SourceLocation SL = TheCall->getBeginLoc(); 263 SourceManager &SM = S.getSourceManager(); 264 // If we're in an expansion of a macro whose name corresponds to this builtin, 265 // use the simple macro name and location. 266 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) == 267 LikelyMacroName) { 268 FunctionName = LikelyMacroName; 269 SL = SM.getImmediateMacroCallerLoc(SL); 270 } 271 272 S.Diag(SL, diag::warn_memcpy_chk_overflow) 273 << FunctionName << DstSize.toString(/*Radix=*/10) 274 << Size.toString(/*Radix=*/10); 275 } 276 277 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 278 if (checkArgCount(S, BuiltinCall, 2)) 279 return true; 280 281 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 282 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 283 Expr *Call = BuiltinCall->getArg(0); 284 Expr *Chain = BuiltinCall->getArg(1); 285 286 if (Call->getStmtClass() != Stmt::CallExprClass) { 287 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 288 << Call->getSourceRange(); 289 return true; 290 } 291 292 auto CE = cast<CallExpr>(Call); 293 if (CE->getCallee()->getType()->isBlockPointerType()) { 294 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 295 << Call->getSourceRange(); 296 return true; 297 } 298 299 const Decl *TargetDecl = CE->getCalleeDecl(); 300 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 301 if (FD->getBuiltinID()) { 302 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 303 << Call->getSourceRange(); 304 return true; 305 } 306 307 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 308 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 309 << Call->getSourceRange(); 310 return true; 311 } 312 313 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 314 if (ChainResult.isInvalid()) 315 return true; 316 if (!ChainResult.get()->getType()->isPointerType()) { 317 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 318 << Chain->getSourceRange(); 319 return true; 320 } 321 322 QualType ReturnTy = CE->getCallReturnType(S.Context); 323 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 324 QualType BuiltinTy = S.Context.getFunctionType( 325 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 326 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 327 328 Builtin = 329 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 330 331 BuiltinCall->setType(CE->getType()); 332 BuiltinCall->setValueKind(CE->getValueKind()); 333 BuiltinCall->setObjectKind(CE->getObjectKind()); 334 BuiltinCall->setCallee(Builtin); 335 BuiltinCall->setArg(1, ChainResult.get()); 336 337 return false; 338 } 339 340 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 341 Scope::ScopeFlags NeededScopeFlags, 342 unsigned DiagID) { 343 // Scopes aren't available during instantiation. Fortunately, builtin 344 // functions cannot be template args so they cannot be formed through template 345 // instantiation. Therefore checking once during the parse is sufficient. 346 if (SemaRef.inTemplateInstantiation()) 347 return false; 348 349 Scope *S = SemaRef.getCurScope(); 350 while (S && !S->isSEHExceptScope()) 351 S = S->getParent(); 352 if (!S || !(S->getFlags() & NeededScopeFlags)) { 353 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 354 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 355 << DRE->getDecl()->getIdentifier(); 356 return true; 357 } 358 359 return false; 360 } 361 362 static inline bool isBlockPointer(Expr *Arg) { 363 return Arg->getType()->isBlockPointerType(); 364 } 365 366 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 367 /// void*, which is a requirement of device side enqueue. 368 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 369 const BlockPointerType *BPT = 370 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 371 ArrayRef<QualType> Params = 372 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 373 unsigned ArgCounter = 0; 374 bool IllegalParams = false; 375 // Iterate through the block parameters until either one is found that is not 376 // a local void*, or the block is valid. 377 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 378 I != E; ++I, ++ArgCounter) { 379 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 380 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 381 LangAS::opencl_local) { 382 // Get the location of the error. If a block literal has been passed 383 // (BlockExpr) then we can point straight to the offending argument, 384 // else we just point to the variable reference. 385 SourceLocation ErrorLoc; 386 if (isa<BlockExpr>(BlockArg)) { 387 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 388 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 389 } else if (isa<DeclRefExpr>(BlockArg)) { 390 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 391 } 392 S.Diag(ErrorLoc, 393 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 394 IllegalParams = true; 395 } 396 } 397 398 return IllegalParams; 399 } 400 401 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 402 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 403 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 404 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 405 return true; 406 } 407 return false; 408 } 409 410 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 411 if (checkArgCount(S, TheCall, 2)) 412 return true; 413 414 if (checkOpenCLSubgroupExt(S, TheCall)) 415 return true; 416 417 // First argument is an ndrange_t type. 418 Expr *NDRangeArg = TheCall->getArg(0); 419 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 420 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 421 << TheCall->getDirectCallee() << "'ndrange_t'"; 422 return true; 423 } 424 425 Expr *BlockArg = TheCall->getArg(1); 426 if (!isBlockPointer(BlockArg)) { 427 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 428 << TheCall->getDirectCallee() << "block"; 429 return true; 430 } 431 return checkOpenCLBlockArgs(S, BlockArg); 432 } 433 434 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 435 /// get_kernel_work_group_size 436 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 437 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 438 if (checkArgCount(S, TheCall, 1)) 439 return true; 440 441 Expr *BlockArg = TheCall->getArg(0); 442 if (!isBlockPointer(BlockArg)) { 443 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 444 << TheCall->getDirectCallee() << "block"; 445 return true; 446 } 447 return checkOpenCLBlockArgs(S, BlockArg); 448 } 449 450 /// Diagnose integer type and any valid implicit conversion to it. 451 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 452 const QualType &IntType); 453 454 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 455 unsigned Start, unsigned End) { 456 bool IllegalParams = false; 457 for (unsigned I = Start; I <= End; ++I) 458 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 459 S.Context.getSizeType()); 460 return IllegalParams; 461 } 462 463 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 464 /// 'local void*' parameter of passed block. 465 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 466 Expr *BlockArg, 467 unsigned NumNonVarArgs) { 468 const BlockPointerType *BPT = 469 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 470 unsigned NumBlockParams = 471 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 472 unsigned TotalNumArgs = TheCall->getNumArgs(); 473 474 // For each argument passed to the block, a corresponding uint needs to 475 // be passed to describe the size of the local memory. 476 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 477 S.Diag(TheCall->getBeginLoc(), 478 diag::err_opencl_enqueue_kernel_local_size_args); 479 return true; 480 } 481 482 // Check that the sizes of the local memory are specified by integers. 483 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 484 TotalNumArgs - 1); 485 } 486 487 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 488 /// overload formats specified in Table 6.13.17.1. 489 /// int enqueue_kernel(queue_t queue, 490 /// kernel_enqueue_flags_t flags, 491 /// const ndrange_t ndrange, 492 /// void (^block)(void)) 493 /// int enqueue_kernel(queue_t queue, 494 /// kernel_enqueue_flags_t flags, 495 /// const ndrange_t ndrange, 496 /// uint num_events_in_wait_list, 497 /// clk_event_t *event_wait_list, 498 /// clk_event_t *event_ret, 499 /// void (^block)(void)) 500 /// int enqueue_kernel(queue_t queue, 501 /// kernel_enqueue_flags_t flags, 502 /// const ndrange_t ndrange, 503 /// void (^block)(local void*, ...), 504 /// uint size0, ...) 505 /// int enqueue_kernel(queue_t queue, 506 /// kernel_enqueue_flags_t flags, 507 /// const ndrange_t ndrange, 508 /// uint num_events_in_wait_list, 509 /// clk_event_t *event_wait_list, 510 /// clk_event_t *event_ret, 511 /// void (^block)(local void*, ...), 512 /// uint size0, ...) 513 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 514 unsigned NumArgs = TheCall->getNumArgs(); 515 516 if (NumArgs < 4) { 517 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 518 return true; 519 } 520 521 Expr *Arg0 = TheCall->getArg(0); 522 Expr *Arg1 = TheCall->getArg(1); 523 Expr *Arg2 = TheCall->getArg(2); 524 Expr *Arg3 = TheCall->getArg(3); 525 526 // First argument always needs to be a queue_t type. 527 if (!Arg0->getType()->isQueueT()) { 528 S.Diag(TheCall->getArg(0)->getBeginLoc(), 529 diag::err_opencl_builtin_expected_type) 530 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 531 return true; 532 } 533 534 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 535 if (!Arg1->getType()->isIntegerType()) { 536 S.Diag(TheCall->getArg(1)->getBeginLoc(), 537 diag::err_opencl_builtin_expected_type) 538 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 539 return true; 540 } 541 542 // Third argument is always an ndrange_t type. 543 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 544 S.Diag(TheCall->getArg(2)->getBeginLoc(), 545 diag::err_opencl_builtin_expected_type) 546 << TheCall->getDirectCallee() << "'ndrange_t'"; 547 return true; 548 } 549 550 // With four arguments, there is only one form that the function could be 551 // called in: no events and no variable arguments. 552 if (NumArgs == 4) { 553 // check that the last argument is the right block type. 554 if (!isBlockPointer(Arg3)) { 555 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 556 << TheCall->getDirectCallee() << "block"; 557 return true; 558 } 559 // we have a block type, check the prototype 560 const BlockPointerType *BPT = 561 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 562 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 563 S.Diag(Arg3->getBeginLoc(), 564 diag::err_opencl_enqueue_kernel_blocks_no_args); 565 return true; 566 } 567 return false; 568 } 569 // we can have block + varargs. 570 if (isBlockPointer(Arg3)) 571 return (checkOpenCLBlockArgs(S, Arg3) || 572 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 573 // last two cases with either exactly 7 args or 7 args and varargs. 574 if (NumArgs >= 7) { 575 // check common block argument. 576 Expr *Arg6 = TheCall->getArg(6); 577 if (!isBlockPointer(Arg6)) { 578 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 579 << TheCall->getDirectCallee() << "block"; 580 return true; 581 } 582 if (checkOpenCLBlockArgs(S, Arg6)) 583 return true; 584 585 // Forth argument has to be any integer type. 586 if (!Arg3->getType()->isIntegerType()) { 587 S.Diag(TheCall->getArg(3)->getBeginLoc(), 588 diag::err_opencl_builtin_expected_type) 589 << TheCall->getDirectCallee() << "integer"; 590 return true; 591 } 592 // check remaining common arguments. 593 Expr *Arg4 = TheCall->getArg(4); 594 Expr *Arg5 = TheCall->getArg(5); 595 596 // Fifth argument is always passed as a pointer to clk_event_t. 597 if (!Arg4->isNullPointerConstant(S.Context, 598 Expr::NPC_ValueDependentIsNotNull) && 599 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 600 S.Diag(TheCall->getArg(4)->getBeginLoc(), 601 diag::err_opencl_builtin_expected_type) 602 << TheCall->getDirectCallee() 603 << S.Context.getPointerType(S.Context.OCLClkEventTy); 604 return true; 605 } 606 607 // Sixth argument is always passed as a pointer to clk_event_t. 608 if (!Arg5->isNullPointerConstant(S.Context, 609 Expr::NPC_ValueDependentIsNotNull) && 610 !(Arg5->getType()->isPointerType() && 611 Arg5->getType()->getPointeeType()->isClkEventT())) { 612 S.Diag(TheCall->getArg(5)->getBeginLoc(), 613 diag::err_opencl_builtin_expected_type) 614 << TheCall->getDirectCallee() 615 << S.Context.getPointerType(S.Context.OCLClkEventTy); 616 return true; 617 } 618 619 if (NumArgs == 7) 620 return false; 621 622 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 623 } 624 625 // None of the specific case has been detected, give generic error 626 S.Diag(TheCall->getBeginLoc(), 627 diag::err_opencl_enqueue_kernel_incorrect_args); 628 return true; 629 } 630 631 /// Returns OpenCL access qual. 632 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 633 return D->getAttr<OpenCLAccessAttr>(); 634 } 635 636 /// Returns true if pipe element type is different from the pointer. 637 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 638 const Expr *Arg0 = Call->getArg(0); 639 // First argument type should always be pipe. 640 if (!Arg0->getType()->isPipeType()) { 641 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 642 << Call->getDirectCallee() << Arg0->getSourceRange(); 643 return true; 644 } 645 OpenCLAccessAttr *AccessQual = 646 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 647 // Validates the access qualifier is compatible with the call. 648 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 649 // read_only and write_only, and assumed to be read_only if no qualifier is 650 // specified. 651 switch (Call->getDirectCallee()->getBuiltinID()) { 652 case Builtin::BIread_pipe: 653 case Builtin::BIreserve_read_pipe: 654 case Builtin::BIcommit_read_pipe: 655 case Builtin::BIwork_group_reserve_read_pipe: 656 case Builtin::BIsub_group_reserve_read_pipe: 657 case Builtin::BIwork_group_commit_read_pipe: 658 case Builtin::BIsub_group_commit_read_pipe: 659 if (!(!AccessQual || AccessQual->isReadOnly())) { 660 S.Diag(Arg0->getBeginLoc(), 661 diag::err_opencl_builtin_pipe_invalid_access_modifier) 662 << "read_only" << Arg0->getSourceRange(); 663 return true; 664 } 665 break; 666 case Builtin::BIwrite_pipe: 667 case Builtin::BIreserve_write_pipe: 668 case Builtin::BIcommit_write_pipe: 669 case Builtin::BIwork_group_reserve_write_pipe: 670 case Builtin::BIsub_group_reserve_write_pipe: 671 case Builtin::BIwork_group_commit_write_pipe: 672 case Builtin::BIsub_group_commit_write_pipe: 673 if (!(AccessQual && AccessQual->isWriteOnly())) { 674 S.Diag(Arg0->getBeginLoc(), 675 diag::err_opencl_builtin_pipe_invalid_access_modifier) 676 << "write_only" << Arg0->getSourceRange(); 677 return true; 678 } 679 break; 680 default: 681 break; 682 } 683 return false; 684 } 685 686 /// Returns true if pipe element type is different from the pointer. 687 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 688 const Expr *Arg0 = Call->getArg(0); 689 const Expr *ArgIdx = Call->getArg(Idx); 690 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 691 const QualType EltTy = PipeTy->getElementType(); 692 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 693 // The Idx argument should be a pointer and the type of the pointer and 694 // the type of pipe element should also be the same. 695 if (!ArgTy || 696 !S.Context.hasSameType( 697 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 698 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 699 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 700 << ArgIdx->getType() << ArgIdx->getSourceRange(); 701 return true; 702 } 703 return false; 704 } 705 706 // Performs semantic analysis for the read/write_pipe call. 707 // \param S Reference to the semantic analyzer. 708 // \param Call A pointer to the builtin call. 709 // \return True if a semantic error has been found, false otherwise. 710 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 711 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 712 // functions have two forms. 713 switch (Call->getNumArgs()) { 714 case 2: 715 if (checkOpenCLPipeArg(S, Call)) 716 return true; 717 // The call with 2 arguments should be 718 // read/write_pipe(pipe T, T*). 719 // Check packet type T. 720 if (checkOpenCLPipePacketType(S, Call, 1)) 721 return true; 722 break; 723 724 case 4: { 725 if (checkOpenCLPipeArg(S, Call)) 726 return true; 727 // The call with 4 arguments should be 728 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 729 // Check reserve_id_t. 730 if (!Call->getArg(1)->getType()->isReserveIDT()) { 731 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 732 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 733 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 734 return true; 735 } 736 737 // Check the index. 738 const Expr *Arg2 = Call->getArg(2); 739 if (!Arg2->getType()->isIntegerType() && 740 !Arg2->getType()->isUnsignedIntegerType()) { 741 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 742 << Call->getDirectCallee() << S.Context.UnsignedIntTy 743 << Arg2->getType() << Arg2->getSourceRange(); 744 return true; 745 } 746 747 // Check packet type T. 748 if (checkOpenCLPipePacketType(S, Call, 3)) 749 return true; 750 } break; 751 default: 752 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 753 << Call->getDirectCallee() << Call->getSourceRange(); 754 return true; 755 } 756 757 return false; 758 } 759 760 // Performs a semantic analysis on the {work_group_/sub_group_ 761 // /_}reserve_{read/write}_pipe 762 // \param S Reference to the semantic analyzer. 763 // \param Call The call to the builtin function to be analyzed. 764 // \return True if a semantic error was found, false otherwise. 765 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 766 if (checkArgCount(S, Call, 2)) 767 return true; 768 769 if (checkOpenCLPipeArg(S, Call)) 770 return true; 771 772 // Check the reserve size. 773 if (!Call->getArg(1)->getType()->isIntegerType() && 774 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 775 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 776 << Call->getDirectCallee() << S.Context.UnsignedIntTy 777 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 778 return true; 779 } 780 781 // Since return type of reserve_read/write_pipe built-in function is 782 // reserve_id_t, which is not defined in the builtin def file , we used int 783 // as return type and need to override the return type of these functions. 784 Call->setType(S.Context.OCLReserveIDTy); 785 786 return false; 787 } 788 789 // Performs a semantic analysis on {work_group_/sub_group_ 790 // /_}commit_{read/write}_pipe 791 // \param S Reference to the semantic analyzer. 792 // \param Call The call to the builtin function to be analyzed. 793 // \return True if a semantic error was found, false otherwise. 794 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 795 if (checkArgCount(S, Call, 2)) 796 return true; 797 798 if (checkOpenCLPipeArg(S, Call)) 799 return true; 800 801 // Check reserve_id_t. 802 if (!Call->getArg(1)->getType()->isReserveIDT()) { 803 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 804 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 805 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 806 return true; 807 } 808 809 return false; 810 } 811 812 // Performs a semantic analysis on the call to built-in Pipe 813 // Query Functions. 814 // \param S Reference to the semantic analyzer. 815 // \param Call The call to the builtin function to be analyzed. 816 // \return True if a semantic error was found, false otherwise. 817 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 818 if (checkArgCount(S, Call, 1)) 819 return true; 820 821 if (!Call->getArg(0)->getType()->isPipeType()) { 822 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 823 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 824 return true; 825 } 826 827 return false; 828 } 829 830 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 831 // Performs semantic analysis for the to_global/local/private call. 832 // \param S Reference to the semantic analyzer. 833 // \param BuiltinID ID of the builtin function. 834 // \param Call A pointer to the builtin call. 835 // \return True if a semantic error has been found, false otherwise. 836 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 837 CallExpr *Call) { 838 if (Call->getNumArgs() != 1) { 839 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 840 << Call->getDirectCallee() << Call->getSourceRange(); 841 return true; 842 } 843 844 auto RT = Call->getArg(0)->getType(); 845 if (!RT->isPointerType() || RT->getPointeeType() 846 .getAddressSpace() == LangAS::opencl_constant) { 847 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 848 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 849 return true; 850 } 851 852 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 853 S.Diag(Call->getArg(0)->getBeginLoc(), 854 diag::warn_opencl_generic_address_space_arg) 855 << Call->getDirectCallee()->getNameInfo().getAsString() 856 << Call->getArg(0)->getSourceRange(); 857 } 858 859 RT = RT->getPointeeType(); 860 auto Qual = RT.getQualifiers(); 861 switch (BuiltinID) { 862 case Builtin::BIto_global: 863 Qual.setAddressSpace(LangAS::opencl_global); 864 break; 865 case Builtin::BIto_local: 866 Qual.setAddressSpace(LangAS::opencl_local); 867 break; 868 case Builtin::BIto_private: 869 Qual.setAddressSpace(LangAS::opencl_private); 870 break; 871 default: 872 llvm_unreachable("Invalid builtin function"); 873 } 874 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 875 RT.getUnqualifiedType(), Qual))); 876 877 return false; 878 } 879 880 // Emit an error and return true if the current architecture is not in the list 881 // of supported architectures. 882 static bool 883 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 884 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 885 llvm::Triple::ArchType CurArch = 886 S.getASTContext().getTargetInfo().getTriple().getArch(); 887 if (llvm::is_contained(SupportedArchs, CurArch)) 888 return false; 889 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 890 << TheCall->getSourceRange(); 891 return true; 892 } 893 894 ExprResult 895 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 896 CallExpr *TheCall) { 897 ExprResult TheCallResult(TheCall); 898 899 // Find out if any arguments are required to be integer constant expressions. 900 unsigned ICEArguments = 0; 901 ASTContext::GetBuiltinTypeError Error; 902 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 903 if (Error != ASTContext::GE_None) 904 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 905 906 // If any arguments are required to be ICE's, check and diagnose. 907 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 908 // Skip arguments not required to be ICE's. 909 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 910 911 llvm::APSInt Result; 912 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 913 return true; 914 ICEArguments &= ~(1 << ArgNo); 915 } 916 917 switch (BuiltinID) { 918 case Builtin::BI__builtin___CFStringMakeConstantString: 919 assert(TheCall->getNumArgs() == 1 && 920 "Wrong # arguments to builtin CFStringMakeConstantString"); 921 if (CheckObjCString(TheCall->getArg(0))) 922 return ExprError(); 923 break; 924 case Builtin::BI__builtin_ms_va_start: 925 case Builtin::BI__builtin_stdarg_start: 926 case Builtin::BI__builtin_va_start: 927 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 928 return ExprError(); 929 break; 930 case Builtin::BI__va_start: { 931 switch (Context.getTargetInfo().getTriple().getArch()) { 932 case llvm::Triple::aarch64: 933 case llvm::Triple::arm: 934 case llvm::Triple::thumb: 935 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 936 return ExprError(); 937 break; 938 default: 939 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 940 return ExprError(); 941 break; 942 } 943 break; 944 } 945 946 // The acquire, release, and no fence variants are ARM and AArch64 only. 947 case Builtin::BI_interlockedbittestandset_acq: 948 case Builtin::BI_interlockedbittestandset_rel: 949 case Builtin::BI_interlockedbittestandset_nf: 950 case Builtin::BI_interlockedbittestandreset_acq: 951 case Builtin::BI_interlockedbittestandreset_rel: 952 case Builtin::BI_interlockedbittestandreset_nf: 953 if (CheckBuiltinTargetSupport( 954 *this, BuiltinID, TheCall, 955 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 956 return ExprError(); 957 break; 958 959 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 960 case Builtin::BI_bittest64: 961 case Builtin::BI_bittestandcomplement64: 962 case Builtin::BI_bittestandreset64: 963 case Builtin::BI_bittestandset64: 964 case Builtin::BI_interlockedbittestandreset64: 965 case Builtin::BI_interlockedbittestandset64: 966 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 967 {llvm::Triple::x86_64, llvm::Triple::arm, 968 llvm::Triple::thumb, llvm::Triple::aarch64})) 969 return ExprError(); 970 break; 971 972 case Builtin::BI__builtin_isgreater: 973 case Builtin::BI__builtin_isgreaterequal: 974 case Builtin::BI__builtin_isless: 975 case Builtin::BI__builtin_islessequal: 976 case Builtin::BI__builtin_islessgreater: 977 case Builtin::BI__builtin_isunordered: 978 if (SemaBuiltinUnorderedCompare(TheCall)) 979 return ExprError(); 980 break; 981 case Builtin::BI__builtin_fpclassify: 982 if (SemaBuiltinFPClassification(TheCall, 6)) 983 return ExprError(); 984 break; 985 case Builtin::BI__builtin_isfinite: 986 case Builtin::BI__builtin_isinf: 987 case Builtin::BI__builtin_isinf_sign: 988 case Builtin::BI__builtin_isnan: 989 case Builtin::BI__builtin_isnormal: 990 case Builtin::BI__builtin_signbit: 991 case Builtin::BI__builtin_signbitf: 992 case Builtin::BI__builtin_signbitl: 993 if (SemaBuiltinFPClassification(TheCall, 1)) 994 return ExprError(); 995 break; 996 case Builtin::BI__builtin_shufflevector: 997 return SemaBuiltinShuffleVector(TheCall); 998 // TheCall will be freed by the smart pointer here, but that's fine, since 999 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1000 case Builtin::BI__builtin_prefetch: 1001 if (SemaBuiltinPrefetch(TheCall)) 1002 return ExprError(); 1003 break; 1004 case Builtin::BI__builtin_alloca_with_align: 1005 if (SemaBuiltinAllocaWithAlign(TheCall)) 1006 return ExprError(); 1007 break; 1008 case Builtin::BI__assume: 1009 case Builtin::BI__builtin_assume: 1010 if (SemaBuiltinAssume(TheCall)) 1011 return ExprError(); 1012 break; 1013 case Builtin::BI__builtin_assume_aligned: 1014 if (SemaBuiltinAssumeAligned(TheCall)) 1015 return ExprError(); 1016 break; 1017 case Builtin::BI__builtin_object_size: 1018 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1019 return ExprError(); 1020 break; 1021 case Builtin::BI__builtin_longjmp: 1022 if (SemaBuiltinLongjmp(TheCall)) 1023 return ExprError(); 1024 break; 1025 case Builtin::BI__builtin_setjmp: 1026 if (SemaBuiltinSetjmp(TheCall)) 1027 return ExprError(); 1028 break; 1029 case Builtin::BI_setjmp: 1030 case Builtin::BI_setjmpex: 1031 if (checkArgCount(*this, TheCall, 1)) 1032 return true; 1033 break; 1034 case Builtin::BI__builtin_classify_type: 1035 if (checkArgCount(*this, TheCall, 1)) return true; 1036 TheCall->setType(Context.IntTy); 1037 break; 1038 case Builtin::BI__builtin_constant_p: 1039 if (checkArgCount(*this, TheCall, 1)) return true; 1040 TheCall->setType(Context.IntTy); 1041 break; 1042 case Builtin::BI__sync_fetch_and_add: 1043 case Builtin::BI__sync_fetch_and_add_1: 1044 case Builtin::BI__sync_fetch_and_add_2: 1045 case Builtin::BI__sync_fetch_and_add_4: 1046 case Builtin::BI__sync_fetch_and_add_8: 1047 case Builtin::BI__sync_fetch_and_add_16: 1048 case Builtin::BI__sync_fetch_and_sub: 1049 case Builtin::BI__sync_fetch_and_sub_1: 1050 case Builtin::BI__sync_fetch_and_sub_2: 1051 case Builtin::BI__sync_fetch_and_sub_4: 1052 case Builtin::BI__sync_fetch_and_sub_8: 1053 case Builtin::BI__sync_fetch_and_sub_16: 1054 case Builtin::BI__sync_fetch_and_or: 1055 case Builtin::BI__sync_fetch_and_or_1: 1056 case Builtin::BI__sync_fetch_and_or_2: 1057 case Builtin::BI__sync_fetch_and_or_4: 1058 case Builtin::BI__sync_fetch_and_or_8: 1059 case Builtin::BI__sync_fetch_and_or_16: 1060 case Builtin::BI__sync_fetch_and_and: 1061 case Builtin::BI__sync_fetch_and_and_1: 1062 case Builtin::BI__sync_fetch_and_and_2: 1063 case Builtin::BI__sync_fetch_and_and_4: 1064 case Builtin::BI__sync_fetch_and_and_8: 1065 case Builtin::BI__sync_fetch_and_and_16: 1066 case Builtin::BI__sync_fetch_and_xor: 1067 case Builtin::BI__sync_fetch_and_xor_1: 1068 case Builtin::BI__sync_fetch_and_xor_2: 1069 case Builtin::BI__sync_fetch_and_xor_4: 1070 case Builtin::BI__sync_fetch_and_xor_8: 1071 case Builtin::BI__sync_fetch_and_xor_16: 1072 case Builtin::BI__sync_fetch_and_nand: 1073 case Builtin::BI__sync_fetch_and_nand_1: 1074 case Builtin::BI__sync_fetch_and_nand_2: 1075 case Builtin::BI__sync_fetch_and_nand_4: 1076 case Builtin::BI__sync_fetch_and_nand_8: 1077 case Builtin::BI__sync_fetch_and_nand_16: 1078 case Builtin::BI__sync_add_and_fetch: 1079 case Builtin::BI__sync_add_and_fetch_1: 1080 case Builtin::BI__sync_add_and_fetch_2: 1081 case Builtin::BI__sync_add_and_fetch_4: 1082 case Builtin::BI__sync_add_and_fetch_8: 1083 case Builtin::BI__sync_add_and_fetch_16: 1084 case Builtin::BI__sync_sub_and_fetch: 1085 case Builtin::BI__sync_sub_and_fetch_1: 1086 case Builtin::BI__sync_sub_and_fetch_2: 1087 case Builtin::BI__sync_sub_and_fetch_4: 1088 case Builtin::BI__sync_sub_and_fetch_8: 1089 case Builtin::BI__sync_sub_and_fetch_16: 1090 case Builtin::BI__sync_and_and_fetch: 1091 case Builtin::BI__sync_and_and_fetch_1: 1092 case Builtin::BI__sync_and_and_fetch_2: 1093 case Builtin::BI__sync_and_and_fetch_4: 1094 case Builtin::BI__sync_and_and_fetch_8: 1095 case Builtin::BI__sync_and_and_fetch_16: 1096 case Builtin::BI__sync_or_and_fetch: 1097 case Builtin::BI__sync_or_and_fetch_1: 1098 case Builtin::BI__sync_or_and_fetch_2: 1099 case Builtin::BI__sync_or_and_fetch_4: 1100 case Builtin::BI__sync_or_and_fetch_8: 1101 case Builtin::BI__sync_or_and_fetch_16: 1102 case Builtin::BI__sync_xor_and_fetch: 1103 case Builtin::BI__sync_xor_and_fetch_1: 1104 case Builtin::BI__sync_xor_and_fetch_2: 1105 case Builtin::BI__sync_xor_and_fetch_4: 1106 case Builtin::BI__sync_xor_and_fetch_8: 1107 case Builtin::BI__sync_xor_and_fetch_16: 1108 case Builtin::BI__sync_nand_and_fetch: 1109 case Builtin::BI__sync_nand_and_fetch_1: 1110 case Builtin::BI__sync_nand_and_fetch_2: 1111 case Builtin::BI__sync_nand_and_fetch_4: 1112 case Builtin::BI__sync_nand_and_fetch_8: 1113 case Builtin::BI__sync_nand_and_fetch_16: 1114 case Builtin::BI__sync_val_compare_and_swap: 1115 case Builtin::BI__sync_val_compare_and_swap_1: 1116 case Builtin::BI__sync_val_compare_and_swap_2: 1117 case Builtin::BI__sync_val_compare_and_swap_4: 1118 case Builtin::BI__sync_val_compare_and_swap_8: 1119 case Builtin::BI__sync_val_compare_and_swap_16: 1120 case Builtin::BI__sync_bool_compare_and_swap: 1121 case Builtin::BI__sync_bool_compare_and_swap_1: 1122 case Builtin::BI__sync_bool_compare_and_swap_2: 1123 case Builtin::BI__sync_bool_compare_and_swap_4: 1124 case Builtin::BI__sync_bool_compare_and_swap_8: 1125 case Builtin::BI__sync_bool_compare_and_swap_16: 1126 case Builtin::BI__sync_lock_test_and_set: 1127 case Builtin::BI__sync_lock_test_and_set_1: 1128 case Builtin::BI__sync_lock_test_and_set_2: 1129 case Builtin::BI__sync_lock_test_and_set_4: 1130 case Builtin::BI__sync_lock_test_and_set_8: 1131 case Builtin::BI__sync_lock_test_and_set_16: 1132 case Builtin::BI__sync_lock_release: 1133 case Builtin::BI__sync_lock_release_1: 1134 case Builtin::BI__sync_lock_release_2: 1135 case Builtin::BI__sync_lock_release_4: 1136 case Builtin::BI__sync_lock_release_8: 1137 case Builtin::BI__sync_lock_release_16: 1138 case Builtin::BI__sync_swap: 1139 case Builtin::BI__sync_swap_1: 1140 case Builtin::BI__sync_swap_2: 1141 case Builtin::BI__sync_swap_4: 1142 case Builtin::BI__sync_swap_8: 1143 case Builtin::BI__sync_swap_16: 1144 return SemaBuiltinAtomicOverloaded(TheCallResult); 1145 case Builtin::BI__sync_synchronize: 1146 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1147 << TheCall->getCallee()->getSourceRange(); 1148 break; 1149 case Builtin::BI__builtin_nontemporal_load: 1150 case Builtin::BI__builtin_nontemporal_store: 1151 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1152 #define BUILTIN(ID, TYPE, ATTRS) 1153 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1154 case Builtin::BI##ID: \ 1155 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1156 #include "clang/Basic/Builtins.def" 1157 case Builtin::BI__annotation: 1158 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1159 return ExprError(); 1160 break; 1161 case Builtin::BI__builtin_annotation: 1162 if (SemaBuiltinAnnotation(*this, TheCall)) 1163 return ExprError(); 1164 break; 1165 case Builtin::BI__builtin_addressof: 1166 if (SemaBuiltinAddressof(*this, TheCall)) 1167 return ExprError(); 1168 break; 1169 case Builtin::BI__builtin_add_overflow: 1170 case Builtin::BI__builtin_sub_overflow: 1171 case Builtin::BI__builtin_mul_overflow: 1172 if (SemaBuiltinOverflow(*this, TheCall)) 1173 return ExprError(); 1174 break; 1175 case Builtin::BI__builtin_operator_new: 1176 case Builtin::BI__builtin_operator_delete: { 1177 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1178 ExprResult Res = 1179 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1180 if (Res.isInvalid()) 1181 CorrectDelayedTyposInExpr(TheCallResult.get()); 1182 return Res; 1183 } 1184 case Builtin::BI__builtin_dump_struct: { 1185 // We first want to ensure we are called with 2 arguments 1186 if (checkArgCount(*this, TheCall, 2)) 1187 return ExprError(); 1188 // Ensure that the first argument is of type 'struct XX *' 1189 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1190 const QualType PtrArgType = PtrArg->getType(); 1191 if (!PtrArgType->isPointerType() || 1192 !PtrArgType->getPointeeType()->isRecordType()) { 1193 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1194 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1195 << "structure pointer"; 1196 return ExprError(); 1197 } 1198 1199 // Ensure that the second argument is of type 'FunctionType' 1200 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1201 const QualType FnPtrArgType = FnPtrArg->getType(); 1202 if (!FnPtrArgType->isPointerType()) { 1203 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1204 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1205 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1206 return ExprError(); 1207 } 1208 1209 const auto *FuncType = 1210 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1211 1212 if (!FuncType) { 1213 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1214 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1215 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1216 return ExprError(); 1217 } 1218 1219 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1220 if (!FT->getNumParams()) { 1221 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1222 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1223 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1224 return ExprError(); 1225 } 1226 QualType PT = FT->getParamType(0); 1227 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1228 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1229 !PT->getPointeeType().isConstQualified()) { 1230 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1231 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1232 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1233 return ExprError(); 1234 } 1235 } 1236 1237 TheCall->setType(Context.IntTy); 1238 break; 1239 } 1240 1241 // check secure string manipulation functions where overflows 1242 // are detectable at compile time 1243 case Builtin::BI__builtin___memcpy_chk: 1244 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy"); 1245 break; 1246 case Builtin::BI__builtin___memmove_chk: 1247 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove"); 1248 break; 1249 case Builtin::BI__builtin___memset_chk: 1250 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset"); 1251 break; 1252 case Builtin::BI__builtin___strlcat_chk: 1253 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat"); 1254 break; 1255 case Builtin::BI__builtin___strlcpy_chk: 1256 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy"); 1257 break; 1258 case Builtin::BI__builtin___strncat_chk: 1259 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat"); 1260 break; 1261 case Builtin::BI__builtin___strncpy_chk: 1262 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy"); 1263 break; 1264 case Builtin::BI__builtin___stpncpy_chk: 1265 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy"); 1266 break; 1267 case Builtin::BI__builtin___memccpy_chk: 1268 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy"); 1269 break; 1270 case Builtin::BI__builtin___snprintf_chk: 1271 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf"); 1272 break; 1273 case Builtin::BI__builtin___vsnprintf_chk: 1274 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf"); 1275 break; 1276 case Builtin::BI__builtin_call_with_static_chain: 1277 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1278 return ExprError(); 1279 break; 1280 case Builtin::BI__exception_code: 1281 case Builtin::BI_exception_code: 1282 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1283 diag::err_seh___except_block)) 1284 return ExprError(); 1285 break; 1286 case Builtin::BI__exception_info: 1287 case Builtin::BI_exception_info: 1288 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1289 diag::err_seh___except_filter)) 1290 return ExprError(); 1291 break; 1292 case Builtin::BI__GetExceptionInfo: 1293 if (checkArgCount(*this, TheCall, 1)) 1294 return ExprError(); 1295 1296 if (CheckCXXThrowOperand( 1297 TheCall->getBeginLoc(), 1298 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1299 TheCall)) 1300 return ExprError(); 1301 1302 TheCall->setType(Context.VoidPtrTy); 1303 break; 1304 // OpenCL v2.0, s6.13.16 - Pipe functions 1305 case Builtin::BIread_pipe: 1306 case Builtin::BIwrite_pipe: 1307 // Since those two functions are declared with var args, we need a semantic 1308 // check for the argument. 1309 if (SemaBuiltinRWPipe(*this, TheCall)) 1310 return ExprError(); 1311 TheCall->setType(Context.IntTy); 1312 break; 1313 case Builtin::BIreserve_read_pipe: 1314 case Builtin::BIreserve_write_pipe: 1315 case Builtin::BIwork_group_reserve_read_pipe: 1316 case Builtin::BIwork_group_reserve_write_pipe: 1317 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1318 return ExprError(); 1319 break; 1320 case Builtin::BIsub_group_reserve_read_pipe: 1321 case Builtin::BIsub_group_reserve_write_pipe: 1322 if (checkOpenCLSubgroupExt(*this, TheCall) || 1323 SemaBuiltinReserveRWPipe(*this, TheCall)) 1324 return ExprError(); 1325 break; 1326 case Builtin::BIcommit_read_pipe: 1327 case Builtin::BIcommit_write_pipe: 1328 case Builtin::BIwork_group_commit_read_pipe: 1329 case Builtin::BIwork_group_commit_write_pipe: 1330 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1331 return ExprError(); 1332 break; 1333 case Builtin::BIsub_group_commit_read_pipe: 1334 case Builtin::BIsub_group_commit_write_pipe: 1335 if (checkOpenCLSubgroupExt(*this, TheCall) || 1336 SemaBuiltinCommitRWPipe(*this, TheCall)) 1337 return ExprError(); 1338 break; 1339 case Builtin::BIget_pipe_num_packets: 1340 case Builtin::BIget_pipe_max_packets: 1341 if (SemaBuiltinPipePackets(*this, TheCall)) 1342 return ExprError(); 1343 TheCall->setType(Context.UnsignedIntTy); 1344 break; 1345 case Builtin::BIto_global: 1346 case Builtin::BIto_local: 1347 case Builtin::BIto_private: 1348 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1349 return ExprError(); 1350 break; 1351 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1352 case Builtin::BIenqueue_kernel: 1353 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1354 return ExprError(); 1355 break; 1356 case Builtin::BIget_kernel_work_group_size: 1357 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1358 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1359 return ExprError(); 1360 break; 1361 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1362 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1363 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1364 return ExprError(); 1365 break; 1366 case Builtin::BI__builtin_os_log_format: 1367 case Builtin::BI__builtin_os_log_format_buffer_size: 1368 if (SemaBuiltinOSLogFormat(TheCall)) 1369 return ExprError(); 1370 break; 1371 } 1372 1373 // Since the target specific builtins for each arch overlap, only check those 1374 // of the arch we are compiling for. 1375 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1376 switch (Context.getTargetInfo().getTriple().getArch()) { 1377 case llvm::Triple::arm: 1378 case llvm::Triple::armeb: 1379 case llvm::Triple::thumb: 1380 case llvm::Triple::thumbeb: 1381 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1382 return ExprError(); 1383 break; 1384 case llvm::Triple::aarch64: 1385 case llvm::Triple::aarch64_be: 1386 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1387 return ExprError(); 1388 break; 1389 case llvm::Triple::hexagon: 1390 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1391 return ExprError(); 1392 break; 1393 case llvm::Triple::mips: 1394 case llvm::Triple::mipsel: 1395 case llvm::Triple::mips64: 1396 case llvm::Triple::mips64el: 1397 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1398 return ExprError(); 1399 break; 1400 case llvm::Triple::systemz: 1401 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1402 return ExprError(); 1403 break; 1404 case llvm::Triple::x86: 1405 case llvm::Triple::x86_64: 1406 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1407 return ExprError(); 1408 break; 1409 case llvm::Triple::ppc: 1410 case llvm::Triple::ppc64: 1411 case llvm::Triple::ppc64le: 1412 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1413 return ExprError(); 1414 break; 1415 default: 1416 break; 1417 } 1418 } 1419 1420 return TheCallResult; 1421 } 1422 1423 // Get the valid immediate range for the specified NEON type code. 1424 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1425 NeonTypeFlags Type(t); 1426 int IsQuad = ForceQuad ? true : Type.isQuad(); 1427 switch (Type.getEltType()) { 1428 case NeonTypeFlags::Int8: 1429 case NeonTypeFlags::Poly8: 1430 return shift ? 7 : (8 << IsQuad) - 1; 1431 case NeonTypeFlags::Int16: 1432 case NeonTypeFlags::Poly16: 1433 return shift ? 15 : (4 << IsQuad) - 1; 1434 case NeonTypeFlags::Int32: 1435 return shift ? 31 : (2 << IsQuad) - 1; 1436 case NeonTypeFlags::Int64: 1437 case NeonTypeFlags::Poly64: 1438 return shift ? 63 : (1 << IsQuad) - 1; 1439 case NeonTypeFlags::Poly128: 1440 return shift ? 127 : (1 << IsQuad) - 1; 1441 case NeonTypeFlags::Float16: 1442 assert(!shift && "cannot shift float types!"); 1443 return (4 << IsQuad) - 1; 1444 case NeonTypeFlags::Float32: 1445 assert(!shift && "cannot shift float types!"); 1446 return (2 << IsQuad) - 1; 1447 case NeonTypeFlags::Float64: 1448 assert(!shift && "cannot shift float types!"); 1449 return (1 << IsQuad) - 1; 1450 } 1451 llvm_unreachable("Invalid NeonTypeFlag!"); 1452 } 1453 1454 /// getNeonEltType - Return the QualType corresponding to the elements of 1455 /// the vector type specified by the NeonTypeFlags. This is used to check 1456 /// the pointer arguments for Neon load/store intrinsics. 1457 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1458 bool IsPolyUnsigned, bool IsInt64Long) { 1459 switch (Flags.getEltType()) { 1460 case NeonTypeFlags::Int8: 1461 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1462 case NeonTypeFlags::Int16: 1463 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1464 case NeonTypeFlags::Int32: 1465 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1466 case NeonTypeFlags::Int64: 1467 if (IsInt64Long) 1468 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1469 else 1470 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1471 : Context.LongLongTy; 1472 case NeonTypeFlags::Poly8: 1473 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1474 case NeonTypeFlags::Poly16: 1475 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1476 case NeonTypeFlags::Poly64: 1477 if (IsInt64Long) 1478 return Context.UnsignedLongTy; 1479 else 1480 return Context.UnsignedLongLongTy; 1481 case NeonTypeFlags::Poly128: 1482 break; 1483 case NeonTypeFlags::Float16: 1484 return Context.HalfTy; 1485 case NeonTypeFlags::Float32: 1486 return Context.FloatTy; 1487 case NeonTypeFlags::Float64: 1488 return Context.DoubleTy; 1489 } 1490 llvm_unreachable("Invalid NeonTypeFlag!"); 1491 } 1492 1493 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1494 llvm::APSInt Result; 1495 uint64_t mask = 0; 1496 unsigned TV = 0; 1497 int PtrArgNum = -1; 1498 bool HasConstPtr = false; 1499 switch (BuiltinID) { 1500 #define GET_NEON_OVERLOAD_CHECK 1501 #include "clang/Basic/arm_neon.inc" 1502 #include "clang/Basic/arm_fp16.inc" 1503 #undef GET_NEON_OVERLOAD_CHECK 1504 } 1505 1506 // For NEON intrinsics which are overloaded on vector element type, validate 1507 // the immediate which specifies which variant to emit. 1508 unsigned ImmArg = TheCall->getNumArgs()-1; 1509 if (mask) { 1510 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1511 return true; 1512 1513 TV = Result.getLimitedValue(64); 1514 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1515 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1516 << TheCall->getArg(ImmArg)->getSourceRange(); 1517 } 1518 1519 if (PtrArgNum >= 0) { 1520 // Check that pointer arguments have the specified type. 1521 Expr *Arg = TheCall->getArg(PtrArgNum); 1522 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1523 Arg = ICE->getSubExpr(); 1524 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1525 QualType RHSTy = RHS.get()->getType(); 1526 1527 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1528 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1529 Arch == llvm::Triple::aarch64_be; 1530 bool IsInt64Long = 1531 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1532 QualType EltTy = 1533 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1534 if (HasConstPtr) 1535 EltTy = EltTy.withConst(); 1536 QualType LHSTy = Context.getPointerType(EltTy); 1537 AssignConvertType ConvTy; 1538 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1539 if (RHS.isInvalid()) 1540 return true; 1541 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1542 RHS.get(), AA_Assigning)) 1543 return true; 1544 } 1545 1546 // For NEON intrinsics which take an immediate value as part of the 1547 // instruction, range check them here. 1548 unsigned i = 0, l = 0, u = 0; 1549 switch (BuiltinID) { 1550 default: 1551 return false; 1552 #define GET_NEON_IMMEDIATE_CHECK 1553 #include "clang/Basic/arm_neon.inc" 1554 #include "clang/Basic/arm_fp16.inc" 1555 #undef GET_NEON_IMMEDIATE_CHECK 1556 } 1557 1558 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1559 } 1560 1561 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1562 unsigned MaxWidth) { 1563 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1564 BuiltinID == ARM::BI__builtin_arm_ldaex || 1565 BuiltinID == ARM::BI__builtin_arm_strex || 1566 BuiltinID == ARM::BI__builtin_arm_stlex || 1567 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1568 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1569 BuiltinID == AArch64::BI__builtin_arm_strex || 1570 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1571 "unexpected ARM builtin"); 1572 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1573 BuiltinID == ARM::BI__builtin_arm_ldaex || 1574 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1575 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1576 1577 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1578 1579 // Ensure that we have the proper number of arguments. 1580 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1581 return true; 1582 1583 // Inspect the pointer argument of the atomic builtin. This should always be 1584 // a pointer type, whose element is an integral scalar or pointer type. 1585 // Because it is a pointer type, we don't have to worry about any implicit 1586 // casts here. 1587 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1588 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1589 if (PointerArgRes.isInvalid()) 1590 return true; 1591 PointerArg = PointerArgRes.get(); 1592 1593 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1594 if (!pointerType) { 1595 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1596 << PointerArg->getType() << PointerArg->getSourceRange(); 1597 return true; 1598 } 1599 1600 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1601 // task is to insert the appropriate casts into the AST. First work out just 1602 // what the appropriate type is. 1603 QualType ValType = pointerType->getPointeeType(); 1604 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1605 if (IsLdrex) 1606 AddrType.addConst(); 1607 1608 // Issue a warning if the cast is dodgy. 1609 CastKind CastNeeded = CK_NoOp; 1610 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1611 CastNeeded = CK_BitCast; 1612 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1613 << PointerArg->getType() << Context.getPointerType(AddrType) 1614 << AA_Passing << PointerArg->getSourceRange(); 1615 } 1616 1617 // Finally, do the cast and replace the argument with the corrected version. 1618 AddrType = Context.getPointerType(AddrType); 1619 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1620 if (PointerArgRes.isInvalid()) 1621 return true; 1622 PointerArg = PointerArgRes.get(); 1623 1624 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1625 1626 // In general, we allow ints, floats and pointers to be loaded and stored. 1627 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1628 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1629 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1630 << PointerArg->getType() << PointerArg->getSourceRange(); 1631 return true; 1632 } 1633 1634 // But ARM doesn't have instructions to deal with 128-bit versions. 1635 if (Context.getTypeSize(ValType) > MaxWidth) { 1636 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1637 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1638 << PointerArg->getType() << PointerArg->getSourceRange(); 1639 return true; 1640 } 1641 1642 switch (ValType.getObjCLifetime()) { 1643 case Qualifiers::OCL_None: 1644 case Qualifiers::OCL_ExplicitNone: 1645 // okay 1646 break; 1647 1648 case Qualifiers::OCL_Weak: 1649 case Qualifiers::OCL_Strong: 1650 case Qualifiers::OCL_Autoreleasing: 1651 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1652 << ValType << PointerArg->getSourceRange(); 1653 return true; 1654 } 1655 1656 if (IsLdrex) { 1657 TheCall->setType(ValType); 1658 return false; 1659 } 1660 1661 // Initialize the argument to be stored. 1662 ExprResult ValArg = TheCall->getArg(0); 1663 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1664 Context, ValType, /*consume*/ false); 1665 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1666 if (ValArg.isInvalid()) 1667 return true; 1668 TheCall->setArg(0, ValArg.get()); 1669 1670 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1671 // but the custom checker bypasses all default analysis. 1672 TheCall->setType(Context.IntTy); 1673 return false; 1674 } 1675 1676 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1677 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1678 BuiltinID == ARM::BI__builtin_arm_ldaex || 1679 BuiltinID == ARM::BI__builtin_arm_strex || 1680 BuiltinID == ARM::BI__builtin_arm_stlex) { 1681 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1682 } 1683 1684 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1685 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1686 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1687 } 1688 1689 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1690 BuiltinID == ARM::BI__builtin_arm_wsr64) 1691 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1692 1693 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1694 BuiltinID == ARM::BI__builtin_arm_rsrp || 1695 BuiltinID == ARM::BI__builtin_arm_wsr || 1696 BuiltinID == ARM::BI__builtin_arm_wsrp) 1697 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1698 1699 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1700 return true; 1701 1702 // For intrinsics which take an immediate value as part of the instruction, 1703 // range check them here. 1704 // FIXME: VFP Intrinsics should error if VFP not present. 1705 switch (BuiltinID) { 1706 default: return false; 1707 case ARM::BI__builtin_arm_ssat: 1708 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1709 case ARM::BI__builtin_arm_usat: 1710 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1711 case ARM::BI__builtin_arm_ssat16: 1712 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1713 case ARM::BI__builtin_arm_usat16: 1714 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1715 case ARM::BI__builtin_arm_vcvtr_f: 1716 case ARM::BI__builtin_arm_vcvtr_d: 1717 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1718 case ARM::BI__builtin_arm_dmb: 1719 case ARM::BI__builtin_arm_dsb: 1720 case ARM::BI__builtin_arm_isb: 1721 case ARM::BI__builtin_arm_dbg: 1722 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1723 } 1724 } 1725 1726 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1727 CallExpr *TheCall) { 1728 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1729 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1730 BuiltinID == AArch64::BI__builtin_arm_strex || 1731 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1732 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1733 } 1734 1735 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1736 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1737 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1738 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1739 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1740 } 1741 1742 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1743 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1744 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1745 1746 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1747 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1748 BuiltinID == AArch64::BI__builtin_arm_wsr || 1749 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1750 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1751 1752 // Only check the valid encoding range. Any constant in this range would be 1753 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1754 // an exception for incorrect registers. This matches MSVC behavior. 1755 if (BuiltinID == AArch64::BI_ReadStatusReg || 1756 BuiltinID == AArch64::BI_WriteStatusReg) 1757 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1758 1759 if (BuiltinID == AArch64::BI__getReg) 1760 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1761 1762 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1763 return true; 1764 1765 // For intrinsics which take an immediate value as part of the instruction, 1766 // range check them here. 1767 unsigned i = 0, l = 0, u = 0; 1768 switch (BuiltinID) { 1769 default: return false; 1770 case AArch64::BI__builtin_arm_dmb: 1771 case AArch64::BI__builtin_arm_dsb: 1772 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1773 } 1774 1775 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1776 } 1777 1778 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1779 static const std::map<unsigned, std::vector<StringRef>> ValidCPU = { 1780 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, {"v65"} }, 1781 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, {"v62", "v65"} }, 1782 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, {"v62", "v65"} }, 1783 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, {"v62", "v65"} }, 1784 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {"v60", "v62", "v65"} }, 1785 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {"v60", "v62", "v65"} }, 1786 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {"v60", "v62", "v65"} }, 1787 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {"v60", "v62", "v65"} }, 1788 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {"v60", "v62", "v65"} }, 1789 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {"v60", "v62", "v65"} }, 1790 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {"v60", "v62", "v65"} }, 1791 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {"v60", "v62", "v65"} }, 1792 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {"v60", "v62", "v65"} }, 1793 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {"v60", "v62", "v65"} }, 1794 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {"v60", "v62", "v65"} }, 1795 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {"v60", "v62", "v65"} }, 1796 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, {"v62", "v65"} }, 1797 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, {"v62", "v65"} }, 1798 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, {"v62", "v65"} }, 1799 }; 1800 1801 static const std::map<unsigned, std::vector<StringRef>> ValidHVX = { 1802 { Hexagon::BI__builtin_HEXAGON_V6_extractw, {"v60", "v62", "v65"} }, 1803 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, {"v60", "v62", "v65"} }, 1804 { Hexagon::BI__builtin_HEXAGON_V6_hi, {"v60", "v62", "v65"} }, 1805 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, {"v60", "v62", "v65"} }, 1806 { Hexagon::BI__builtin_HEXAGON_V6_lo, {"v60", "v62", "v65"} }, 1807 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, {"v60", "v62", "v65"} }, 1808 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, {"v62", "v65"} }, 1809 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, {"v62", "v65"} }, 1810 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, {"v62", "v65"} }, 1811 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, {"v62", "v65"} }, 1812 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, {"v60", "v62", "v65"} }, 1813 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, {"v60", "v62", "v65"} }, 1814 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, {"v60", "v62", "v65"} }, 1815 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, {"v60", "v62", "v65"} }, 1816 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, {"v60", "v62", "v65"} }, 1817 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, {"v60", "v62", "v65"} }, 1818 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, {"v60", "v62", "v65"} }, 1819 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, {"v60", "v62", "v65"} }, 1820 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, {"v60", "v62", "v65"} }, 1821 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, {"v60", "v62", "v65"} }, 1822 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, {"v60", "v62", "v65"} }, 1823 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, {"v60", "v62", "v65"} }, 1824 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, {"v60", "v62", "v65"} }, 1825 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, {"v60", "v62", "v65"} }, 1826 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, {"v62", "v65"} }, 1827 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, {"v62", "v65"} }, 1828 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, {"v60", "v62", "v65"} }, 1829 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, {"v60", "v62", "v65"} }, 1830 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, {"v62", "v65"} }, 1831 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, {"v62", "v65"} }, 1832 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, {"v62", "v65"} }, 1833 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, {"v62", "v65"} }, 1834 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, {"v65"} }, 1835 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, {"v65"} }, 1836 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, {"v65"} }, 1837 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, {"v65"} }, 1838 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, {"v60", "v62", "v65"} }, 1839 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, {"v60", "v62", "v65"} }, 1840 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, {"v60", "v62", "v65"} }, 1841 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, {"v60", "v62", "v65"} }, 1842 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, {"v60", "v62", "v65"} }, 1843 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, {"v60", "v62", "v65"} }, 1844 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, {"v60", "v62", "v65"} }, 1845 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, {"v60", "v62", "v65"} }, 1846 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, {"v60", "v62", "v65"} }, 1847 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, {"v60", "v62", "v65"} }, 1848 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, {"v60", "v62", "v65"} }, 1849 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, {"v60", "v62", "v65"} }, 1850 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, {"v60", "v62", "v65"} }, 1851 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, {"v60", "v62", "v65"} }, 1852 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, {"v60", "v62", "v65"} }, 1853 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, {"v60", "v62", "v65"} }, 1854 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, {"v60", "v62", "v65"} }, 1855 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, {"v60", "v62", "v65"} }, 1856 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, {"v60", "v62", "v65"} }, 1857 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, {"v60", "v62", "v65"} }, 1858 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, {"v62", "v65"} }, 1859 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, {"v62", "v65"} }, 1860 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, {"v62", "v65"} }, 1861 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, {"v62", "v65"} }, 1862 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, {"v62", "v65"} }, 1863 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, {"v62", "v65"} }, 1864 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, {"v62", "v65"} }, 1865 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, {"v62", "v65"} }, 1866 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, {"v62", "v65"} }, 1867 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, {"v62", "v65"} }, 1868 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, {"v60", "v62", "v65"} }, 1869 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, {"v60", "v62", "v65"} }, 1870 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, {"v60", "v62", "v65"} }, 1871 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, {"v60", "v62", "v65"} }, 1872 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, {"v60", "v62", "v65"} }, 1873 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, {"v60", "v62", "v65"} }, 1874 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, {"v60", "v62", "v65"} }, 1875 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, {"v60", "v62", "v65"} }, 1876 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, {"v60", "v62", "v65"} }, 1877 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, {"v60", "v62", "v65"} }, 1878 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, {"v62", "v65"} }, 1879 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, {"v62", "v65"} }, 1880 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, {"v60", "v62", "v65"} }, 1881 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, {"v60", "v62", "v65"} }, 1882 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, {"v62", "v65"} }, 1883 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, {"v62", "v65"} }, 1884 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, {"v60", "v62", "v65"} }, 1885 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, {"v60", "v62", "v65"} }, 1886 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, {"v60", "v62", "v65"} }, 1887 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, {"v60", "v62", "v65"} }, 1888 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, {"v62", "v65"} }, 1889 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, {"v62", "v65"} }, 1890 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, {"v60", "v62", "v65"} }, 1891 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, {"v60", "v62", "v65"} }, 1892 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, {"v60", "v62", "v65"} }, 1893 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, {"v60", "v62", "v65"} }, 1894 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, {"v60", "v62", "v65"} }, 1895 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, {"v60", "v62", "v65"} }, 1896 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, {"v62", "v65"} }, 1897 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, {"v62", "v65"} }, 1898 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, {"v62", "v65"} }, 1899 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, {"v62", "v65"} }, 1900 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, {"v62", "v65"} }, 1901 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, {"v62", "v65"} }, 1902 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, {"v60", "v62", "v65"} }, 1903 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, {"v60", "v62", "v65"} }, 1904 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, {"v60", "v62", "v65"} }, 1905 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, {"v60", "v62", "v65"} }, 1906 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, {"v60", "v62", "v65"} }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, {"v60", "v62", "v65"} }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, {"v60", "v62", "v65"} }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, {"v60", "v62", "v65"} }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_valignb, {"v60", "v62", "v65"} }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, {"v60", "v62", "v65"} }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {"v60", "v62", "v65"} }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {"v60", "v62", "v65"} }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vand, {"v60", "v62", "v65"} }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, {"v60", "v62", "v65"} }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, {"v62", "v65"} }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, {"v62", "v65"} }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, {"v62", "v65"} }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, {"v62", "v65"} }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, {"v60", "v62", "v65"} }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, {"v60", "v62", "v65"} }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, {"v60", "v62", "v65"} }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, {"v60", "v62", "v65"} }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, {"v62", "v65"} }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, {"v62", "v65"} }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, {"v62", "v65"} }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, {"v62", "v65"} }, 1928 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, {"v60", "v62", "v65"} }, 1929 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, {"v60", "v62", "v65"} }, 1930 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, {"v60", "v62", "v65"} }, 1931 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, {"v60", "v62", "v65"} }, 1932 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, {"v60", "v62", "v65"} }, 1933 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, {"v60", "v62", "v65"} }, 1934 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, {"v65"} }, 1935 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, {"v65"} }, 1936 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, {"v60", "v62", "v65"} }, 1937 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, {"v60", "v62", "v65"} }, 1938 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, {"v60", "v62", "v65"} }, 1939 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, {"v60", "v62", "v65"} }, 1940 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, {"v60", "v62", "v65"} }, 1941 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, {"v60", "v62", "v65"} }, 1942 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, {"v60", "v62", "v65"} }, 1943 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, {"v60", "v62", "v65"} }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, {"v60", "v62", "v65"} }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, {"v60", "v62", "v65"} }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, {"v65"} }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, {"v65"} }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, {"v60", "v62", "v65"} }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, {"v60", "v62", "v65"} }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, {"v62", "v65"} }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, {"v62", "v65"} }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, {"v60", "v62", "v65"} }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, {"v60", "v62", "v65"} }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, {"v60", "v62", "v65"} }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, {"v60", "v62", "v65"} }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, {"v60", "v62", "v65"} }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, {"v60", "v62", "v65"} }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, {"v65"} }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, {"v65"} }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, {"v65"} }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, {"v65"} }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, {"v62", "v65"} }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, {"v62", "v65"} }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, {"v65"} }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, {"v65"} }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, {"v60", "v62", "v65"} }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, {"v60", "v62", "v65"} }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, {"v60", "v62", "v65"} }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, {"v60", "v62", "v65"} }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, {"v60", "v62", "v65"} }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, {"v60", "v62", "v65"} }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, {"v60", "v62", "v65"} }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, {"v60", "v62", "v65"} }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, {"v60", "v62", "v65"} }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, {"v60", "v62", "v65"} }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, {"v62", "v65"} }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, {"v62", "v65"} }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, {"v60", "v62", "v65"} }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, {"v60", "v62", "v65"} }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, {"v60", "v62", "v65"} }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, {"v60", "v62", "v65"} }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vassign, {"v60", "v62", "v65"} }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, {"v60", "v62", "v65"} }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, {"v60", "v62", "v65"} }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, {"v60", "v62", "v65"} }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, {"v65"} }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, {"v65"} }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, {"v65"} }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, {"v65"} }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, {"v60", "v62", "v65"} }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, {"v60", "v62", "v65"} }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, {"v60", "v62", "v65"} }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, {"v60", "v62", "v65"} }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, {"v60", "v62", "v65"} }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, {"v60", "v62", "v65"} }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, {"v60", "v62", "v65"} }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, {"v60", "v62", "v65"} }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, {"v60", "v62", "v65"} }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, {"v60", "v62", "v65"} }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, {"v60", "v62", "v65"} }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, {"v60", "v62", "v65"} }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, {"v65"} }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, {"v65"} }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, {"v65"} }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, {"v65"} }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, {"v60", "v62", "v65"} }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, {"v60", "v62", "v65"} }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, {"v60", "v62", "v65"} }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, {"v60", "v62", "v65"} }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, {"v60", "v62", "v65"} }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, {"v60", "v62", "v65"} }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, {"v60", "v62", "v65"} }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, {"v60", "v62", "v65"} }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, {"v60", "v62", "v65"} }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, {"v60", "v62", "v65"} }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vd0, {"v60", "v62", "v65"} }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, {"v60", "v62", "v65"} }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, {"v65"} }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, {"v65"} }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, {"v60", "v62", "v65"} }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, {"v60", "v62", "v65"} }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, {"v60", "v62", "v65"} }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, {"v60", "v62", "v65"} }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, {"v60", "v62", "v65"} }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, {"v60", "v62", "v65"} }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, {"v60", "v62", "v65"} }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, {"v60", "v62", "v65"} }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, {"v60", "v62", "v65"} }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, {"v60", "v62", "v65"} }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, {"v60", "v62", "v65"} }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, {"v60", "v62", "v65"} }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, {"v60", "v62", "v65"} }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, {"v60", "v62", "v65"} }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, {"v60", "v62", "v65"} }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, {"v60", "v62", "v65"} }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, {"v60", "v62", "v65"} }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, {"v60", "v62", "v65"} }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, {"v60", "v62", "v65"} }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, {"v60", "v62", "v65"} }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, {"v60", "v62", "v65"} }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, {"v60", "v62", "v65"} }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, {"v60", "v62", "v65"} }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, {"v60", "v62", "v65"} }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, {"v60", "v62", "v65"} }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, {"v60", "v62", "v65"} }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, {"v60", "v62", "v65"} }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, {"v60", "v62", "v65"} }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, {"v60", "v62", "v65"} }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, {"v60", "v62", "v65"} }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, {"v60", "v62", "v65"} }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, {"v60", "v62", "v65"} }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, {"v60", "v62", "v65"} }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, {"v60", "v62", "v65"} }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, {"v60", "v62", "v65"} }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, {"v60", "v62", "v65"} }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, {"v60", "v62", "v65"} }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, {"v60", "v62", "v65"} }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, {"v60", "v62", "v65"} }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, {"v60", "v62", "v65"} }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, {"v60", "v62", "v65"} }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, {"v60", "v62", "v65"} }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, {"v60", "v62", "v65"} }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, {"v60", "v62", "v65"} }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, {"v60", "v62", "v65"} }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, {"v60", "v62", "v65"} }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, {"v60", "v62", "v65"} }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, {"v60", "v62", "v65"} }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, {"v60", "v62", "v65"} }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, {"v60", "v62", "v65"} }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_veqb, {"v60", "v62", "v65"} }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, {"v60", "v62", "v65"} }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, {"v60", "v62", "v65"} }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, {"v60", "v62", "v65"} }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, {"v60", "v62", "v65"} }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, {"v60", "v62", "v65"} }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, {"v60", "v62", "v65"} }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, {"v60", "v62", "v65"} }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_veqh, {"v60", "v62", "v65"} }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, {"v60", "v62", "v65"} }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, {"v60", "v62", "v65"} }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, {"v60", "v62", "v65"} }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, {"v60", "v62", "v65"} }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, {"v60", "v62", "v65"} }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, {"v60", "v62", "v65"} }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, {"v60", "v62", "v65"} }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_veqw, {"v60", "v62", "v65"} }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, {"v60", "v62", "v65"} }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, {"v60", "v62", "v65"} }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, {"v60", "v62", "v65"} }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, {"v60", "v62", "v65"} }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, {"v60", "v62", "v65"} }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, {"v60", "v62", "v65"} }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, {"v60", "v62", "v65"} }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, {"v60", "v62", "v65"} }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, {"v60", "v62", "v65"} }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, {"v60", "v62", "v65"} }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, {"v60", "v62", "v65"} }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, {"v60", "v62", "v65"} }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, {"v60", "v62", "v65"} }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, {"v60", "v62", "v65"} }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, {"v60", "v62", "v65"} }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vgth, {"v60", "v62", "v65"} }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, {"v60", "v62", "v65"} }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, {"v60", "v62", "v65"} }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, {"v60", "v62", "v65"} }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, {"v60", "v62", "v65"} }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, {"v60", "v62", "v65"} }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, {"v60", "v62", "v65"} }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, {"v60", "v62", "v65"} }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, {"v60", "v62", "v65"} }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, {"v60", "v62", "v65"} }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, {"v60", "v62", "v65"} }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, {"v60", "v62", "v65"} }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, {"v60", "v62", "v65"} }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, {"v60", "v62", "v65"} }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, {"v60", "v62", "v65"} }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, {"v60", "v62", "v65"} }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, {"v60", "v62", "v65"} }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, {"v60", "v62", "v65"} }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, {"v60", "v62", "v65"} }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, {"v60", "v62", "v65"} }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, {"v60", "v62", "v65"} }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, {"v60", "v62", "v65"} }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, {"v60", "v62", "v65"} }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, {"v60", "v62", "v65"} }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, {"v60", "v62", "v65"} }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, {"v60", "v62", "v65"} }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, {"v60", "v62", "v65"} }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, {"v60", "v62", "v65"} }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, {"v60", "v62", "v65"} }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, {"v60", "v62", "v65"} }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, {"v60", "v62", "v65"} }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, {"v60", "v62", "v65"} }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, {"v60", "v62", "v65"} }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, {"v60", "v62", "v65"} }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, {"v60", "v62", "v65"} }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, {"v60", "v62", "v65"} }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, {"v60", "v62", "v65"} }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, {"v60", "v62", "v65"} }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, {"v60", "v62", "v65"} }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, {"v60", "v62", "v65"} }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, {"v60", "v62", "v65"} }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, {"v60", "v62", "v65"} }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, {"v60", "v62", "v65"} }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, {"v60", "v62", "v65"} }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {"v60", "v62", "v65"} }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {"v60", "v62", "v65"} }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, {"v62", "v65"} }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, {"v62", "v65"} }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, {"v60", "v62", "v65"} }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, {"v60", "v62", "v65"} }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, {"v60", "v62", "v65"} }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, {"v60", "v62", "v65"} }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, {"v60", "v62", "v65"} }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, {"v60", "v62", "v65"} }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, {"v60", "v62", "v65"} }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, {"v60", "v62", "v65"} }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, {"v65"} }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, {"v65"} }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, {"v60", "v62", "v65"} }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, {"v60", "v62", "v65"} }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {"v62", "v65"} }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {"v62", "v65"} }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, {"v62", "v65"} }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, {"v62", "v65"} }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, {"v60", "v62", "v65"} }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, {"v60", "v62", "v65"} }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {"v62", "v65"} }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, {"v62", "v65"} }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, {"v60", "v62", "v65"} }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, {"v60", "v62", "v65"} }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {"v62", "v65"} }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {"v62", "v65"} }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, {"v62", "v65"} }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, {"v62", "v65"} }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, {"v60", "v62", "v65"} }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, {"v60", "v62", "v65"} }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {"v62", "v65"} }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, {"v62", "v65"} }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, {"v62", "v65"} }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, {"v62", "v65"} }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, {"v60", "v62", "v65"} }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, {"v60", "v62", "v65"} }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, {"v60", "v62", "v65"} }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, {"v60", "v62", "v65"} }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, {"v60", "v62", "v65"} }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, {"v60", "v62", "v65"} }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, {"v60", "v62", "v65"} }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, {"v60", "v62", "v65"} }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vminb, {"v62", "v65"} }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, {"v62", "v65"} }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vminh, {"v60", "v62", "v65"} }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, {"v60", "v62", "v65"} }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vminub, {"v60", "v62", "v65"} }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, {"v60", "v62", "v65"} }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, {"v60", "v62", "v65"} }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, {"v60", "v62", "v65"} }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vminw, {"v60", "v62", "v65"} }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, {"v60", "v62", "v65"} }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, {"v60", "v62", "v65"} }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, {"v60", "v62", "v65"} }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, {"v60", "v62", "v65"} }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, {"v60", "v62", "v65"} }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, {"v60", "v62", "v65"} }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, {"v60", "v62", "v65"} }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, {"v65"} }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, {"v65"} }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, {"v65"} }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, {"v65"} }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, {"v60", "v62", "v65"} }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, {"v60", "v62", "v65"} }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, {"v60", "v62", "v65"} }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, {"v60", "v62", "v65"} }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, {"v60", "v62", "v65"} }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, {"v60", "v62", "v65"} }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, {"v65"} }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, {"v65"} }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, {"v62", "v65"} }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, {"v62", "v65"} }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, {"v62", "v65"} }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, {"v62", "v65"} }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, {"v65"} }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, {"v65"} }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, {"v65"} }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, {"v65"} }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, {"v60", "v62", "v65"} }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, {"v60", "v62", "v65"} }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, {"v60", "v62", "v65"} }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, {"v60", "v62", "v65"} }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, {"v60", "v62", "v65"} }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, {"v60", "v62", "v65"} }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, {"v60", "v62", "v65"} }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, {"v60", "v62", "v65"} }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, {"v60", "v62", "v65"} }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, {"v60", "v62", "v65"} }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, {"v60", "v62", "v65"} }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, {"v60", "v62", "v65"} }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, {"v60", "v62", "v65"} }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, {"v60", "v62", "v65"} }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, {"v62", "v65"} }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, {"v62", "v65"} }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, {"v60", "v62", "v65"} }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, {"v60", "v62", "v65"} }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, {"v65"} }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, {"v65"} }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, {"v60", "v62", "v65"} }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, {"v60", "v62", "v65"} }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, {"v60", "v62", "v65"} }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, {"v60", "v62", "v65"} }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, {"v60", "v62", "v65"} }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, {"v60", "v62", "v65"} }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, {"v60", "v62", "v65"} }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, {"v60", "v62", "v65"} }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, {"v60", "v62", "v65"} }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, {"v60", "v62", "v65"} }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, {"v60", "v62", "v65"} }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, {"v60", "v62", "v65"} }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, {"v60", "v62", "v65"} }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, {"v60", "v62", "v65"} }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, {"v60", "v62", "v65"} }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, {"v60", "v62", "v65"} }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, {"v60", "v62", "v65"} }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, {"v60", "v62", "v65"} }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, {"v60", "v62", "v65"} }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, {"v60", "v62", "v65"} }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, {"v60", "v62", "v65"} }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, {"v60", "v62", "v65"} }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, {"v60", "v62", "v65"} }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, {"v60", "v62", "v65"} }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, {"v60", "v62", "v65"} }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, {"v60", "v62", "v65"} }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, {"v60", "v62", "v65"} }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, {"v60", "v62", "v65"} }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, {"v60", "v62", "v65"} }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, {"v60", "v62", "v65"} }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, {"v60", "v62", "v65"} }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, {"v60", "v62", "v65"} }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, {"v60", "v62", "v65"} }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, {"v60", "v62", "v65"} }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, {"v60", "v62", "v65"} }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, {"v60", "v62", "v65"} }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, {"v60", "v62", "v65"} }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, {"v60", "v62", "v65"} }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, {"v60", "v62", "v65"} }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, {"v60", "v62", "v65"} }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, {"v60", "v62", "v65"} }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, {"v60", "v62", "v65"} }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, {"v62", "v65"} }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, {"v62", "v65"} }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, {"v62", "v65"} }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, {"v62", "v65"} }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, {"v60", "v62", "v65"} }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, {"v60", "v62", "v65"} }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, {"v62", "v65"} }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, {"v62", "v65"} }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, {"v60", "v62", "v65"} }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, {"v60", "v62", "v65"} }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, {"v60", "v62", "v65"} }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, {"v60", "v62", "v65"} }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, {"v60", "v62", "v65"} }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, {"v60", "v62", "v65"} }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, {"v60", "v62", "v65"} }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, {"v60", "v62", "v65"} }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, {"v60", "v62", "v65"} }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, {"v60", "v62", "v65"} }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, {"v60", "v62", "v65"} }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, {"v60", "v62", "v65"} }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, {"v60", "v62", "v65"} }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, {"v60", "v62", "v65"} }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, {"v60", "v62", "v65"} }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, {"v60", "v62", "v65"} }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, {"v60", "v62", "v65"} }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, {"v60", "v62", "v65"} }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, {"v65"} }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, {"v65"} }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, {"v65"} }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, {"v65"} }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, {"v60", "v62", "v65"} }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, {"v60", "v62", "v65"} }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, {"v60", "v62", "v65"} }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, {"v60", "v62", "v65"} }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vmux, {"v60", "v62", "v65"} }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, {"v60", "v62", "v65"} }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, {"v65"} }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, {"v65"} }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, {"v60", "v62", "v65"} }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, {"v60", "v62", "v65"} }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, {"v60", "v62", "v65"} }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, {"v60", "v62", "v65"} }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, {"v60", "v62", "v65"} }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, {"v60", "v62", "v65"} }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, {"v60", "v62", "v65"} }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, {"v60", "v62", "v65"} }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, {"v60", "v62", "v65"} }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, {"v60", "v62", "v65"} }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vnot, {"v60", "v62", "v65"} }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, {"v60", "v62", "v65"} }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vor, {"v60", "v62", "v65"} }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, {"v60", "v62", "v65"} }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, {"v60", "v62", "v65"} }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, {"v60", "v62", "v65"} }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, {"v60", "v62", "v65"} }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, {"v60", "v62", "v65"} }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, {"v60", "v62", "v65"} }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, {"v60", "v62", "v65"} }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, {"v60", "v62", "v65"} }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, {"v60", "v62", "v65"} }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, {"v60", "v62", "v65"} }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, {"v60", "v62", "v65"} }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, {"v60", "v62", "v65"} }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, {"v60", "v62", "v65"} }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, {"v60", "v62", "v65"} }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, {"v60", "v62", "v65"} }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, {"v60", "v62", "v65"} }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, {"v60", "v62", "v65"} }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, {"v60", "v62", "v65"} }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, {"v60", "v62", "v65"} }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, {"v65"} }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, {"v65"} }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, {"v65"} }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, {"v65"} }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, {"v65"} }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, {"v65"} }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, {"v60", "v62", "v65"} }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, {"v60", "v62", "v65"} }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, {"v65"} }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, {"v65"} }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, {"v65"} }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, {"v65"} }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, {"v60", "v62", "v65"} }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, {"v60", "v62", "v65"} }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, {"v60", "v62", "v65"} }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, {"v60", "v62", "v65"} }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {"v60", "v62", "v65"} }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {"v60", "v62", "v65"} }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {"v60", "v62", "v65"} }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, {"v60", "v62", "v65"} }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, {"v60", "v62", "v65"} }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, {"v60", "v62", "v65"} }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, {"v60", "v62", "v65"} }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, {"v60", "v62", "v65"} }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, {"v60", "v62", "v65"} }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, {"v60", "v62", "v65"} }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, {"v60", "v62", "v65"} }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, {"v60", "v62", "v65"} }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, {"v60", "v62", "v65"} }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, {"v60", "v62", "v65"} }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, {"v60", "v62", "v65"} }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, {"v60", "v62", "v65"} }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {"v60", "v62", "v65"} }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {"v60", "v62", "v65"} }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {"v60", "v62", "v65"} }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, {"v60", "v62", "v65"} }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, {"v65"} }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, {"v65"} }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, {"v65"} }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, {"v65"} }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, {"v60", "v62", "v65"} }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, {"v60", "v62", "v65"} }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, {"v60", "v62", "v65"} }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, {"v60", "v62", "v65"} }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vror, {"v60", "v62", "v65"} }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, {"v60", "v62", "v65"} }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, {"v60", "v62", "v65"} }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, {"v60", "v62", "v65"} }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, {"v60", "v62", "v65"} }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, {"v60", "v62", "v65"} }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, {"v62", "v65"} }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, {"v62", "v65"} }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, {"v62", "v65"} }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, {"v62", "v65"} }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, {"v60", "v62", "v65"} }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, {"v60", "v62", "v65"} }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, {"v60", "v62", "v65"} }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, {"v60", "v62", "v65"} }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {"v60", "v62", "v65"} }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {"v60", "v62", "v65"} }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {"v60", "v62", "v65"} }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, {"v60", "v62", "v65"} }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, {"v60", "v62", "v65"} }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, {"v60", "v62", "v65"} }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, {"v62", "v65"} }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, {"v62", "v65"} }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, {"v60", "v62", "v65"} }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, {"v60", "v62", "v65"} }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vsb, {"v60", "v62", "v65"} }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, {"v60", "v62", "v65"} }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vsh, {"v60", "v62", "v65"} }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, {"v60", "v62", "v65"} }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, {"v60", "v62", "v65"} }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, {"v60", "v62", "v65"} }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, {"v60", "v62", "v65"} }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, {"v60", "v62", "v65"} }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, {"v60", "v62", "v65"} }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, {"v60", "v62", "v65"} }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, {"v60", "v62", "v65"} }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, {"v60", "v62", "v65"} }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, {"v60", "v62", "v65"} }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, {"v60", "v62", "v65"} }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, {"v60", "v62", "v65"} }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, {"v60", "v62", "v65"} }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, {"v60", "v62", "v65"} }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, {"v60", "v62", "v65"} }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, {"v60", "v62", "v65"} }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, {"v60", "v62", "v65"} }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, {"v60", "v62", "v65"} }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, {"v60", "v62", "v65"} }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, {"v60", "v62", "v65"} }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, {"v60", "v62", "v65"} }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, {"v60", "v62", "v65"} }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, {"v60", "v62", "v65"} }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, {"v62", "v65"} }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, {"v62", "v65"} }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, {"v62", "v65"} }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, {"v62", "v65"} }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, {"v62", "v65"} }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, {"v62", "v65"} }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, {"v60", "v62", "v65"} }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, {"v60", "v62", "v65"} }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, {"v60", "v62", "v65"} }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, {"v60", "v62", "v65"} }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, {"v60", "v62", "v65"} }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, {"v60", "v62", "v65"} }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, {"v60", "v62", "v65"} }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, {"v60", "v62", "v65"} }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, {"v60", "v62", "v65"} }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, {"v60", "v62", "v65"} }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, {"v60", "v62", "v65"} }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, {"v60", "v62", "v65"} }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, {"v60", "v62", "v65"} }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, {"v60", "v62", "v65"} }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, {"v60", "v62", "v65"} }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, {"v60", "v62", "v65"} }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, {"v62", "v65"} }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, {"v62", "v65"} }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, {"v60", "v62", "v65"} }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, {"v60", "v62", "v65"} }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, {"v60", "v62", "v65"} }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, {"v60", "v62", "v65"} }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, {"v60", "v62", "v65"} }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, {"v60", "v62", "v65"} }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, {"v62", "v65"} }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, {"v62", "v65"} }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, {"v62", "v65"} }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, {"v62", "v65"} }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, {"v60", "v62", "v65"} }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, {"v60", "v62", "v65"} }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, {"v60", "v62", "v65"} }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, {"v60", "v62", "v65"} }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, {"v60", "v62", "v65"} }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, {"v60", "v62", "v65"} }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, {"v60", "v62", "v65"} }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, {"v60", "v62", "v65"} }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vswap, {"v60", "v62", "v65"} }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, {"v60", "v62", "v65"} }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, {"v60", "v62", "v65"} }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, {"v60", "v62", "v65"} }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, {"v60", "v62", "v65"} }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, {"v60", "v62", "v65"} }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, {"v60", "v62", "v65"} }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, {"v60", "v62", "v65"} }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, {"v60", "v62", "v65"} }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, {"v60", "v62", "v65"} }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, {"v60", "v62", "v65"} }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, {"v60", "v62", "v65"} }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, {"v60", "v62", "v65"} }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, {"v60", "v62", "v65"} }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, {"v60", "v62", "v65"} }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, {"v60", "v62", "v65"} }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, {"v60", "v62", "v65"} }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, {"v60", "v62", "v65"} }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, {"v60", "v62", "v65"} }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, {"v60", "v62", "v65"} }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, {"v60", "v62", "v65"} }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, {"v60", "v62", "v65"} }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, {"v60", "v62", "v65"} }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, {"v60", "v62", "v65"} }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, {"v60", "v62", "v65"} }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, {"v60", "v62", "v65"} }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vxor, {"v60", "v62", "v65"} }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, {"v60", "v62", "v65"} }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vzb, {"v60", "v62", "v65"} }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, {"v60", "v62", "v65"} }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vzh, {"v60", "v62", "v65"} }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, {"v60", "v62", "v65"} }, 2526 }; 2527 2528 const TargetInfo &TI = Context.getTargetInfo(); 2529 2530 auto FC = ValidCPU.find(BuiltinID); 2531 if (FC != ValidCPU.end()) { 2532 const TargetOptions &Opts = TI.getTargetOpts(); 2533 StringRef CPU = Opts.CPU; 2534 if (!CPU.empty()) { 2535 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2536 CPU.consume_front("hexagon"); 2537 if (llvm::none_of(FC->second, [CPU](StringRef S) { return S == CPU; })) 2538 return Diag(TheCall->getBeginLoc(), 2539 diag::err_hexagon_builtin_unsupported_cpu); 2540 } 2541 } 2542 2543 auto FH = ValidHVX.find(BuiltinID); 2544 if (FH != ValidHVX.end()) { 2545 if (!TI.hasFeature("hvx")) 2546 return Diag(TheCall->getBeginLoc(), 2547 diag::err_hexagon_builtin_requires_hvx); 2548 2549 bool IsValid = llvm::any_of(FH->second, 2550 [&TI] (StringRef V) { 2551 std::string F = "hvx" + V.str(); 2552 return TI.hasFeature(F); 2553 }); 2554 if (!IsValid) 2555 return Diag(TheCall->getBeginLoc(), 2556 diag::err_hexagon_builtin_unsupported_hvx); 2557 } 2558 2559 return false; 2560 } 2561 2562 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2563 struct ArgInfo { 2564 ArgInfo(unsigned O, bool S, unsigned W, unsigned A) 2565 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {} 2566 unsigned OpNum = 0; 2567 bool IsSigned = false; 2568 unsigned BitWidth = 0; 2569 unsigned Align = 0; 2570 }; 2571 2572 static const std::map<unsigned, std::vector<ArgInfo>> Infos = { 2573 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2574 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2575 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2576 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2577 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2578 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2579 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2580 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2581 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2582 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2583 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2584 2585 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2588 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2589 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2593 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2596 2597 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2598 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2599 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2600 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2601 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2602 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2603 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2604 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2605 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2606 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2607 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2608 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2609 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2610 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2611 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2612 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2613 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2615 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2616 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2617 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2618 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2619 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2620 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2621 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2622 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2624 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2625 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2648 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2649 {{ 1, false, 6, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2657 {{ 1, false, 5, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2664 { 2, false, 5, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2666 { 2, false, 6, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2668 { 3, false, 5, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2670 { 3, false, 6, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2687 {{ 2, false, 4, 0 }, 2688 { 3, false, 5, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2690 {{ 2, false, 4, 0 }, 2691 { 3, false, 5, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2693 {{ 2, false, 4, 0 }, 2694 { 3, false, 5, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2696 {{ 2, false, 4, 0 }, 2697 { 3, false, 5, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2709 { 2, false, 5, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2711 { 2, false, 6, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2721 {{ 1, false, 4, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2724 {{ 1, false, 4, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2745 {{ 3, false, 1, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2749 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2750 {{ 3, false, 1, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2755 {{ 3, false, 1, 0 }} }, 2756 }; 2757 2758 auto F = Infos.find(BuiltinID); 2759 if (F == Infos.end()) 2760 return false; 2761 2762 bool Error = false; 2763 2764 for (const ArgInfo &A : F->second) { 2765 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0; 2766 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1; 2767 if (!A.Align) { 2768 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2769 } else { 2770 unsigned M = 1 << A.Align; 2771 Min *= M; 2772 Max *= M; 2773 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2774 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2775 } 2776 } 2777 return Error; 2778 } 2779 2780 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2781 CallExpr *TheCall) { 2782 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2783 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2784 } 2785 2786 2787 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2788 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2789 // ordering for DSP is unspecified. MSA is ordered by the data format used 2790 // by the underlying instruction i.e., df/m, df/n and then by size. 2791 // 2792 // FIXME: The size tests here should instead be tablegen'd along with the 2793 // definitions from include/clang/Basic/BuiltinsMips.def. 2794 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2795 // be too. 2796 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2797 unsigned i = 0, l = 0, u = 0, m = 0; 2798 switch (BuiltinID) { 2799 default: return false; 2800 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2801 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2802 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2803 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2804 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2805 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2806 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2807 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 2808 // df/m field. 2809 // These intrinsics take an unsigned 3 bit immediate. 2810 case Mips::BI__builtin_msa_bclri_b: 2811 case Mips::BI__builtin_msa_bnegi_b: 2812 case Mips::BI__builtin_msa_bseti_b: 2813 case Mips::BI__builtin_msa_sat_s_b: 2814 case Mips::BI__builtin_msa_sat_u_b: 2815 case Mips::BI__builtin_msa_slli_b: 2816 case Mips::BI__builtin_msa_srai_b: 2817 case Mips::BI__builtin_msa_srari_b: 2818 case Mips::BI__builtin_msa_srli_b: 2819 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2820 case Mips::BI__builtin_msa_binsli_b: 2821 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2822 // These intrinsics take an unsigned 4 bit immediate. 2823 case Mips::BI__builtin_msa_bclri_h: 2824 case Mips::BI__builtin_msa_bnegi_h: 2825 case Mips::BI__builtin_msa_bseti_h: 2826 case Mips::BI__builtin_msa_sat_s_h: 2827 case Mips::BI__builtin_msa_sat_u_h: 2828 case Mips::BI__builtin_msa_slli_h: 2829 case Mips::BI__builtin_msa_srai_h: 2830 case Mips::BI__builtin_msa_srari_h: 2831 case Mips::BI__builtin_msa_srli_h: 2832 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2833 case Mips::BI__builtin_msa_binsli_h: 2834 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2835 // These intrinsics take an unsigned 5 bit immediate. 2836 // The first block of intrinsics actually have an unsigned 5 bit field, 2837 // not a df/n field. 2838 case Mips::BI__builtin_msa_clei_u_b: 2839 case Mips::BI__builtin_msa_clei_u_h: 2840 case Mips::BI__builtin_msa_clei_u_w: 2841 case Mips::BI__builtin_msa_clei_u_d: 2842 case Mips::BI__builtin_msa_clti_u_b: 2843 case Mips::BI__builtin_msa_clti_u_h: 2844 case Mips::BI__builtin_msa_clti_u_w: 2845 case Mips::BI__builtin_msa_clti_u_d: 2846 case Mips::BI__builtin_msa_maxi_u_b: 2847 case Mips::BI__builtin_msa_maxi_u_h: 2848 case Mips::BI__builtin_msa_maxi_u_w: 2849 case Mips::BI__builtin_msa_maxi_u_d: 2850 case Mips::BI__builtin_msa_mini_u_b: 2851 case Mips::BI__builtin_msa_mini_u_h: 2852 case Mips::BI__builtin_msa_mini_u_w: 2853 case Mips::BI__builtin_msa_mini_u_d: 2854 case Mips::BI__builtin_msa_addvi_b: 2855 case Mips::BI__builtin_msa_addvi_h: 2856 case Mips::BI__builtin_msa_addvi_w: 2857 case Mips::BI__builtin_msa_addvi_d: 2858 case Mips::BI__builtin_msa_bclri_w: 2859 case Mips::BI__builtin_msa_bnegi_w: 2860 case Mips::BI__builtin_msa_bseti_w: 2861 case Mips::BI__builtin_msa_sat_s_w: 2862 case Mips::BI__builtin_msa_sat_u_w: 2863 case Mips::BI__builtin_msa_slli_w: 2864 case Mips::BI__builtin_msa_srai_w: 2865 case Mips::BI__builtin_msa_srari_w: 2866 case Mips::BI__builtin_msa_srli_w: 2867 case Mips::BI__builtin_msa_srlri_w: 2868 case Mips::BI__builtin_msa_subvi_b: 2869 case Mips::BI__builtin_msa_subvi_h: 2870 case Mips::BI__builtin_msa_subvi_w: 2871 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2872 case Mips::BI__builtin_msa_binsli_w: 2873 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2874 // These intrinsics take an unsigned 6 bit immediate. 2875 case Mips::BI__builtin_msa_bclri_d: 2876 case Mips::BI__builtin_msa_bnegi_d: 2877 case Mips::BI__builtin_msa_bseti_d: 2878 case Mips::BI__builtin_msa_sat_s_d: 2879 case Mips::BI__builtin_msa_sat_u_d: 2880 case Mips::BI__builtin_msa_slli_d: 2881 case Mips::BI__builtin_msa_srai_d: 2882 case Mips::BI__builtin_msa_srari_d: 2883 case Mips::BI__builtin_msa_srli_d: 2884 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2885 case Mips::BI__builtin_msa_binsli_d: 2886 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2887 // These intrinsics take a signed 5 bit immediate. 2888 case Mips::BI__builtin_msa_ceqi_b: 2889 case Mips::BI__builtin_msa_ceqi_h: 2890 case Mips::BI__builtin_msa_ceqi_w: 2891 case Mips::BI__builtin_msa_ceqi_d: 2892 case Mips::BI__builtin_msa_clti_s_b: 2893 case Mips::BI__builtin_msa_clti_s_h: 2894 case Mips::BI__builtin_msa_clti_s_w: 2895 case Mips::BI__builtin_msa_clti_s_d: 2896 case Mips::BI__builtin_msa_clei_s_b: 2897 case Mips::BI__builtin_msa_clei_s_h: 2898 case Mips::BI__builtin_msa_clei_s_w: 2899 case Mips::BI__builtin_msa_clei_s_d: 2900 case Mips::BI__builtin_msa_maxi_s_b: 2901 case Mips::BI__builtin_msa_maxi_s_h: 2902 case Mips::BI__builtin_msa_maxi_s_w: 2903 case Mips::BI__builtin_msa_maxi_s_d: 2904 case Mips::BI__builtin_msa_mini_s_b: 2905 case Mips::BI__builtin_msa_mini_s_h: 2906 case Mips::BI__builtin_msa_mini_s_w: 2907 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2908 // These intrinsics take an unsigned 8 bit immediate. 2909 case Mips::BI__builtin_msa_andi_b: 2910 case Mips::BI__builtin_msa_nori_b: 2911 case Mips::BI__builtin_msa_ori_b: 2912 case Mips::BI__builtin_msa_shf_b: 2913 case Mips::BI__builtin_msa_shf_h: 2914 case Mips::BI__builtin_msa_shf_w: 2915 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2916 case Mips::BI__builtin_msa_bseli_b: 2917 case Mips::BI__builtin_msa_bmnzi_b: 2918 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2919 // df/n format 2920 // These intrinsics take an unsigned 4 bit immediate. 2921 case Mips::BI__builtin_msa_copy_s_b: 2922 case Mips::BI__builtin_msa_copy_u_b: 2923 case Mips::BI__builtin_msa_insve_b: 2924 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2925 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2926 // These intrinsics take an unsigned 3 bit immediate. 2927 case Mips::BI__builtin_msa_copy_s_h: 2928 case Mips::BI__builtin_msa_copy_u_h: 2929 case Mips::BI__builtin_msa_insve_h: 2930 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2931 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2932 // These intrinsics take an unsigned 2 bit immediate. 2933 case Mips::BI__builtin_msa_copy_s_w: 2934 case Mips::BI__builtin_msa_copy_u_w: 2935 case Mips::BI__builtin_msa_insve_w: 2936 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2937 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2938 // These intrinsics take an unsigned 1 bit immediate. 2939 case Mips::BI__builtin_msa_copy_s_d: 2940 case Mips::BI__builtin_msa_copy_u_d: 2941 case Mips::BI__builtin_msa_insve_d: 2942 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2943 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2944 // Memory offsets and immediate loads. 2945 // These intrinsics take a signed 10 bit immediate. 2946 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2947 case Mips::BI__builtin_msa_ldi_h: 2948 case Mips::BI__builtin_msa_ldi_w: 2949 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2950 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 2951 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 2952 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 2953 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 2954 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 2955 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 2956 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 2957 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 2958 } 2959 2960 if (!m) 2961 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2962 2963 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2964 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2965 } 2966 2967 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2968 unsigned i = 0, l = 0, u = 0; 2969 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2970 BuiltinID == PPC::BI__builtin_divdeu || 2971 BuiltinID == PPC::BI__builtin_bpermd; 2972 bool IsTarget64Bit = Context.getTargetInfo() 2973 .getTypeWidth(Context 2974 .getTargetInfo() 2975 .getIntPtrType()) == 64; 2976 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2977 BuiltinID == PPC::BI__builtin_divweu || 2978 BuiltinID == PPC::BI__builtin_divde || 2979 BuiltinID == PPC::BI__builtin_divdeu; 2980 2981 if (Is64BitBltin && !IsTarget64Bit) 2982 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2983 << TheCall->getSourceRange(); 2984 2985 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2986 (BuiltinID == PPC::BI__builtin_bpermd && 2987 !Context.getTargetInfo().hasFeature("bpermd"))) 2988 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2989 << TheCall->getSourceRange(); 2990 2991 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 2992 if (!Context.getTargetInfo().hasFeature("vsx")) 2993 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2994 << TheCall->getSourceRange(); 2995 return false; 2996 }; 2997 2998 switch (BuiltinID) { 2999 default: return false; 3000 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3001 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3003 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3004 case PPC::BI__builtin_tbegin: 3005 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3006 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3007 case PPC::BI__builtin_tabortwc: 3008 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3009 case PPC::BI__builtin_tabortwci: 3010 case PPC::BI__builtin_tabortdci: 3011 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3012 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3013 case PPC::BI__builtin_vsx_xxpermdi: 3014 case PPC::BI__builtin_vsx_xxsldwi: 3015 return SemaBuiltinVSX(TheCall); 3016 case PPC::BI__builtin_unpack_vector_int128: 3017 return SemaVSXCheck(TheCall) || 3018 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3019 case PPC::BI__builtin_pack_vector_int128: 3020 return SemaVSXCheck(TheCall); 3021 } 3022 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3023 } 3024 3025 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3026 CallExpr *TheCall) { 3027 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3028 Expr *Arg = TheCall->getArg(0); 3029 llvm::APSInt AbortCode(32); 3030 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3031 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3032 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3033 << Arg->getSourceRange(); 3034 } 3035 3036 // For intrinsics which take an immediate value as part of the instruction, 3037 // range check them here. 3038 unsigned i = 0, l = 0, u = 0; 3039 switch (BuiltinID) { 3040 default: return false; 3041 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3042 case SystemZ::BI__builtin_s390_verimb: 3043 case SystemZ::BI__builtin_s390_verimh: 3044 case SystemZ::BI__builtin_s390_verimf: 3045 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3046 case SystemZ::BI__builtin_s390_vfaeb: 3047 case SystemZ::BI__builtin_s390_vfaeh: 3048 case SystemZ::BI__builtin_s390_vfaef: 3049 case SystemZ::BI__builtin_s390_vfaebs: 3050 case SystemZ::BI__builtin_s390_vfaehs: 3051 case SystemZ::BI__builtin_s390_vfaefs: 3052 case SystemZ::BI__builtin_s390_vfaezb: 3053 case SystemZ::BI__builtin_s390_vfaezh: 3054 case SystemZ::BI__builtin_s390_vfaezf: 3055 case SystemZ::BI__builtin_s390_vfaezbs: 3056 case SystemZ::BI__builtin_s390_vfaezhs: 3057 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3058 case SystemZ::BI__builtin_s390_vfisb: 3059 case SystemZ::BI__builtin_s390_vfidb: 3060 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3061 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3062 case SystemZ::BI__builtin_s390_vftcisb: 3063 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3064 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3065 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3066 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3067 case SystemZ::BI__builtin_s390_vstrcb: 3068 case SystemZ::BI__builtin_s390_vstrch: 3069 case SystemZ::BI__builtin_s390_vstrcf: 3070 case SystemZ::BI__builtin_s390_vstrczb: 3071 case SystemZ::BI__builtin_s390_vstrczh: 3072 case SystemZ::BI__builtin_s390_vstrczf: 3073 case SystemZ::BI__builtin_s390_vstrcbs: 3074 case SystemZ::BI__builtin_s390_vstrchs: 3075 case SystemZ::BI__builtin_s390_vstrcfs: 3076 case SystemZ::BI__builtin_s390_vstrczbs: 3077 case SystemZ::BI__builtin_s390_vstrczhs: 3078 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3079 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3080 case SystemZ::BI__builtin_s390_vfminsb: 3081 case SystemZ::BI__builtin_s390_vfmaxsb: 3082 case SystemZ::BI__builtin_s390_vfmindb: 3083 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3084 } 3085 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3086 } 3087 3088 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3089 /// This checks that the target supports __builtin_cpu_supports and 3090 /// that the string argument is constant and valid. 3091 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3092 Expr *Arg = TheCall->getArg(0); 3093 3094 // Check if the argument is a string literal. 3095 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3096 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3097 << Arg->getSourceRange(); 3098 3099 // Check the contents of the string. 3100 StringRef Feature = 3101 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3102 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3103 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3104 << Arg->getSourceRange(); 3105 return false; 3106 } 3107 3108 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3109 /// This checks that the target supports __builtin_cpu_is and 3110 /// that the string argument is constant and valid. 3111 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3112 Expr *Arg = TheCall->getArg(0); 3113 3114 // Check if the argument is a string literal. 3115 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3116 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3117 << Arg->getSourceRange(); 3118 3119 // Check the contents of the string. 3120 StringRef Feature = 3121 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3122 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3123 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3124 << Arg->getSourceRange(); 3125 return false; 3126 } 3127 3128 // Check if the rounding mode is legal. 3129 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3130 // Indicates if this instruction has rounding control or just SAE. 3131 bool HasRC = false; 3132 3133 unsigned ArgNum = 0; 3134 switch (BuiltinID) { 3135 default: 3136 return false; 3137 case X86::BI__builtin_ia32_vcvttsd2si32: 3138 case X86::BI__builtin_ia32_vcvttsd2si64: 3139 case X86::BI__builtin_ia32_vcvttsd2usi32: 3140 case X86::BI__builtin_ia32_vcvttsd2usi64: 3141 case X86::BI__builtin_ia32_vcvttss2si32: 3142 case X86::BI__builtin_ia32_vcvttss2si64: 3143 case X86::BI__builtin_ia32_vcvttss2usi32: 3144 case X86::BI__builtin_ia32_vcvttss2usi64: 3145 ArgNum = 1; 3146 break; 3147 case X86::BI__builtin_ia32_maxpd512: 3148 case X86::BI__builtin_ia32_maxps512: 3149 case X86::BI__builtin_ia32_minpd512: 3150 case X86::BI__builtin_ia32_minps512: 3151 ArgNum = 2; 3152 break; 3153 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3154 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3155 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3156 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3157 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3158 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3159 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3160 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3161 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3162 case X86::BI__builtin_ia32_exp2pd_mask: 3163 case X86::BI__builtin_ia32_exp2ps_mask: 3164 case X86::BI__builtin_ia32_getexppd512_mask: 3165 case X86::BI__builtin_ia32_getexpps512_mask: 3166 case X86::BI__builtin_ia32_rcp28pd_mask: 3167 case X86::BI__builtin_ia32_rcp28ps_mask: 3168 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3169 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3170 case X86::BI__builtin_ia32_vcomisd: 3171 case X86::BI__builtin_ia32_vcomiss: 3172 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3173 ArgNum = 3; 3174 break; 3175 case X86::BI__builtin_ia32_cmppd512_mask: 3176 case X86::BI__builtin_ia32_cmpps512_mask: 3177 case X86::BI__builtin_ia32_cmpsd_mask: 3178 case X86::BI__builtin_ia32_cmpss_mask: 3179 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3180 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3181 case X86::BI__builtin_ia32_getexpss128_round_mask: 3182 case X86::BI__builtin_ia32_maxsd_round_mask: 3183 case X86::BI__builtin_ia32_maxss_round_mask: 3184 case X86::BI__builtin_ia32_minsd_round_mask: 3185 case X86::BI__builtin_ia32_minss_round_mask: 3186 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3187 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3188 case X86::BI__builtin_ia32_reducepd512_mask: 3189 case X86::BI__builtin_ia32_reduceps512_mask: 3190 case X86::BI__builtin_ia32_rndscalepd_mask: 3191 case X86::BI__builtin_ia32_rndscaleps_mask: 3192 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3193 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3194 ArgNum = 4; 3195 break; 3196 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3197 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3198 case X86::BI__builtin_ia32_fixupimmps512_mask: 3199 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3200 case X86::BI__builtin_ia32_fixupimmsd_mask: 3201 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3202 case X86::BI__builtin_ia32_fixupimmss_mask: 3203 case X86::BI__builtin_ia32_fixupimmss_maskz: 3204 case X86::BI__builtin_ia32_rangepd512_mask: 3205 case X86::BI__builtin_ia32_rangeps512_mask: 3206 case X86::BI__builtin_ia32_rangesd128_round_mask: 3207 case X86::BI__builtin_ia32_rangess128_round_mask: 3208 case X86::BI__builtin_ia32_reducesd_mask: 3209 case X86::BI__builtin_ia32_reducess_mask: 3210 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3211 case X86::BI__builtin_ia32_rndscaless_round_mask: 3212 ArgNum = 5; 3213 break; 3214 case X86::BI__builtin_ia32_vcvtsd2si64: 3215 case X86::BI__builtin_ia32_vcvtsd2si32: 3216 case X86::BI__builtin_ia32_vcvtsd2usi32: 3217 case X86::BI__builtin_ia32_vcvtsd2usi64: 3218 case X86::BI__builtin_ia32_vcvtss2si32: 3219 case X86::BI__builtin_ia32_vcvtss2si64: 3220 case X86::BI__builtin_ia32_vcvtss2usi32: 3221 case X86::BI__builtin_ia32_vcvtss2usi64: 3222 case X86::BI__builtin_ia32_sqrtpd512: 3223 case X86::BI__builtin_ia32_sqrtps512: 3224 ArgNum = 1; 3225 HasRC = true; 3226 break; 3227 case X86::BI__builtin_ia32_addpd512: 3228 case X86::BI__builtin_ia32_addps512: 3229 case X86::BI__builtin_ia32_divpd512: 3230 case X86::BI__builtin_ia32_divps512: 3231 case X86::BI__builtin_ia32_mulpd512: 3232 case X86::BI__builtin_ia32_mulps512: 3233 case X86::BI__builtin_ia32_subpd512: 3234 case X86::BI__builtin_ia32_subps512: 3235 case X86::BI__builtin_ia32_cvtsi2sd64: 3236 case X86::BI__builtin_ia32_cvtsi2ss32: 3237 case X86::BI__builtin_ia32_cvtsi2ss64: 3238 case X86::BI__builtin_ia32_cvtusi2sd64: 3239 case X86::BI__builtin_ia32_cvtusi2ss32: 3240 case X86::BI__builtin_ia32_cvtusi2ss64: 3241 ArgNum = 2; 3242 HasRC = true; 3243 break; 3244 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3245 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3246 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3247 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3248 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3249 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3250 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3251 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3252 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3253 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3254 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3255 ArgNum = 3; 3256 HasRC = true; 3257 break; 3258 case X86::BI__builtin_ia32_addss_round_mask: 3259 case X86::BI__builtin_ia32_addsd_round_mask: 3260 case X86::BI__builtin_ia32_divss_round_mask: 3261 case X86::BI__builtin_ia32_divsd_round_mask: 3262 case X86::BI__builtin_ia32_mulss_round_mask: 3263 case X86::BI__builtin_ia32_mulsd_round_mask: 3264 case X86::BI__builtin_ia32_subss_round_mask: 3265 case X86::BI__builtin_ia32_subsd_round_mask: 3266 case X86::BI__builtin_ia32_scalefpd512_mask: 3267 case X86::BI__builtin_ia32_scalefps512_mask: 3268 case X86::BI__builtin_ia32_scalefsd_round_mask: 3269 case X86::BI__builtin_ia32_scalefss_round_mask: 3270 case X86::BI__builtin_ia32_getmantpd512_mask: 3271 case X86::BI__builtin_ia32_getmantps512_mask: 3272 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3273 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3274 case X86::BI__builtin_ia32_sqrtss_round_mask: 3275 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3276 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3277 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3278 case X86::BI__builtin_ia32_vfmaddss3_mask: 3279 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3280 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3281 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3282 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3283 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3284 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3285 case X86::BI__builtin_ia32_vfmaddps512_mask: 3286 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3287 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3288 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3289 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3290 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3291 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3292 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3293 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3294 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3295 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3296 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3297 ArgNum = 4; 3298 HasRC = true; 3299 break; 3300 case X86::BI__builtin_ia32_getmantsd_round_mask: 3301 case X86::BI__builtin_ia32_getmantss_round_mask: 3302 ArgNum = 5; 3303 HasRC = true; 3304 break; 3305 } 3306 3307 llvm::APSInt Result; 3308 3309 // We can't check the value of a dependent argument. 3310 Expr *Arg = TheCall->getArg(ArgNum); 3311 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3312 return false; 3313 3314 // Check constant-ness first. 3315 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3316 return true; 3317 3318 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3319 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3320 // combined with ROUND_NO_EXC. 3321 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3322 Result == 8/*ROUND_NO_EXC*/ || 3323 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3324 return false; 3325 3326 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3327 << Arg->getSourceRange(); 3328 } 3329 3330 // Check if the gather/scatter scale is legal. 3331 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3332 CallExpr *TheCall) { 3333 unsigned ArgNum = 0; 3334 switch (BuiltinID) { 3335 default: 3336 return false; 3337 case X86::BI__builtin_ia32_gatherpfdpd: 3338 case X86::BI__builtin_ia32_gatherpfdps: 3339 case X86::BI__builtin_ia32_gatherpfqpd: 3340 case X86::BI__builtin_ia32_gatherpfqps: 3341 case X86::BI__builtin_ia32_scatterpfdpd: 3342 case X86::BI__builtin_ia32_scatterpfdps: 3343 case X86::BI__builtin_ia32_scatterpfqpd: 3344 case X86::BI__builtin_ia32_scatterpfqps: 3345 ArgNum = 3; 3346 break; 3347 case X86::BI__builtin_ia32_gatherd_pd: 3348 case X86::BI__builtin_ia32_gatherd_pd256: 3349 case X86::BI__builtin_ia32_gatherq_pd: 3350 case X86::BI__builtin_ia32_gatherq_pd256: 3351 case X86::BI__builtin_ia32_gatherd_ps: 3352 case X86::BI__builtin_ia32_gatherd_ps256: 3353 case X86::BI__builtin_ia32_gatherq_ps: 3354 case X86::BI__builtin_ia32_gatherq_ps256: 3355 case X86::BI__builtin_ia32_gatherd_q: 3356 case X86::BI__builtin_ia32_gatherd_q256: 3357 case X86::BI__builtin_ia32_gatherq_q: 3358 case X86::BI__builtin_ia32_gatherq_q256: 3359 case X86::BI__builtin_ia32_gatherd_d: 3360 case X86::BI__builtin_ia32_gatherd_d256: 3361 case X86::BI__builtin_ia32_gatherq_d: 3362 case X86::BI__builtin_ia32_gatherq_d256: 3363 case X86::BI__builtin_ia32_gather3div2df: 3364 case X86::BI__builtin_ia32_gather3div2di: 3365 case X86::BI__builtin_ia32_gather3div4df: 3366 case X86::BI__builtin_ia32_gather3div4di: 3367 case X86::BI__builtin_ia32_gather3div4sf: 3368 case X86::BI__builtin_ia32_gather3div4si: 3369 case X86::BI__builtin_ia32_gather3div8sf: 3370 case X86::BI__builtin_ia32_gather3div8si: 3371 case X86::BI__builtin_ia32_gather3siv2df: 3372 case X86::BI__builtin_ia32_gather3siv2di: 3373 case X86::BI__builtin_ia32_gather3siv4df: 3374 case X86::BI__builtin_ia32_gather3siv4di: 3375 case X86::BI__builtin_ia32_gather3siv4sf: 3376 case X86::BI__builtin_ia32_gather3siv4si: 3377 case X86::BI__builtin_ia32_gather3siv8sf: 3378 case X86::BI__builtin_ia32_gather3siv8si: 3379 case X86::BI__builtin_ia32_gathersiv8df: 3380 case X86::BI__builtin_ia32_gathersiv16sf: 3381 case X86::BI__builtin_ia32_gatherdiv8df: 3382 case X86::BI__builtin_ia32_gatherdiv16sf: 3383 case X86::BI__builtin_ia32_gathersiv8di: 3384 case X86::BI__builtin_ia32_gathersiv16si: 3385 case X86::BI__builtin_ia32_gatherdiv8di: 3386 case X86::BI__builtin_ia32_gatherdiv16si: 3387 case X86::BI__builtin_ia32_scatterdiv2df: 3388 case X86::BI__builtin_ia32_scatterdiv2di: 3389 case X86::BI__builtin_ia32_scatterdiv4df: 3390 case X86::BI__builtin_ia32_scatterdiv4di: 3391 case X86::BI__builtin_ia32_scatterdiv4sf: 3392 case X86::BI__builtin_ia32_scatterdiv4si: 3393 case X86::BI__builtin_ia32_scatterdiv8sf: 3394 case X86::BI__builtin_ia32_scatterdiv8si: 3395 case X86::BI__builtin_ia32_scattersiv2df: 3396 case X86::BI__builtin_ia32_scattersiv2di: 3397 case X86::BI__builtin_ia32_scattersiv4df: 3398 case X86::BI__builtin_ia32_scattersiv4di: 3399 case X86::BI__builtin_ia32_scattersiv4sf: 3400 case X86::BI__builtin_ia32_scattersiv4si: 3401 case X86::BI__builtin_ia32_scattersiv8sf: 3402 case X86::BI__builtin_ia32_scattersiv8si: 3403 case X86::BI__builtin_ia32_scattersiv8df: 3404 case X86::BI__builtin_ia32_scattersiv16sf: 3405 case X86::BI__builtin_ia32_scatterdiv8df: 3406 case X86::BI__builtin_ia32_scatterdiv16sf: 3407 case X86::BI__builtin_ia32_scattersiv8di: 3408 case X86::BI__builtin_ia32_scattersiv16si: 3409 case X86::BI__builtin_ia32_scatterdiv8di: 3410 case X86::BI__builtin_ia32_scatterdiv16si: 3411 ArgNum = 4; 3412 break; 3413 } 3414 3415 llvm::APSInt Result; 3416 3417 // We can't check the value of a dependent argument. 3418 Expr *Arg = TheCall->getArg(ArgNum); 3419 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3420 return false; 3421 3422 // Check constant-ness first. 3423 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3424 return true; 3425 3426 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3427 return false; 3428 3429 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3430 << Arg->getSourceRange(); 3431 } 3432 3433 static bool isX86_32Builtin(unsigned BuiltinID) { 3434 // These builtins only work on x86-32 targets. 3435 switch (BuiltinID) { 3436 case X86::BI__builtin_ia32_readeflags_u32: 3437 case X86::BI__builtin_ia32_writeeflags_u32: 3438 return true; 3439 } 3440 3441 return false; 3442 } 3443 3444 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3445 if (BuiltinID == X86::BI__builtin_cpu_supports) 3446 return SemaBuiltinCpuSupports(*this, TheCall); 3447 3448 if (BuiltinID == X86::BI__builtin_cpu_is) 3449 return SemaBuiltinCpuIs(*this, TheCall); 3450 3451 // Check for 32-bit only builtins on a 64-bit target. 3452 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3453 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3454 return Diag(TheCall->getCallee()->getBeginLoc(), 3455 diag::err_32_bit_builtin_64_bit_tgt); 3456 3457 // If the intrinsic has rounding or SAE make sure its valid. 3458 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3459 return true; 3460 3461 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3462 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3463 return true; 3464 3465 // For intrinsics which take an immediate value as part of the instruction, 3466 // range check them here. 3467 int i = 0, l = 0, u = 0; 3468 switch (BuiltinID) { 3469 default: 3470 return false; 3471 case X86::BI__builtin_ia32_vec_ext_v2si: 3472 case X86::BI__builtin_ia32_vec_ext_v2di: 3473 case X86::BI__builtin_ia32_vextractf128_pd256: 3474 case X86::BI__builtin_ia32_vextractf128_ps256: 3475 case X86::BI__builtin_ia32_vextractf128_si256: 3476 case X86::BI__builtin_ia32_extract128i256: 3477 case X86::BI__builtin_ia32_extractf64x4_mask: 3478 case X86::BI__builtin_ia32_extracti64x4_mask: 3479 case X86::BI__builtin_ia32_extractf32x8_mask: 3480 case X86::BI__builtin_ia32_extracti32x8_mask: 3481 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3482 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3483 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3484 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3485 i = 1; l = 0; u = 1; 3486 break; 3487 case X86::BI__builtin_ia32_vec_set_v2di: 3488 case X86::BI__builtin_ia32_vinsertf128_pd256: 3489 case X86::BI__builtin_ia32_vinsertf128_ps256: 3490 case X86::BI__builtin_ia32_vinsertf128_si256: 3491 case X86::BI__builtin_ia32_insert128i256: 3492 case X86::BI__builtin_ia32_insertf32x8: 3493 case X86::BI__builtin_ia32_inserti32x8: 3494 case X86::BI__builtin_ia32_insertf64x4: 3495 case X86::BI__builtin_ia32_inserti64x4: 3496 case X86::BI__builtin_ia32_insertf64x2_256: 3497 case X86::BI__builtin_ia32_inserti64x2_256: 3498 case X86::BI__builtin_ia32_insertf32x4_256: 3499 case X86::BI__builtin_ia32_inserti32x4_256: 3500 i = 2; l = 0; u = 1; 3501 break; 3502 case X86::BI__builtin_ia32_vpermilpd: 3503 case X86::BI__builtin_ia32_vec_ext_v4hi: 3504 case X86::BI__builtin_ia32_vec_ext_v4si: 3505 case X86::BI__builtin_ia32_vec_ext_v4sf: 3506 case X86::BI__builtin_ia32_vec_ext_v4di: 3507 case X86::BI__builtin_ia32_extractf32x4_mask: 3508 case X86::BI__builtin_ia32_extracti32x4_mask: 3509 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3510 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3511 i = 1; l = 0; u = 3; 3512 break; 3513 case X86::BI_mm_prefetch: 3514 case X86::BI__builtin_ia32_vec_ext_v8hi: 3515 case X86::BI__builtin_ia32_vec_ext_v8si: 3516 i = 1; l = 0; u = 7; 3517 break; 3518 case X86::BI__builtin_ia32_sha1rnds4: 3519 case X86::BI__builtin_ia32_blendpd: 3520 case X86::BI__builtin_ia32_shufpd: 3521 case X86::BI__builtin_ia32_vec_set_v4hi: 3522 case X86::BI__builtin_ia32_vec_set_v4si: 3523 case X86::BI__builtin_ia32_vec_set_v4di: 3524 case X86::BI__builtin_ia32_shuf_f32x4_256: 3525 case X86::BI__builtin_ia32_shuf_f64x2_256: 3526 case X86::BI__builtin_ia32_shuf_i32x4_256: 3527 case X86::BI__builtin_ia32_shuf_i64x2_256: 3528 case X86::BI__builtin_ia32_insertf64x2_512: 3529 case X86::BI__builtin_ia32_inserti64x2_512: 3530 case X86::BI__builtin_ia32_insertf32x4: 3531 case X86::BI__builtin_ia32_inserti32x4: 3532 i = 2; l = 0; u = 3; 3533 break; 3534 case X86::BI__builtin_ia32_vpermil2pd: 3535 case X86::BI__builtin_ia32_vpermil2pd256: 3536 case X86::BI__builtin_ia32_vpermil2ps: 3537 case X86::BI__builtin_ia32_vpermil2ps256: 3538 i = 3; l = 0; u = 3; 3539 break; 3540 case X86::BI__builtin_ia32_cmpb128_mask: 3541 case X86::BI__builtin_ia32_cmpw128_mask: 3542 case X86::BI__builtin_ia32_cmpd128_mask: 3543 case X86::BI__builtin_ia32_cmpq128_mask: 3544 case X86::BI__builtin_ia32_cmpb256_mask: 3545 case X86::BI__builtin_ia32_cmpw256_mask: 3546 case X86::BI__builtin_ia32_cmpd256_mask: 3547 case X86::BI__builtin_ia32_cmpq256_mask: 3548 case X86::BI__builtin_ia32_cmpb512_mask: 3549 case X86::BI__builtin_ia32_cmpw512_mask: 3550 case X86::BI__builtin_ia32_cmpd512_mask: 3551 case X86::BI__builtin_ia32_cmpq512_mask: 3552 case X86::BI__builtin_ia32_ucmpb128_mask: 3553 case X86::BI__builtin_ia32_ucmpw128_mask: 3554 case X86::BI__builtin_ia32_ucmpd128_mask: 3555 case X86::BI__builtin_ia32_ucmpq128_mask: 3556 case X86::BI__builtin_ia32_ucmpb256_mask: 3557 case X86::BI__builtin_ia32_ucmpw256_mask: 3558 case X86::BI__builtin_ia32_ucmpd256_mask: 3559 case X86::BI__builtin_ia32_ucmpq256_mask: 3560 case X86::BI__builtin_ia32_ucmpb512_mask: 3561 case X86::BI__builtin_ia32_ucmpw512_mask: 3562 case X86::BI__builtin_ia32_ucmpd512_mask: 3563 case X86::BI__builtin_ia32_ucmpq512_mask: 3564 case X86::BI__builtin_ia32_vpcomub: 3565 case X86::BI__builtin_ia32_vpcomuw: 3566 case X86::BI__builtin_ia32_vpcomud: 3567 case X86::BI__builtin_ia32_vpcomuq: 3568 case X86::BI__builtin_ia32_vpcomb: 3569 case X86::BI__builtin_ia32_vpcomw: 3570 case X86::BI__builtin_ia32_vpcomd: 3571 case X86::BI__builtin_ia32_vpcomq: 3572 case X86::BI__builtin_ia32_vec_set_v8hi: 3573 case X86::BI__builtin_ia32_vec_set_v8si: 3574 i = 2; l = 0; u = 7; 3575 break; 3576 case X86::BI__builtin_ia32_vpermilpd256: 3577 case X86::BI__builtin_ia32_roundps: 3578 case X86::BI__builtin_ia32_roundpd: 3579 case X86::BI__builtin_ia32_roundps256: 3580 case X86::BI__builtin_ia32_roundpd256: 3581 case X86::BI__builtin_ia32_getmantpd128_mask: 3582 case X86::BI__builtin_ia32_getmantpd256_mask: 3583 case X86::BI__builtin_ia32_getmantps128_mask: 3584 case X86::BI__builtin_ia32_getmantps256_mask: 3585 case X86::BI__builtin_ia32_getmantpd512_mask: 3586 case X86::BI__builtin_ia32_getmantps512_mask: 3587 case X86::BI__builtin_ia32_vec_ext_v16qi: 3588 case X86::BI__builtin_ia32_vec_ext_v16hi: 3589 i = 1; l = 0; u = 15; 3590 break; 3591 case X86::BI__builtin_ia32_pblendd128: 3592 case X86::BI__builtin_ia32_blendps: 3593 case X86::BI__builtin_ia32_blendpd256: 3594 case X86::BI__builtin_ia32_shufpd256: 3595 case X86::BI__builtin_ia32_roundss: 3596 case X86::BI__builtin_ia32_roundsd: 3597 case X86::BI__builtin_ia32_rangepd128_mask: 3598 case X86::BI__builtin_ia32_rangepd256_mask: 3599 case X86::BI__builtin_ia32_rangepd512_mask: 3600 case X86::BI__builtin_ia32_rangeps128_mask: 3601 case X86::BI__builtin_ia32_rangeps256_mask: 3602 case X86::BI__builtin_ia32_rangeps512_mask: 3603 case X86::BI__builtin_ia32_getmantsd_round_mask: 3604 case X86::BI__builtin_ia32_getmantss_round_mask: 3605 case X86::BI__builtin_ia32_vec_set_v16qi: 3606 case X86::BI__builtin_ia32_vec_set_v16hi: 3607 i = 2; l = 0; u = 15; 3608 break; 3609 case X86::BI__builtin_ia32_vec_ext_v32qi: 3610 i = 1; l = 0; u = 31; 3611 break; 3612 case X86::BI__builtin_ia32_cmpps: 3613 case X86::BI__builtin_ia32_cmpss: 3614 case X86::BI__builtin_ia32_cmppd: 3615 case X86::BI__builtin_ia32_cmpsd: 3616 case X86::BI__builtin_ia32_cmpps256: 3617 case X86::BI__builtin_ia32_cmppd256: 3618 case X86::BI__builtin_ia32_cmpps128_mask: 3619 case X86::BI__builtin_ia32_cmppd128_mask: 3620 case X86::BI__builtin_ia32_cmpps256_mask: 3621 case X86::BI__builtin_ia32_cmppd256_mask: 3622 case X86::BI__builtin_ia32_cmpps512_mask: 3623 case X86::BI__builtin_ia32_cmppd512_mask: 3624 case X86::BI__builtin_ia32_cmpsd_mask: 3625 case X86::BI__builtin_ia32_cmpss_mask: 3626 case X86::BI__builtin_ia32_vec_set_v32qi: 3627 i = 2; l = 0; u = 31; 3628 break; 3629 case X86::BI__builtin_ia32_permdf256: 3630 case X86::BI__builtin_ia32_permdi256: 3631 case X86::BI__builtin_ia32_permdf512: 3632 case X86::BI__builtin_ia32_permdi512: 3633 case X86::BI__builtin_ia32_vpermilps: 3634 case X86::BI__builtin_ia32_vpermilps256: 3635 case X86::BI__builtin_ia32_vpermilpd512: 3636 case X86::BI__builtin_ia32_vpermilps512: 3637 case X86::BI__builtin_ia32_pshufd: 3638 case X86::BI__builtin_ia32_pshufd256: 3639 case X86::BI__builtin_ia32_pshufd512: 3640 case X86::BI__builtin_ia32_pshufhw: 3641 case X86::BI__builtin_ia32_pshufhw256: 3642 case X86::BI__builtin_ia32_pshufhw512: 3643 case X86::BI__builtin_ia32_pshuflw: 3644 case X86::BI__builtin_ia32_pshuflw256: 3645 case X86::BI__builtin_ia32_pshuflw512: 3646 case X86::BI__builtin_ia32_vcvtps2ph: 3647 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3648 case X86::BI__builtin_ia32_vcvtps2ph256: 3649 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3650 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3651 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3652 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3653 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3654 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3655 case X86::BI__builtin_ia32_rndscaleps_mask: 3656 case X86::BI__builtin_ia32_rndscalepd_mask: 3657 case X86::BI__builtin_ia32_reducepd128_mask: 3658 case X86::BI__builtin_ia32_reducepd256_mask: 3659 case X86::BI__builtin_ia32_reducepd512_mask: 3660 case X86::BI__builtin_ia32_reduceps128_mask: 3661 case X86::BI__builtin_ia32_reduceps256_mask: 3662 case X86::BI__builtin_ia32_reduceps512_mask: 3663 case X86::BI__builtin_ia32_prold512: 3664 case X86::BI__builtin_ia32_prolq512: 3665 case X86::BI__builtin_ia32_prold128: 3666 case X86::BI__builtin_ia32_prold256: 3667 case X86::BI__builtin_ia32_prolq128: 3668 case X86::BI__builtin_ia32_prolq256: 3669 case X86::BI__builtin_ia32_prord512: 3670 case X86::BI__builtin_ia32_prorq512: 3671 case X86::BI__builtin_ia32_prord128: 3672 case X86::BI__builtin_ia32_prord256: 3673 case X86::BI__builtin_ia32_prorq128: 3674 case X86::BI__builtin_ia32_prorq256: 3675 case X86::BI__builtin_ia32_fpclasspd128_mask: 3676 case X86::BI__builtin_ia32_fpclasspd256_mask: 3677 case X86::BI__builtin_ia32_fpclassps128_mask: 3678 case X86::BI__builtin_ia32_fpclassps256_mask: 3679 case X86::BI__builtin_ia32_fpclassps512_mask: 3680 case X86::BI__builtin_ia32_fpclasspd512_mask: 3681 case X86::BI__builtin_ia32_fpclasssd_mask: 3682 case X86::BI__builtin_ia32_fpclassss_mask: 3683 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3684 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3685 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3686 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3687 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3688 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3689 case X86::BI__builtin_ia32_kshiftliqi: 3690 case X86::BI__builtin_ia32_kshiftlihi: 3691 case X86::BI__builtin_ia32_kshiftlisi: 3692 case X86::BI__builtin_ia32_kshiftlidi: 3693 case X86::BI__builtin_ia32_kshiftriqi: 3694 case X86::BI__builtin_ia32_kshiftrihi: 3695 case X86::BI__builtin_ia32_kshiftrisi: 3696 case X86::BI__builtin_ia32_kshiftridi: 3697 i = 1; l = 0; u = 255; 3698 break; 3699 case X86::BI__builtin_ia32_vperm2f128_pd256: 3700 case X86::BI__builtin_ia32_vperm2f128_ps256: 3701 case X86::BI__builtin_ia32_vperm2f128_si256: 3702 case X86::BI__builtin_ia32_permti256: 3703 case X86::BI__builtin_ia32_pblendw128: 3704 case X86::BI__builtin_ia32_pblendw256: 3705 case X86::BI__builtin_ia32_blendps256: 3706 case X86::BI__builtin_ia32_pblendd256: 3707 case X86::BI__builtin_ia32_palignr128: 3708 case X86::BI__builtin_ia32_palignr256: 3709 case X86::BI__builtin_ia32_palignr512: 3710 case X86::BI__builtin_ia32_alignq512: 3711 case X86::BI__builtin_ia32_alignd512: 3712 case X86::BI__builtin_ia32_alignd128: 3713 case X86::BI__builtin_ia32_alignd256: 3714 case X86::BI__builtin_ia32_alignq128: 3715 case X86::BI__builtin_ia32_alignq256: 3716 case X86::BI__builtin_ia32_vcomisd: 3717 case X86::BI__builtin_ia32_vcomiss: 3718 case X86::BI__builtin_ia32_shuf_f32x4: 3719 case X86::BI__builtin_ia32_shuf_f64x2: 3720 case X86::BI__builtin_ia32_shuf_i32x4: 3721 case X86::BI__builtin_ia32_shuf_i64x2: 3722 case X86::BI__builtin_ia32_shufpd512: 3723 case X86::BI__builtin_ia32_shufps: 3724 case X86::BI__builtin_ia32_shufps256: 3725 case X86::BI__builtin_ia32_shufps512: 3726 case X86::BI__builtin_ia32_dbpsadbw128: 3727 case X86::BI__builtin_ia32_dbpsadbw256: 3728 case X86::BI__builtin_ia32_dbpsadbw512: 3729 case X86::BI__builtin_ia32_vpshldd128: 3730 case X86::BI__builtin_ia32_vpshldd256: 3731 case X86::BI__builtin_ia32_vpshldd512: 3732 case X86::BI__builtin_ia32_vpshldq128: 3733 case X86::BI__builtin_ia32_vpshldq256: 3734 case X86::BI__builtin_ia32_vpshldq512: 3735 case X86::BI__builtin_ia32_vpshldw128: 3736 case X86::BI__builtin_ia32_vpshldw256: 3737 case X86::BI__builtin_ia32_vpshldw512: 3738 case X86::BI__builtin_ia32_vpshrdd128: 3739 case X86::BI__builtin_ia32_vpshrdd256: 3740 case X86::BI__builtin_ia32_vpshrdd512: 3741 case X86::BI__builtin_ia32_vpshrdq128: 3742 case X86::BI__builtin_ia32_vpshrdq256: 3743 case X86::BI__builtin_ia32_vpshrdq512: 3744 case X86::BI__builtin_ia32_vpshrdw128: 3745 case X86::BI__builtin_ia32_vpshrdw256: 3746 case X86::BI__builtin_ia32_vpshrdw512: 3747 i = 2; l = 0; u = 255; 3748 break; 3749 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3750 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3751 case X86::BI__builtin_ia32_fixupimmps512_mask: 3752 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3753 case X86::BI__builtin_ia32_fixupimmsd_mask: 3754 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3755 case X86::BI__builtin_ia32_fixupimmss_mask: 3756 case X86::BI__builtin_ia32_fixupimmss_maskz: 3757 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3758 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3759 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3760 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3761 case X86::BI__builtin_ia32_fixupimmps128_mask: 3762 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3763 case X86::BI__builtin_ia32_fixupimmps256_mask: 3764 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3765 case X86::BI__builtin_ia32_pternlogd512_mask: 3766 case X86::BI__builtin_ia32_pternlogd512_maskz: 3767 case X86::BI__builtin_ia32_pternlogq512_mask: 3768 case X86::BI__builtin_ia32_pternlogq512_maskz: 3769 case X86::BI__builtin_ia32_pternlogd128_mask: 3770 case X86::BI__builtin_ia32_pternlogd128_maskz: 3771 case X86::BI__builtin_ia32_pternlogd256_mask: 3772 case X86::BI__builtin_ia32_pternlogd256_maskz: 3773 case X86::BI__builtin_ia32_pternlogq128_mask: 3774 case X86::BI__builtin_ia32_pternlogq128_maskz: 3775 case X86::BI__builtin_ia32_pternlogq256_mask: 3776 case X86::BI__builtin_ia32_pternlogq256_maskz: 3777 i = 3; l = 0; u = 255; 3778 break; 3779 case X86::BI__builtin_ia32_gatherpfdpd: 3780 case X86::BI__builtin_ia32_gatherpfdps: 3781 case X86::BI__builtin_ia32_gatherpfqpd: 3782 case X86::BI__builtin_ia32_gatherpfqps: 3783 case X86::BI__builtin_ia32_scatterpfdpd: 3784 case X86::BI__builtin_ia32_scatterpfdps: 3785 case X86::BI__builtin_ia32_scatterpfqpd: 3786 case X86::BI__builtin_ia32_scatterpfqps: 3787 i = 4; l = 2; u = 3; 3788 break; 3789 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3790 case X86::BI__builtin_ia32_rndscaless_round_mask: 3791 i = 4; l = 0; u = 255; 3792 break; 3793 } 3794 3795 // Note that we don't force a hard error on the range check here, allowing 3796 // template-generated or macro-generated dead code to potentially have out-of- 3797 // range values. These need to code generate, but don't need to necessarily 3798 // make any sense. We use a warning that defaults to an error. 3799 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3800 } 3801 3802 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3803 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3804 /// Returns true when the format fits the function and the FormatStringInfo has 3805 /// been populated. 3806 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3807 FormatStringInfo *FSI) { 3808 FSI->HasVAListArg = Format->getFirstArg() == 0; 3809 FSI->FormatIdx = Format->getFormatIdx() - 1; 3810 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3811 3812 // The way the format attribute works in GCC, the implicit this argument 3813 // of member functions is counted. However, it doesn't appear in our own 3814 // lists, so decrement format_idx in that case. 3815 if (IsCXXMember) { 3816 if(FSI->FormatIdx == 0) 3817 return false; 3818 --FSI->FormatIdx; 3819 if (FSI->FirstDataArg != 0) 3820 --FSI->FirstDataArg; 3821 } 3822 return true; 3823 } 3824 3825 /// Checks if a the given expression evaluates to null. 3826 /// 3827 /// Returns true if the value evaluates to null. 3828 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3829 // If the expression has non-null type, it doesn't evaluate to null. 3830 if (auto nullability 3831 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3832 if (*nullability == NullabilityKind::NonNull) 3833 return false; 3834 } 3835 3836 // As a special case, transparent unions initialized with zero are 3837 // considered null for the purposes of the nonnull attribute. 3838 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3839 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3840 if (const CompoundLiteralExpr *CLE = 3841 dyn_cast<CompoundLiteralExpr>(Expr)) 3842 if (const InitListExpr *ILE = 3843 dyn_cast<InitListExpr>(CLE->getInitializer())) 3844 Expr = ILE->getInit(0); 3845 } 3846 3847 bool Result; 3848 return (!Expr->isValueDependent() && 3849 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3850 !Result); 3851 } 3852 3853 static void CheckNonNullArgument(Sema &S, 3854 const Expr *ArgExpr, 3855 SourceLocation CallSiteLoc) { 3856 if (CheckNonNullExpr(S, ArgExpr)) 3857 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3858 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3859 } 3860 3861 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3862 FormatStringInfo FSI; 3863 if ((GetFormatStringType(Format) == FST_NSString) && 3864 getFormatStringInfo(Format, false, &FSI)) { 3865 Idx = FSI.FormatIdx; 3866 return true; 3867 } 3868 return false; 3869 } 3870 3871 /// Diagnose use of %s directive in an NSString which is being passed 3872 /// as formatting string to formatting method. 3873 static void 3874 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3875 const NamedDecl *FDecl, 3876 Expr **Args, 3877 unsigned NumArgs) { 3878 unsigned Idx = 0; 3879 bool Format = false; 3880 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3881 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3882 Idx = 2; 3883 Format = true; 3884 } 3885 else 3886 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3887 if (S.GetFormatNSStringIdx(I, Idx)) { 3888 Format = true; 3889 break; 3890 } 3891 } 3892 if (!Format || NumArgs <= Idx) 3893 return; 3894 const Expr *FormatExpr = Args[Idx]; 3895 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3896 FormatExpr = CSCE->getSubExpr(); 3897 const StringLiteral *FormatString; 3898 if (const ObjCStringLiteral *OSL = 3899 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3900 FormatString = OSL->getString(); 3901 else 3902 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3903 if (!FormatString) 3904 return; 3905 if (S.FormatStringHasSArg(FormatString)) { 3906 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3907 << "%s" << 1 << 1; 3908 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3909 << FDecl->getDeclName(); 3910 } 3911 } 3912 3913 /// Determine whether the given type has a non-null nullability annotation. 3914 static bool isNonNullType(ASTContext &ctx, QualType type) { 3915 if (auto nullability = type->getNullability(ctx)) 3916 return *nullability == NullabilityKind::NonNull; 3917 3918 return false; 3919 } 3920 3921 static void CheckNonNullArguments(Sema &S, 3922 const NamedDecl *FDecl, 3923 const FunctionProtoType *Proto, 3924 ArrayRef<const Expr *> Args, 3925 SourceLocation CallSiteLoc) { 3926 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3927 3928 // Check the attributes attached to the method/function itself. 3929 llvm::SmallBitVector NonNullArgs; 3930 if (FDecl) { 3931 // Handle the nonnull attribute on the function/method declaration itself. 3932 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3933 if (!NonNull->args_size()) { 3934 // Easy case: all pointer arguments are nonnull. 3935 for (const auto *Arg : Args) 3936 if (S.isValidPointerAttrType(Arg->getType())) 3937 CheckNonNullArgument(S, Arg, CallSiteLoc); 3938 return; 3939 } 3940 3941 for (const ParamIdx &Idx : NonNull->args()) { 3942 unsigned IdxAST = Idx.getASTIndex(); 3943 if (IdxAST >= Args.size()) 3944 continue; 3945 if (NonNullArgs.empty()) 3946 NonNullArgs.resize(Args.size()); 3947 NonNullArgs.set(IdxAST); 3948 } 3949 } 3950 } 3951 3952 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3953 // Handle the nonnull attribute on the parameters of the 3954 // function/method. 3955 ArrayRef<ParmVarDecl*> parms; 3956 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3957 parms = FD->parameters(); 3958 else 3959 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3960 3961 unsigned ParamIndex = 0; 3962 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3963 I != E; ++I, ++ParamIndex) { 3964 const ParmVarDecl *PVD = *I; 3965 if (PVD->hasAttr<NonNullAttr>() || 3966 isNonNullType(S.Context, PVD->getType())) { 3967 if (NonNullArgs.empty()) 3968 NonNullArgs.resize(Args.size()); 3969 3970 NonNullArgs.set(ParamIndex); 3971 } 3972 } 3973 } else { 3974 // If we have a non-function, non-method declaration but no 3975 // function prototype, try to dig out the function prototype. 3976 if (!Proto) { 3977 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3978 QualType type = VD->getType().getNonReferenceType(); 3979 if (auto pointerType = type->getAs<PointerType>()) 3980 type = pointerType->getPointeeType(); 3981 else if (auto blockType = type->getAs<BlockPointerType>()) 3982 type = blockType->getPointeeType(); 3983 // FIXME: data member pointers? 3984 3985 // Dig out the function prototype, if there is one. 3986 Proto = type->getAs<FunctionProtoType>(); 3987 } 3988 } 3989 3990 // Fill in non-null argument information from the nullability 3991 // information on the parameter types (if we have them). 3992 if (Proto) { 3993 unsigned Index = 0; 3994 for (auto paramType : Proto->getParamTypes()) { 3995 if (isNonNullType(S.Context, paramType)) { 3996 if (NonNullArgs.empty()) 3997 NonNullArgs.resize(Args.size()); 3998 3999 NonNullArgs.set(Index); 4000 } 4001 4002 ++Index; 4003 } 4004 } 4005 } 4006 4007 // Check for non-null arguments. 4008 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4009 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4010 if (NonNullArgs[ArgIndex]) 4011 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4012 } 4013 } 4014 4015 /// Handles the checks for format strings, non-POD arguments to vararg 4016 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4017 /// attributes. 4018 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4019 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4020 bool IsMemberFunction, SourceLocation Loc, 4021 SourceRange Range, VariadicCallType CallType) { 4022 // FIXME: We should check as much as we can in the template definition. 4023 if (CurContext->isDependentContext()) 4024 return; 4025 4026 // Printf and scanf checking. 4027 llvm::SmallBitVector CheckedVarArgs; 4028 if (FDecl) { 4029 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4030 // Only create vector if there are format attributes. 4031 CheckedVarArgs.resize(Args.size()); 4032 4033 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4034 CheckedVarArgs); 4035 } 4036 } 4037 4038 // Refuse POD arguments that weren't caught by the format string 4039 // checks above. 4040 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4041 if (CallType != VariadicDoesNotApply && 4042 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4043 unsigned NumParams = Proto ? Proto->getNumParams() 4044 : FDecl && isa<FunctionDecl>(FDecl) 4045 ? cast<FunctionDecl>(FDecl)->getNumParams() 4046 : FDecl && isa<ObjCMethodDecl>(FDecl) 4047 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4048 : 0; 4049 4050 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4051 // Args[ArgIdx] can be null in malformed code. 4052 if (const Expr *Arg = Args[ArgIdx]) { 4053 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4054 checkVariadicArgument(Arg, CallType); 4055 } 4056 } 4057 } 4058 4059 if (FDecl || Proto) { 4060 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4061 4062 // Type safety checking. 4063 if (FDecl) { 4064 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4065 CheckArgumentWithTypeTag(I, Args, Loc); 4066 } 4067 } 4068 4069 if (FD) 4070 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4071 } 4072 4073 /// CheckConstructorCall - Check a constructor call for correctness and safety 4074 /// properties not enforced by the C type system. 4075 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4076 ArrayRef<const Expr *> Args, 4077 const FunctionProtoType *Proto, 4078 SourceLocation Loc) { 4079 VariadicCallType CallType = 4080 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4081 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4082 Loc, SourceRange(), CallType); 4083 } 4084 4085 /// CheckFunctionCall - Check a direct function call for various correctness 4086 /// and safety properties not strictly enforced by the C type system. 4087 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4088 const FunctionProtoType *Proto) { 4089 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4090 isa<CXXMethodDecl>(FDecl); 4091 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4092 IsMemberOperatorCall; 4093 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4094 TheCall->getCallee()); 4095 Expr** Args = TheCall->getArgs(); 4096 unsigned NumArgs = TheCall->getNumArgs(); 4097 4098 Expr *ImplicitThis = nullptr; 4099 if (IsMemberOperatorCall) { 4100 // If this is a call to a member operator, hide the first argument 4101 // from checkCall. 4102 // FIXME: Our choice of AST representation here is less than ideal. 4103 ImplicitThis = Args[0]; 4104 ++Args; 4105 --NumArgs; 4106 } else if (IsMemberFunction) 4107 ImplicitThis = 4108 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4109 4110 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4111 IsMemberFunction, TheCall->getRParenLoc(), 4112 TheCall->getCallee()->getSourceRange(), CallType); 4113 4114 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4115 // None of the checks below are needed for functions that don't have 4116 // simple names (e.g., C++ conversion functions). 4117 if (!FnInfo) 4118 return false; 4119 4120 CheckAbsoluteValueFunction(TheCall, FDecl); 4121 CheckMaxUnsignedZero(TheCall, FDecl); 4122 4123 if (getLangOpts().ObjC1) 4124 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4125 4126 unsigned CMId = FDecl->getMemoryFunctionKind(); 4127 if (CMId == 0) 4128 return false; 4129 4130 // Handle memory setting and copying functions. 4131 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4132 CheckStrlcpycatArguments(TheCall, FnInfo); 4133 else if (CMId == Builtin::BIstrncat) 4134 CheckStrncatArguments(TheCall, FnInfo); 4135 else 4136 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4137 4138 return false; 4139 } 4140 4141 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4142 ArrayRef<const Expr *> Args) { 4143 VariadicCallType CallType = 4144 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4145 4146 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4147 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4148 CallType); 4149 4150 return false; 4151 } 4152 4153 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4154 const FunctionProtoType *Proto) { 4155 QualType Ty; 4156 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4157 Ty = V->getType().getNonReferenceType(); 4158 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4159 Ty = F->getType().getNonReferenceType(); 4160 else 4161 return false; 4162 4163 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4164 !Ty->isFunctionProtoType()) 4165 return false; 4166 4167 VariadicCallType CallType; 4168 if (!Proto || !Proto->isVariadic()) { 4169 CallType = VariadicDoesNotApply; 4170 } else if (Ty->isBlockPointerType()) { 4171 CallType = VariadicBlock; 4172 } else { // Ty->isFunctionPointerType() 4173 CallType = VariadicFunction; 4174 } 4175 4176 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4177 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4178 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4179 TheCall->getCallee()->getSourceRange(), CallType); 4180 4181 return false; 4182 } 4183 4184 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4185 /// such as function pointers returned from functions. 4186 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4187 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4188 TheCall->getCallee()); 4189 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4190 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4191 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4192 TheCall->getCallee()->getSourceRange(), CallType); 4193 4194 return false; 4195 } 4196 4197 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4198 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4199 return false; 4200 4201 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4202 switch (Op) { 4203 case AtomicExpr::AO__c11_atomic_init: 4204 case AtomicExpr::AO__opencl_atomic_init: 4205 llvm_unreachable("There is no ordering argument for an init"); 4206 4207 case AtomicExpr::AO__c11_atomic_load: 4208 case AtomicExpr::AO__opencl_atomic_load: 4209 case AtomicExpr::AO__atomic_load_n: 4210 case AtomicExpr::AO__atomic_load: 4211 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4212 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4213 4214 case AtomicExpr::AO__c11_atomic_store: 4215 case AtomicExpr::AO__opencl_atomic_store: 4216 case AtomicExpr::AO__atomic_store: 4217 case AtomicExpr::AO__atomic_store_n: 4218 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4219 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4220 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4221 4222 default: 4223 return true; 4224 } 4225 } 4226 4227 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4228 AtomicExpr::AtomicOp Op) { 4229 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4230 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4231 4232 // All the non-OpenCL operations take one of the following forms. 4233 // The OpenCL operations take the __c11 forms with one extra argument for 4234 // synchronization scope. 4235 enum { 4236 // C __c11_atomic_init(A *, C) 4237 Init, 4238 4239 // C __c11_atomic_load(A *, int) 4240 Load, 4241 4242 // void __atomic_load(A *, CP, int) 4243 LoadCopy, 4244 4245 // void __atomic_store(A *, CP, int) 4246 Copy, 4247 4248 // C __c11_atomic_add(A *, M, int) 4249 Arithmetic, 4250 4251 // C __atomic_exchange_n(A *, CP, int) 4252 Xchg, 4253 4254 // void __atomic_exchange(A *, C *, CP, int) 4255 GNUXchg, 4256 4257 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4258 C11CmpXchg, 4259 4260 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4261 GNUCmpXchg 4262 } Form = Init; 4263 4264 const unsigned NumForm = GNUCmpXchg + 1; 4265 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4266 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4267 // where: 4268 // C is an appropriate type, 4269 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4270 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4271 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4272 // the int parameters are for orderings. 4273 4274 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4275 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4276 "need to update code for modified forms"); 4277 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4278 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4279 AtomicExpr::AO__atomic_load, 4280 "need to update code for modified C11 atomics"); 4281 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4282 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4283 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4284 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4285 IsOpenCL; 4286 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4287 Op == AtomicExpr::AO__atomic_store_n || 4288 Op == AtomicExpr::AO__atomic_exchange_n || 4289 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4290 bool IsAddSub = false; 4291 bool IsMinMax = false; 4292 4293 switch (Op) { 4294 case AtomicExpr::AO__c11_atomic_init: 4295 case AtomicExpr::AO__opencl_atomic_init: 4296 Form = Init; 4297 break; 4298 4299 case AtomicExpr::AO__c11_atomic_load: 4300 case AtomicExpr::AO__opencl_atomic_load: 4301 case AtomicExpr::AO__atomic_load_n: 4302 Form = Load; 4303 break; 4304 4305 case AtomicExpr::AO__atomic_load: 4306 Form = LoadCopy; 4307 break; 4308 4309 case AtomicExpr::AO__c11_atomic_store: 4310 case AtomicExpr::AO__opencl_atomic_store: 4311 case AtomicExpr::AO__atomic_store: 4312 case AtomicExpr::AO__atomic_store_n: 4313 Form = Copy; 4314 break; 4315 4316 case AtomicExpr::AO__c11_atomic_fetch_add: 4317 case AtomicExpr::AO__c11_atomic_fetch_sub: 4318 case AtomicExpr::AO__opencl_atomic_fetch_add: 4319 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4320 case AtomicExpr::AO__opencl_atomic_fetch_min: 4321 case AtomicExpr::AO__opencl_atomic_fetch_max: 4322 case AtomicExpr::AO__atomic_fetch_add: 4323 case AtomicExpr::AO__atomic_fetch_sub: 4324 case AtomicExpr::AO__atomic_add_fetch: 4325 case AtomicExpr::AO__atomic_sub_fetch: 4326 IsAddSub = true; 4327 LLVM_FALLTHROUGH; 4328 case AtomicExpr::AO__c11_atomic_fetch_and: 4329 case AtomicExpr::AO__c11_atomic_fetch_or: 4330 case AtomicExpr::AO__c11_atomic_fetch_xor: 4331 case AtomicExpr::AO__opencl_atomic_fetch_and: 4332 case AtomicExpr::AO__opencl_atomic_fetch_or: 4333 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4334 case AtomicExpr::AO__atomic_fetch_and: 4335 case AtomicExpr::AO__atomic_fetch_or: 4336 case AtomicExpr::AO__atomic_fetch_xor: 4337 case AtomicExpr::AO__atomic_fetch_nand: 4338 case AtomicExpr::AO__atomic_and_fetch: 4339 case AtomicExpr::AO__atomic_or_fetch: 4340 case AtomicExpr::AO__atomic_xor_fetch: 4341 case AtomicExpr::AO__atomic_nand_fetch: 4342 Form = Arithmetic; 4343 break; 4344 4345 case AtomicExpr::AO__atomic_fetch_min: 4346 case AtomicExpr::AO__atomic_fetch_max: 4347 IsMinMax = true; 4348 Form = Arithmetic; 4349 break; 4350 4351 case AtomicExpr::AO__c11_atomic_exchange: 4352 case AtomicExpr::AO__opencl_atomic_exchange: 4353 case AtomicExpr::AO__atomic_exchange_n: 4354 Form = Xchg; 4355 break; 4356 4357 case AtomicExpr::AO__atomic_exchange: 4358 Form = GNUXchg; 4359 break; 4360 4361 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4362 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4363 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4364 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4365 Form = C11CmpXchg; 4366 break; 4367 4368 case AtomicExpr::AO__atomic_compare_exchange: 4369 case AtomicExpr::AO__atomic_compare_exchange_n: 4370 Form = GNUCmpXchg; 4371 break; 4372 } 4373 4374 unsigned AdjustedNumArgs = NumArgs[Form]; 4375 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4376 ++AdjustedNumArgs; 4377 // Check we have the right number of arguments. 4378 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4379 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4380 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4381 << TheCall->getCallee()->getSourceRange(); 4382 return ExprError(); 4383 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4384 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4385 diag::err_typecheck_call_too_many_args) 4386 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4387 << TheCall->getCallee()->getSourceRange(); 4388 return ExprError(); 4389 } 4390 4391 // Inspect the first argument of the atomic operation. 4392 Expr *Ptr = TheCall->getArg(0); 4393 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4394 if (ConvertedPtr.isInvalid()) 4395 return ExprError(); 4396 4397 Ptr = ConvertedPtr.get(); 4398 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4399 if (!pointerType) { 4400 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4401 << Ptr->getType() << Ptr->getSourceRange(); 4402 return ExprError(); 4403 } 4404 4405 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4406 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4407 QualType ValType = AtomTy; // 'C' 4408 if (IsC11) { 4409 if (!AtomTy->isAtomicType()) { 4410 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4411 << Ptr->getType() << Ptr->getSourceRange(); 4412 return ExprError(); 4413 } 4414 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4415 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4416 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4417 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4418 << Ptr->getSourceRange(); 4419 return ExprError(); 4420 } 4421 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4422 } else if (Form != Load && Form != LoadCopy) { 4423 if (ValType.isConstQualified()) { 4424 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4425 << Ptr->getType() << Ptr->getSourceRange(); 4426 return ExprError(); 4427 } 4428 } 4429 4430 // For an arithmetic operation, the implied arithmetic must be well-formed. 4431 if (Form == Arithmetic) { 4432 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4433 if (IsAddSub && !ValType->isIntegerType() 4434 && !ValType->isPointerType()) { 4435 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4436 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4437 return ExprError(); 4438 } 4439 if (IsMinMax) { 4440 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4441 if (!BT || (BT->getKind() != BuiltinType::Int && 4442 BT->getKind() != BuiltinType::UInt)) { 4443 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4444 return ExprError(); 4445 } 4446 } 4447 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4448 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4449 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4450 return ExprError(); 4451 } 4452 if (IsC11 && ValType->isPointerType() && 4453 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4454 diag::err_incomplete_type)) { 4455 return ExprError(); 4456 } 4457 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4458 // For __atomic_*_n operations, the value type must be a scalar integral or 4459 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4460 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4461 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4462 return ExprError(); 4463 } 4464 4465 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4466 !AtomTy->isScalarType()) { 4467 // For GNU atomics, require a trivially-copyable type. This is not part of 4468 // the GNU atomics specification, but we enforce it for sanity. 4469 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4470 << Ptr->getType() << Ptr->getSourceRange(); 4471 return ExprError(); 4472 } 4473 4474 switch (ValType.getObjCLifetime()) { 4475 case Qualifiers::OCL_None: 4476 case Qualifiers::OCL_ExplicitNone: 4477 // okay 4478 break; 4479 4480 case Qualifiers::OCL_Weak: 4481 case Qualifiers::OCL_Strong: 4482 case Qualifiers::OCL_Autoreleasing: 4483 // FIXME: Can this happen? By this point, ValType should be known 4484 // to be trivially copyable. 4485 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4486 << ValType << Ptr->getSourceRange(); 4487 return ExprError(); 4488 } 4489 4490 // All atomic operations have an overload which takes a pointer to a volatile 4491 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4492 // into the result or the other operands. Similarly atomic_load takes a 4493 // pointer to a const 'A'. 4494 ValType.removeLocalVolatile(); 4495 ValType.removeLocalConst(); 4496 QualType ResultType = ValType; 4497 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4498 Form == Init) 4499 ResultType = Context.VoidTy; 4500 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4501 ResultType = Context.BoolTy; 4502 4503 // The type of a parameter passed 'by value'. In the GNU atomics, such 4504 // arguments are actually passed as pointers. 4505 QualType ByValType = ValType; // 'CP' 4506 bool IsPassedByAddress = false; 4507 if (!IsC11 && !IsN) { 4508 ByValType = Ptr->getType(); 4509 IsPassedByAddress = true; 4510 } 4511 4512 // The first argument's non-CV pointer type is used to deduce the type of 4513 // subsequent arguments, except for: 4514 // - weak flag (always converted to bool) 4515 // - memory order (always converted to int) 4516 // - scope (always converted to int) 4517 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4518 QualType Ty; 4519 if (i < NumVals[Form] + 1) { 4520 switch (i) { 4521 case 0: 4522 // The first argument is always a pointer. It has a fixed type. 4523 // It is always dereferenced, a nullptr is undefined. 4524 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4525 // Nothing else to do: we already know all we want about this pointer. 4526 continue; 4527 case 1: 4528 // The second argument is the non-atomic operand. For arithmetic, this 4529 // is always passed by value, and for a compare_exchange it is always 4530 // passed by address. For the rest, GNU uses by-address and C11 uses 4531 // by-value. 4532 assert(Form != Load); 4533 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4534 Ty = ValType; 4535 else if (Form == Copy || Form == Xchg) { 4536 if (IsPassedByAddress) 4537 // The value pointer is always dereferenced, a nullptr is undefined. 4538 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4539 Ty = ByValType; 4540 } else if (Form == Arithmetic) 4541 Ty = Context.getPointerDiffType(); 4542 else { 4543 Expr *ValArg = TheCall->getArg(i); 4544 // The value pointer is always dereferenced, a nullptr is undefined. 4545 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4546 LangAS AS = LangAS::Default; 4547 // Keep address space of non-atomic pointer type. 4548 if (const PointerType *PtrTy = 4549 ValArg->getType()->getAs<PointerType>()) { 4550 AS = PtrTy->getPointeeType().getAddressSpace(); 4551 } 4552 Ty = Context.getPointerType( 4553 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4554 } 4555 break; 4556 case 2: 4557 // The third argument to compare_exchange / GNU exchange is the desired 4558 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4559 if (IsPassedByAddress) 4560 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4561 Ty = ByValType; 4562 break; 4563 case 3: 4564 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4565 Ty = Context.BoolTy; 4566 break; 4567 } 4568 } else { 4569 // The order(s) and scope are always converted to int. 4570 Ty = Context.IntTy; 4571 } 4572 4573 InitializedEntity Entity = 4574 InitializedEntity::InitializeParameter(Context, Ty, false); 4575 ExprResult Arg = TheCall->getArg(i); 4576 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4577 if (Arg.isInvalid()) 4578 return true; 4579 TheCall->setArg(i, Arg.get()); 4580 } 4581 4582 // Permute the arguments into a 'consistent' order. 4583 SmallVector<Expr*, 5> SubExprs; 4584 SubExprs.push_back(Ptr); 4585 switch (Form) { 4586 case Init: 4587 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4588 SubExprs.push_back(TheCall->getArg(1)); // Val1 4589 break; 4590 case Load: 4591 SubExprs.push_back(TheCall->getArg(1)); // Order 4592 break; 4593 case LoadCopy: 4594 case Copy: 4595 case Arithmetic: 4596 case Xchg: 4597 SubExprs.push_back(TheCall->getArg(2)); // Order 4598 SubExprs.push_back(TheCall->getArg(1)); // Val1 4599 break; 4600 case GNUXchg: 4601 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4602 SubExprs.push_back(TheCall->getArg(3)); // Order 4603 SubExprs.push_back(TheCall->getArg(1)); // Val1 4604 SubExprs.push_back(TheCall->getArg(2)); // Val2 4605 break; 4606 case C11CmpXchg: 4607 SubExprs.push_back(TheCall->getArg(3)); // Order 4608 SubExprs.push_back(TheCall->getArg(1)); // Val1 4609 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4610 SubExprs.push_back(TheCall->getArg(2)); // Val2 4611 break; 4612 case GNUCmpXchg: 4613 SubExprs.push_back(TheCall->getArg(4)); // Order 4614 SubExprs.push_back(TheCall->getArg(1)); // Val1 4615 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4616 SubExprs.push_back(TheCall->getArg(2)); // Val2 4617 SubExprs.push_back(TheCall->getArg(3)); // Weak 4618 break; 4619 } 4620 4621 if (SubExprs.size() >= 2 && Form != Init) { 4622 llvm::APSInt Result(32); 4623 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4624 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4625 Diag(SubExprs[1]->getBeginLoc(), 4626 diag::warn_atomic_op_has_invalid_memory_order) 4627 << SubExprs[1]->getSourceRange(); 4628 } 4629 4630 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4631 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4632 llvm::APSInt Result(32); 4633 if (Scope->isIntegerConstantExpr(Result, Context) && 4634 !ScopeModel->isValid(Result.getZExtValue())) { 4635 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4636 << Scope->getSourceRange(); 4637 } 4638 SubExprs.push_back(Scope); 4639 } 4640 4641 AtomicExpr *AE = 4642 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4643 ResultType, Op, TheCall->getRParenLoc()); 4644 4645 if ((Op == AtomicExpr::AO__c11_atomic_load || 4646 Op == AtomicExpr::AO__c11_atomic_store || 4647 Op == AtomicExpr::AO__opencl_atomic_load || 4648 Op == AtomicExpr::AO__opencl_atomic_store ) && 4649 Context.AtomicUsesUnsupportedLibcall(AE)) 4650 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4651 << ((Op == AtomicExpr::AO__c11_atomic_load || 4652 Op == AtomicExpr::AO__opencl_atomic_load) 4653 ? 0 4654 : 1); 4655 4656 return AE; 4657 } 4658 4659 /// checkBuiltinArgument - Given a call to a builtin function, perform 4660 /// normal type-checking on the given argument, updating the call in 4661 /// place. This is useful when a builtin function requires custom 4662 /// type-checking for some of its arguments but not necessarily all of 4663 /// them. 4664 /// 4665 /// Returns true on error. 4666 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4667 FunctionDecl *Fn = E->getDirectCallee(); 4668 assert(Fn && "builtin call without direct callee!"); 4669 4670 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4671 InitializedEntity Entity = 4672 InitializedEntity::InitializeParameter(S.Context, Param); 4673 4674 ExprResult Arg = E->getArg(0); 4675 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4676 if (Arg.isInvalid()) 4677 return true; 4678 4679 E->setArg(ArgIndex, Arg.get()); 4680 return false; 4681 } 4682 4683 /// We have a call to a function like __sync_fetch_and_add, which is an 4684 /// overloaded function based on the pointer type of its first argument. 4685 /// The main ActOnCallExpr routines have already promoted the types of 4686 /// arguments because all of these calls are prototyped as void(...). 4687 /// 4688 /// This function goes through and does final semantic checking for these 4689 /// builtins, as well as generating any warnings. 4690 ExprResult 4691 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4692 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4693 Expr *Callee = TheCall->getCallee(); 4694 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4695 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4696 4697 // Ensure that we have at least one argument to do type inference from. 4698 if (TheCall->getNumArgs() < 1) { 4699 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4700 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4701 return ExprError(); 4702 } 4703 4704 // Inspect the first argument of the atomic builtin. This should always be 4705 // a pointer type, whose element is an integral scalar or pointer type. 4706 // Because it is a pointer type, we don't have to worry about any implicit 4707 // casts here. 4708 // FIXME: We don't allow floating point scalars as input. 4709 Expr *FirstArg = TheCall->getArg(0); 4710 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4711 if (FirstArgResult.isInvalid()) 4712 return ExprError(); 4713 FirstArg = FirstArgResult.get(); 4714 TheCall->setArg(0, FirstArg); 4715 4716 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4717 if (!pointerType) { 4718 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4719 << FirstArg->getType() << FirstArg->getSourceRange(); 4720 return ExprError(); 4721 } 4722 4723 QualType ValType = pointerType->getPointeeType(); 4724 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4725 !ValType->isBlockPointerType()) { 4726 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4727 << FirstArg->getType() << FirstArg->getSourceRange(); 4728 return ExprError(); 4729 } 4730 4731 if (ValType.isConstQualified()) { 4732 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4733 << FirstArg->getType() << FirstArg->getSourceRange(); 4734 return ExprError(); 4735 } 4736 4737 switch (ValType.getObjCLifetime()) { 4738 case Qualifiers::OCL_None: 4739 case Qualifiers::OCL_ExplicitNone: 4740 // okay 4741 break; 4742 4743 case Qualifiers::OCL_Weak: 4744 case Qualifiers::OCL_Strong: 4745 case Qualifiers::OCL_Autoreleasing: 4746 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4747 << ValType << FirstArg->getSourceRange(); 4748 return ExprError(); 4749 } 4750 4751 // Strip any qualifiers off ValType. 4752 ValType = ValType.getUnqualifiedType(); 4753 4754 // The majority of builtins return a value, but a few have special return 4755 // types, so allow them to override appropriately below. 4756 QualType ResultType = ValType; 4757 4758 // We need to figure out which concrete builtin this maps onto. For example, 4759 // __sync_fetch_and_add with a 2 byte object turns into 4760 // __sync_fetch_and_add_2. 4761 #define BUILTIN_ROW(x) \ 4762 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4763 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4764 4765 static const unsigned BuiltinIndices[][5] = { 4766 BUILTIN_ROW(__sync_fetch_and_add), 4767 BUILTIN_ROW(__sync_fetch_and_sub), 4768 BUILTIN_ROW(__sync_fetch_and_or), 4769 BUILTIN_ROW(__sync_fetch_and_and), 4770 BUILTIN_ROW(__sync_fetch_and_xor), 4771 BUILTIN_ROW(__sync_fetch_and_nand), 4772 4773 BUILTIN_ROW(__sync_add_and_fetch), 4774 BUILTIN_ROW(__sync_sub_and_fetch), 4775 BUILTIN_ROW(__sync_and_and_fetch), 4776 BUILTIN_ROW(__sync_or_and_fetch), 4777 BUILTIN_ROW(__sync_xor_and_fetch), 4778 BUILTIN_ROW(__sync_nand_and_fetch), 4779 4780 BUILTIN_ROW(__sync_val_compare_and_swap), 4781 BUILTIN_ROW(__sync_bool_compare_and_swap), 4782 BUILTIN_ROW(__sync_lock_test_and_set), 4783 BUILTIN_ROW(__sync_lock_release), 4784 BUILTIN_ROW(__sync_swap) 4785 }; 4786 #undef BUILTIN_ROW 4787 4788 // Determine the index of the size. 4789 unsigned SizeIndex; 4790 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4791 case 1: SizeIndex = 0; break; 4792 case 2: SizeIndex = 1; break; 4793 case 4: SizeIndex = 2; break; 4794 case 8: SizeIndex = 3; break; 4795 case 16: SizeIndex = 4; break; 4796 default: 4797 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4798 << FirstArg->getType() << FirstArg->getSourceRange(); 4799 return ExprError(); 4800 } 4801 4802 // Each of these builtins has one pointer argument, followed by some number of 4803 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4804 // that we ignore. Find out which row of BuiltinIndices to read from as well 4805 // as the number of fixed args. 4806 unsigned BuiltinID = FDecl->getBuiltinID(); 4807 unsigned BuiltinIndex, NumFixed = 1; 4808 bool WarnAboutSemanticsChange = false; 4809 switch (BuiltinID) { 4810 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4811 case Builtin::BI__sync_fetch_and_add: 4812 case Builtin::BI__sync_fetch_and_add_1: 4813 case Builtin::BI__sync_fetch_and_add_2: 4814 case Builtin::BI__sync_fetch_and_add_4: 4815 case Builtin::BI__sync_fetch_and_add_8: 4816 case Builtin::BI__sync_fetch_and_add_16: 4817 BuiltinIndex = 0; 4818 break; 4819 4820 case Builtin::BI__sync_fetch_and_sub: 4821 case Builtin::BI__sync_fetch_and_sub_1: 4822 case Builtin::BI__sync_fetch_and_sub_2: 4823 case Builtin::BI__sync_fetch_and_sub_4: 4824 case Builtin::BI__sync_fetch_and_sub_8: 4825 case Builtin::BI__sync_fetch_and_sub_16: 4826 BuiltinIndex = 1; 4827 break; 4828 4829 case Builtin::BI__sync_fetch_and_or: 4830 case Builtin::BI__sync_fetch_and_or_1: 4831 case Builtin::BI__sync_fetch_and_or_2: 4832 case Builtin::BI__sync_fetch_and_or_4: 4833 case Builtin::BI__sync_fetch_and_or_8: 4834 case Builtin::BI__sync_fetch_and_or_16: 4835 BuiltinIndex = 2; 4836 break; 4837 4838 case Builtin::BI__sync_fetch_and_and: 4839 case Builtin::BI__sync_fetch_and_and_1: 4840 case Builtin::BI__sync_fetch_and_and_2: 4841 case Builtin::BI__sync_fetch_and_and_4: 4842 case Builtin::BI__sync_fetch_and_and_8: 4843 case Builtin::BI__sync_fetch_and_and_16: 4844 BuiltinIndex = 3; 4845 break; 4846 4847 case Builtin::BI__sync_fetch_and_xor: 4848 case Builtin::BI__sync_fetch_and_xor_1: 4849 case Builtin::BI__sync_fetch_and_xor_2: 4850 case Builtin::BI__sync_fetch_and_xor_4: 4851 case Builtin::BI__sync_fetch_and_xor_8: 4852 case Builtin::BI__sync_fetch_and_xor_16: 4853 BuiltinIndex = 4; 4854 break; 4855 4856 case Builtin::BI__sync_fetch_and_nand: 4857 case Builtin::BI__sync_fetch_and_nand_1: 4858 case Builtin::BI__sync_fetch_and_nand_2: 4859 case Builtin::BI__sync_fetch_and_nand_4: 4860 case Builtin::BI__sync_fetch_and_nand_8: 4861 case Builtin::BI__sync_fetch_and_nand_16: 4862 BuiltinIndex = 5; 4863 WarnAboutSemanticsChange = true; 4864 break; 4865 4866 case Builtin::BI__sync_add_and_fetch: 4867 case Builtin::BI__sync_add_and_fetch_1: 4868 case Builtin::BI__sync_add_and_fetch_2: 4869 case Builtin::BI__sync_add_and_fetch_4: 4870 case Builtin::BI__sync_add_and_fetch_8: 4871 case Builtin::BI__sync_add_and_fetch_16: 4872 BuiltinIndex = 6; 4873 break; 4874 4875 case Builtin::BI__sync_sub_and_fetch: 4876 case Builtin::BI__sync_sub_and_fetch_1: 4877 case Builtin::BI__sync_sub_and_fetch_2: 4878 case Builtin::BI__sync_sub_and_fetch_4: 4879 case Builtin::BI__sync_sub_and_fetch_8: 4880 case Builtin::BI__sync_sub_and_fetch_16: 4881 BuiltinIndex = 7; 4882 break; 4883 4884 case Builtin::BI__sync_and_and_fetch: 4885 case Builtin::BI__sync_and_and_fetch_1: 4886 case Builtin::BI__sync_and_and_fetch_2: 4887 case Builtin::BI__sync_and_and_fetch_4: 4888 case Builtin::BI__sync_and_and_fetch_8: 4889 case Builtin::BI__sync_and_and_fetch_16: 4890 BuiltinIndex = 8; 4891 break; 4892 4893 case Builtin::BI__sync_or_and_fetch: 4894 case Builtin::BI__sync_or_and_fetch_1: 4895 case Builtin::BI__sync_or_and_fetch_2: 4896 case Builtin::BI__sync_or_and_fetch_4: 4897 case Builtin::BI__sync_or_and_fetch_8: 4898 case Builtin::BI__sync_or_and_fetch_16: 4899 BuiltinIndex = 9; 4900 break; 4901 4902 case Builtin::BI__sync_xor_and_fetch: 4903 case Builtin::BI__sync_xor_and_fetch_1: 4904 case Builtin::BI__sync_xor_and_fetch_2: 4905 case Builtin::BI__sync_xor_and_fetch_4: 4906 case Builtin::BI__sync_xor_and_fetch_8: 4907 case Builtin::BI__sync_xor_and_fetch_16: 4908 BuiltinIndex = 10; 4909 break; 4910 4911 case Builtin::BI__sync_nand_and_fetch: 4912 case Builtin::BI__sync_nand_and_fetch_1: 4913 case Builtin::BI__sync_nand_and_fetch_2: 4914 case Builtin::BI__sync_nand_and_fetch_4: 4915 case Builtin::BI__sync_nand_and_fetch_8: 4916 case Builtin::BI__sync_nand_and_fetch_16: 4917 BuiltinIndex = 11; 4918 WarnAboutSemanticsChange = true; 4919 break; 4920 4921 case Builtin::BI__sync_val_compare_and_swap: 4922 case Builtin::BI__sync_val_compare_and_swap_1: 4923 case Builtin::BI__sync_val_compare_and_swap_2: 4924 case Builtin::BI__sync_val_compare_and_swap_4: 4925 case Builtin::BI__sync_val_compare_and_swap_8: 4926 case Builtin::BI__sync_val_compare_and_swap_16: 4927 BuiltinIndex = 12; 4928 NumFixed = 2; 4929 break; 4930 4931 case Builtin::BI__sync_bool_compare_and_swap: 4932 case Builtin::BI__sync_bool_compare_and_swap_1: 4933 case Builtin::BI__sync_bool_compare_and_swap_2: 4934 case Builtin::BI__sync_bool_compare_and_swap_4: 4935 case Builtin::BI__sync_bool_compare_and_swap_8: 4936 case Builtin::BI__sync_bool_compare_and_swap_16: 4937 BuiltinIndex = 13; 4938 NumFixed = 2; 4939 ResultType = Context.BoolTy; 4940 break; 4941 4942 case Builtin::BI__sync_lock_test_and_set: 4943 case Builtin::BI__sync_lock_test_and_set_1: 4944 case Builtin::BI__sync_lock_test_and_set_2: 4945 case Builtin::BI__sync_lock_test_and_set_4: 4946 case Builtin::BI__sync_lock_test_and_set_8: 4947 case Builtin::BI__sync_lock_test_and_set_16: 4948 BuiltinIndex = 14; 4949 break; 4950 4951 case Builtin::BI__sync_lock_release: 4952 case Builtin::BI__sync_lock_release_1: 4953 case Builtin::BI__sync_lock_release_2: 4954 case Builtin::BI__sync_lock_release_4: 4955 case Builtin::BI__sync_lock_release_8: 4956 case Builtin::BI__sync_lock_release_16: 4957 BuiltinIndex = 15; 4958 NumFixed = 0; 4959 ResultType = Context.VoidTy; 4960 break; 4961 4962 case Builtin::BI__sync_swap: 4963 case Builtin::BI__sync_swap_1: 4964 case Builtin::BI__sync_swap_2: 4965 case Builtin::BI__sync_swap_4: 4966 case Builtin::BI__sync_swap_8: 4967 case Builtin::BI__sync_swap_16: 4968 BuiltinIndex = 16; 4969 break; 4970 } 4971 4972 // Now that we know how many fixed arguments we expect, first check that we 4973 // have at least that many. 4974 if (TheCall->getNumArgs() < 1+NumFixed) { 4975 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4976 << 0 << 1 + NumFixed << TheCall->getNumArgs() 4977 << Callee->getSourceRange(); 4978 return ExprError(); 4979 } 4980 4981 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 4982 << Callee->getSourceRange(); 4983 4984 if (WarnAboutSemanticsChange) { 4985 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4986 << Callee->getSourceRange(); 4987 } 4988 4989 // Get the decl for the concrete builtin from this, we can tell what the 4990 // concrete integer type we should convert to is. 4991 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4992 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4993 FunctionDecl *NewBuiltinDecl; 4994 if (NewBuiltinID == BuiltinID) 4995 NewBuiltinDecl = FDecl; 4996 else { 4997 // Perform builtin lookup to avoid redeclaring it. 4998 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4999 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5000 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5001 assert(Res.getFoundDecl()); 5002 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5003 if (!NewBuiltinDecl) 5004 return ExprError(); 5005 } 5006 5007 // The first argument --- the pointer --- has a fixed type; we 5008 // deduce the types of the rest of the arguments accordingly. Walk 5009 // the remaining arguments, converting them to the deduced value type. 5010 for (unsigned i = 0; i != NumFixed; ++i) { 5011 ExprResult Arg = TheCall->getArg(i+1); 5012 5013 // GCC does an implicit conversion to the pointer or integer ValType. This 5014 // can fail in some cases (1i -> int**), check for this error case now. 5015 // Initialize the argument. 5016 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5017 ValType, /*consume*/ false); 5018 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5019 if (Arg.isInvalid()) 5020 return ExprError(); 5021 5022 // Okay, we have something that *can* be converted to the right type. Check 5023 // to see if there is a potentially weird extension going on here. This can 5024 // happen when you do an atomic operation on something like an char* and 5025 // pass in 42. The 42 gets converted to char. This is even more strange 5026 // for things like 45.123 -> char, etc. 5027 // FIXME: Do this check. 5028 TheCall->setArg(i+1, Arg.get()); 5029 } 5030 5031 ASTContext& Context = this->getASTContext(); 5032 5033 // Create a new DeclRefExpr to refer to the new decl. 5034 DeclRefExpr* NewDRE = DeclRefExpr::Create( 5035 Context, 5036 DRE->getQualifierLoc(), 5037 SourceLocation(), 5038 NewBuiltinDecl, 5039 /*enclosing*/ false, 5040 DRE->getLocation(), 5041 Context.BuiltinFnTy, 5042 DRE->getValueKind()); 5043 5044 // Set the callee in the CallExpr. 5045 // FIXME: This loses syntactic information. 5046 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5047 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5048 CK_BuiltinFnToFnPtr); 5049 TheCall->setCallee(PromotedCall.get()); 5050 5051 // Change the result type of the call to match the original value type. This 5052 // is arbitrary, but the codegen for these builtins ins design to handle it 5053 // gracefully. 5054 TheCall->setType(ResultType); 5055 5056 return TheCallResult; 5057 } 5058 5059 /// SemaBuiltinNontemporalOverloaded - We have a call to 5060 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5061 /// overloaded function based on the pointer type of its last argument. 5062 /// 5063 /// This function goes through and does final semantic checking for these 5064 /// builtins. 5065 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5066 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5067 DeclRefExpr *DRE = 5068 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5069 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5070 unsigned BuiltinID = FDecl->getBuiltinID(); 5071 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5072 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5073 "Unexpected nontemporal load/store builtin!"); 5074 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5075 unsigned numArgs = isStore ? 2 : 1; 5076 5077 // Ensure that we have the proper number of arguments. 5078 if (checkArgCount(*this, TheCall, numArgs)) 5079 return ExprError(); 5080 5081 // Inspect the last argument of the nontemporal builtin. This should always 5082 // be a pointer type, from which we imply the type of the memory access. 5083 // Because it is a pointer type, we don't have to worry about any implicit 5084 // casts here. 5085 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5086 ExprResult PointerArgResult = 5087 DefaultFunctionArrayLvalueConversion(PointerArg); 5088 5089 if (PointerArgResult.isInvalid()) 5090 return ExprError(); 5091 PointerArg = PointerArgResult.get(); 5092 TheCall->setArg(numArgs - 1, PointerArg); 5093 5094 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5095 if (!pointerType) { 5096 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5097 << PointerArg->getType() << PointerArg->getSourceRange(); 5098 return ExprError(); 5099 } 5100 5101 QualType ValType = pointerType->getPointeeType(); 5102 5103 // Strip any qualifiers off ValType. 5104 ValType = ValType.getUnqualifiedType(); 5105 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5106 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5107 !ValType->isVectorType()) { 5108 Diag(DRE->getBeginLoc(), 5109 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5110 << PointerArg->getType() << PointerArg->getSourceRange(); 5111 return ExprError(); 5112 } 5113 5114 if (!isStore) { 5115 TheCall->setType(ValType); 5116 return TheCallResult; 5117 } 5118 5119 ExprResult ValArg = TheCall->getArg(0); 5120 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5121 Context, ValType, /*consume*/ false); 5122 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5123 if (ValArg.isInvalid()) 5124 return ExprError(); 5125 5126 TheCall->setArg(0, ValArg.get()); 5127 TheCall->setType(Context.VoidTy); 5128 return TheCallResult; 5129 } 5130 5131 /// CheckObjCString - Checks that the argument to the builtin 5132 /// CFString constructor is correct 5133 /// Note: It might also make sense to do the UTF-16 conversion here (would 5134 /// simplify the backend). 5135 bool Sema::CheckObjCString(Expr *Arg) { 5136 Arg = Arg->IgnoreParenCasts(); 5137 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5138 5139 if (!Literal || !Literal->isAscii()) { 5140 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5141 << Arg->getSourceRange(); 5142 return true; 5143 } 5144 5145 if (Literal->containsNonAsciiOrNull()) { 5146 StringRef String = Literal->getString(); 5147 unsigned NumBytes = String.size(); 5148 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5149 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5150 llvm::UTF16 *ToPtr = &ToBuf[0]; 5151 5152 llvm::ConversionResult Result = 5153 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5154 ToPtr + NumBytes, llvm::strictConversion); 5155 // Check for conversion failure. 5156 if (Result != llvm::conversionOK) 5157 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5158 << Arg->getSourceRange(); 5159 } 5160 return false; 5161 } 5162 5163 /// CheckObjCString - Checks that the format string argument to the os_log() 5164 /// and os_trace() functions is correct, and converts it to const char *. 5165 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5166 Arg = Arg->IgnoreParenCasts(); 5167 auto *Literal = dyn_cast<StringLiteral>(Arg); 5168 if (!Literal) { 5169 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5170 Literal = ObjcLiteral->getString(); 5171 } 5172 } 5173 5174 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5175 return ExprError( 5176 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5177 << Arg->getSourceRange()); 5178 } 5179 5180 ExprResult Result(Literal); 5181 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5182 InitializedEntity Entity = 5183 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5184 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5185 return Result; 5186 } 5187 5188 /// Check that the user is calling the appropriate va_start builtin for the 5189 /// target and calling convention. 5190 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5191 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5192 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5193 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5194 bool IsWindows = TT.isOSWindows(); 5195 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5196 if (IsX64 || IsAArch64) { 5197 CallingConv CC = CC_C; 5198 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5199 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5200 if (IsMSVAStart) { 5201 // Don't allow this in System V ABI functions. 5202 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5203 return S.Diag(Fn->getBeginLoc(), 5204 diag::err_ms_va_start_used_in_sysv_function); 5205 } else { 5206 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5207 // On x64 Windows, don't allow this in System V ABI functions. 5208 // (Yes, that means there's no corresponding way to support variadic 5209 // System V ABI functions on Windows.) 5210 if ((IsWindows && CC == CC_X86_64SysV) || 5211 (!IsWindows && CC == CC_Win64)) 5212 return S.Diag(Fn->getBeginLoc(), 5213 diag::err_va_start_used_in_wrong_abi_function) 5214 << !IsWindows; 5215 } 5216 return false; 5217 } 5218 5219 if (IsMSVAStart) 5220 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5221 return false; 5222 } 5223 5224 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5225 ParmVarDecl **LastParam = nullptr) { 5226 // Determine whether the current function, block, or obj-c method is variadic 5227 // and get its parameter list. 5228 bool IsVariadic = false; 5229 ArrayRef<ParmVarDecl *> Params; 5230 DeclContext *Caller = S.CurContext; 5231 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5232 IsVariadic = Block->isVariadic(); 5233 Params = Block->parameters(); 5234 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5235 IsVariadic = FD->isVariadic(); 5236 Params = FD->parameters(); 5237 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5238 IsVariadic = MD->isVariadic(); 5239 // FIXME: This isn't correct for methods (results in bogus warning). 5240 Params = MD->parameters(); 5241 } else if (isa<CapturedDecl>(Caller)) { 5242 // We don't support va_start in a CapturedDecl. 5243 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5244 return true; 5245 } else { 5246 // This must be some other declcontext that parses exprs. 5247 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5248 return true; 5249 } 5250 5251 if (!IsVariadic) { 5252 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5253 return true; 5254 } 5255 5256 if (LastParam) 5257 *LastParam = Params.empty() ? nullptr : Params.back(); 5258 5259 return false; 5260 } 5261 5262 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5263 /// for validity. Emit an error and return true on failure; return false 5264 /// on success. 5265 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5266 Expr *Fn = TheCall->getCallee(); 5267 5268 if (checkVAStartABI(*this, BuiltinID, Fn)) 5269 return true; 5270 5271 if (TheCall->getNumArgs() > 2) { 5272 Diag(TheCall->getArg(2)->getBeginLoc(), 5273 diag::err_typecheck_call_too_many_args) 5274 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5275 << Fn->getSourceRange() 5276 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5277 (*(TheCall->arg_end() - 1))->getEndLoc()); 5278 return true; 5279 } 5280 5281 if (TheCall->getNumArgs() < 2) { 5282 return Diag(TheCall->getEndLoc(), 5283 diag::err_typecheck_call_too_few_args_at_least) 5284 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5285 } 5286 5287 // Type-check the first argument normally. 5288 if (checkBuiltinArgument(*this, TheCall, 0)) 5289 return true; 5290 5291 // Check that the current function is variadic, and get its last parameter. 5292 ParmVarDecl *LastParam; 5293 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5294 return true; 5295 5296 // Verify that the second argument to the builtin is the last argument of the 5297 // current function or method. 5298 bool SecondArgIsLastNamedArgument = false; 5299 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5300 5301 // These are valid if SecondArgIsLastNamedArgument is false after the next 5302 // block. 5303 QualType Type; 5304 SourceLocation ParamLoc; 5305 bool IsCRegister = false; 5306 5307 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5308 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5309 SecondArgIsLastNamedArgument = PV == LastParam; 5310 5311 Type = PV->getType(); 5312 ParamLoc = PV->getLocation(); 5313 IsCRegister = 5314 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5315 } 5316 } 5317 5318 if (!SecondArgIsLastNamedArgument) 5319 Diag(TheCall->getArg(1)->getBeginLoc(), 5320 diag::warn_second_arg_of_va_start_not_last_named_param); 5321 else if (IsCRegister || Type->isReferenceType() || 5322 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5323 // Promotable integers are UB, but enumerations need a bit of 5324 // extra checking to see what their promotable type actually is. 5325 if (!Type->isPromotableIntegerType()) 5326 return false; 5327 if (!Type->isEnumeralType()) 5328 return true; 5329 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5330 return !(ED && 5331 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5332 }()) { 5333 unsigned Reason = 0; 5334 if (Type->isReferenceType()) Reason = 1; 5335 else if (IsCRegister) Reason = 2; 5336 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5337 Diag(ParamLoc, diag::note_parameter_type) << Type; 5338 } 5339 5340 TheCall->setType(Context.VoidTy); 5341 return false; 5342 } 5343 5344 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5345 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5346 // const char *named_addr); 5347 5348 Expr *Func = Call->getCallee(); 5349 5350 if (Call->getNumArgs() < 3) 5351 return Diag(Call->getEndLoc(), 5352 diag::err_typecheck_call_too_few_args_at_least) 5353 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5354 5355 // Type-check the first argument normally. 5356 if (checkBuiltinArgument(*this, Call, 0)) 5357 return true; 5358 5359 // Check that the current function is variadic. 5360 if (checkVAStartIsInVariadicFunction(*this, Func)) 5361 return true; 5362 5363 // __va_start on Windows does not validate the parameter qualifiers 5364 5365 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5366 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5367 5368 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5369 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5370 5371 const QualType &ConstCharPtrTy = 5372 Context.getPointerType(Context.CharTy.withConst()); 5373 if (!Arg1Ty->isPointerType() || 5374 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5375 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5376 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5377 << 0 /* qualifier difference */ 5378 << 3 /* parameter mismatch */ 5379 << 2 << Arg1->getType() << ConstCharPtrTy; 5380 5381 const QualType SizeTy = Context.getSizeType(); 5382 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5383 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5384 << Arg2->getType() << SizeTy << 1 /* different class */ 5385 << 0 /* qualifier difference */ 5386 << 3 /* parameter mismatch */ 5387 << 3 << Arg2->getType() << SizeTy; 5388 5389 return false; 5390 } 5391 5392 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5393 /// friends. This is declared to take (...), so we have to check everything. 5394 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5395 if (TheCall->getNumArgs() < 2) 5396 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5397 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5398 if (TheCall->getNumArgs() > 2) 5399 return Diag(TheCall->getArg(2)->getBeginLoc(), 5400 diag::err_typecheck_call_too_many_args) 5401 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5402 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5403 (*(TheCall->arg_end() - 1))->getEndLoc()); 5404 5405 ExprResult OrigArg0 = TheCall->getArg(0); 5406 ExprResult OrigArg1 = TheCall->getArg(1); 5407 5408 // Do standard promotions between the two arguments, returning their common 5409 // type. 5410 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5411 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5412 return true; 5413 5414 // Make sure any conversions are pushed back into the call; this is 5415 // type safe since unordered compare builtins are declared as "_Bool 5416 // foo(...)". 5417 TheCall->setArg(0, OrigArg0.get()); 5418 TheCall->setArg(1, OrigArg1.get()); 5419 5420 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5421 return false; 5422 5423 // If the common type isn't a real floating type, then the arguments were 5424 // invalid for this operation. 5425 if (Res.isNull() || !Res->isRealFloatingType()) 5426 return Diag(OrigArg0.get()->getBeginLoc(), 5427 diag::err_typecheck_call_invalid_ordered_compare) 5428 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5429 << SourceRange(OrigArg0.get()->getBeginLoc(), 5430 OrigArg1.get()->getEndLoc()); 5431 5432 return false; 5433 } 5434 5435 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5436 /// __builtin_isnan and friends. This is declared to take (...), so we have 5437 /// to check everything. We expect the last argument to be a floating point 5438 /// value. 5439 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5440 if (TheCall->getNumArgs() < NumArgs) 5441 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5442 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5443 if (TheCall->getNumArgs() > NumArgs) 5444 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5445 diag::err_typecheck_call_too_many_args) 5446 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5447 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5448 (*(TheCall->arg_end() - 1))->getEndLoc()); 5449 5450 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5451 5452 if (OrigArg->isTypeDependent()) 5453 return false; 5454 5455 // This operation requires a non-_Complex floating-point number. 5456 if (!OrigArg->getType()->isRealFloatingType()) 5457 return Diag(OrigArg->getBeginLoc(), 5458 diag::err_typecheck_call_invalid_unary_fp) 5459 << OrigArg->getType() << OrigArg->getSourceRange(); 5460 5461 // If this is an implicit conversion from float -> float, double, or 5462 // long double, remove it. 5463 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5464 // Only remove standard FloatCasts, leaving other casts inplace 5465 if (Cast->getCastKind() == CK_FloatingCast) { 5466 Expr *CastArg = Cast->getSubExpr(); 5467 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5468 assert( 5469 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5470 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5471 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5472 "promotion from float to either float, double, or long double is " 5473 "the only expected cast here"); 5474 Cast->setSubExpr(nullptr); 5475 TheCall->setArg(NumArgs-1, CastArg); 5476 } 5477 } 5478 } 5479 5480 return false; 5481 } 5482 5483 // Customized Sema Checking for VSX builtins that have the following signature: 5484 // vector [...] builtinName(vector [...], vector [...], const int); 5485 // Which takes the same type of vectors (any legal vector type) for the first 5486 // two arguments and takes compile time constant for the third argument. 5487 // Example builtins are : 5488 // vector double vec_xxpermdi(vector double, vector double, int); 5489 // vector short vec_xxsldwi(vector short, vector short, int); 5490 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5491 unsigned ExpectedNumArgs = 3; 5492 if (TheCall->getNumArgs() < ExpectedNumArgs) 5493 return Diag(TheCall->getEndLoc(), 5494 diag::err_typecheck_call_too_few_args_at_least) 5495 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5496 << TheCall->getSourceRange(); 5497 5498 if (TheCall->getNumArgs() > ExpectedNumArgs) 5499 return Diag(TheCall->getEndLoc(), 5500 diag::err_typecheck_call_too_many_args_at_most) 5501 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5502 << TheCall->getSourceRange(); 5503 5504 // Check the third argument is a compile time constant 5505 llvm::APSInt Value; 5506 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5507 return Diag(TheCall->getBeginLoc(), 5508 diag::err_vsx_builtin_nonconstant_argument) 5509 << 3 /* argument index */ << TheCall->getDirectCallee() 5510 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5511 TheCall->getArg(2)->getEndLoc()); 5512 5513 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5514 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5515 5516 // Check the type of argument 1 and argument 2 are vectors. 5517 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5518 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5519 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5520 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5521 << TheCall->getDirectCallee() 5522 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5523 TheCall->getArg(1)->getEndLoc()); 5524 } 5525 5526 // Check the first two arguments are the same type. 5527 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5528 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5529 << TheCall->getDirectCallee() 5530 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5531 TheCall->getArg(1)->getEndLoc()); 5532 } 5533 5534 // When default clang type checking is turned off and the customized type 5535 // checking is used, the returning type of the function must be explicitly 5536 // set. Otherwise it is _Bool by default. 5537 TheCall->setType(Arg1Ty); 5538 5539 return false; 5540 } 5541 5542 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5543 // This is declared to take (...), so we have to check everything. 5544 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5545 if (TheCall->getNumArgs() < 2) 5546 return ExprError(Diag(TheCall->getEndLoc(), 5547 diag::err_typecheck_call_too_few_args_at_least) 5548 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5549 << TheCall->getSourceRange()); 5550 5551 // Determine which of the following types of shufflevector we're checking: 5552 // 1) unary, vector mask: (lhs, mask) 5553 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5554 QualType resType = TheCall->getArg(0)->getType(); 5555 unsigned numElements = 0; 5556 5557 if (!TheCall->getArg(0)->isTypeDependent() && 5558 !TheCall->getArg(1)->isTypeDependent()) { 5559 QualType LHSType = TheCall->getArg(0)->getType(); 5560 QualType RHSType = TheCall->getArg(1)->getType(); 5561 5562 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5563 return ExprError( 5564 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5565 << TheCall->getDirectCallee() 5566 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5567 TheCall->getArg(1)->getEndLoc())); 5568 5569 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5570 unsigned numResElements = TheCall->getNumArgs() - 2; 5571 5572 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5573 // with mask. If so, verify that RHS is an integer vector type with the 5574 // same number of elts as lhs. 5575 if (TheCall->getNumArgs() == 2) { 5576 if (!RHSType->hasIntegerRepresentation() || 5577 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5578 return ExprError(Diag(TheCall->getBeginLoc(), 5579 diag::err_vec_builtin_incompatible_vector) 5580 << TheCall->getDirectCallee() 5581 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5582 TheCall->getArg(1)->getEndLoc())); 5583 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5584 return ExprError(Diag(TheCall->getBeginLoc(), 5585 diag::err_vec_builtin_incompatible_vector) 5586 << TheCall->getDirectCallee() 5587 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5588 TheCall->getArg(1)->getEndLoc())); 5589 } else if (numElements != numResElements) { 5590 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5591 resType = Context.getVectorType(eltType, numResElements, 5592 VectorType::GenericVector); 5593 } 5594 } 5595 5596 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5597 if (TheCall->getArg(i)->isTypeDependent() || 5598 TheCall->getArg(i)->isValueDependent()) 5599 continue; 5600 5601 llvm::APSInt Result(32); 5602 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5603 return ExprError(Diag(TheCall->getBeginLoc(), 5604 diag::err_shufflevector_nonconstant_argument) 5605 << TheCall->getArg(i)->getSourceRange()); 5606 5607 // Allow -1 which will be translated to undef in the IR. 5608 if (Result.isSigned() && Result.isAllOnesValue()) 5609 continue; 5610 5611 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5612 return ExprError(Diag(TheCall->getBeginLoc(), 5613 diag::err_shufflevector_argument_too_large) 5614 << TheCall->getArg(i)->getSourceRange()); 5615 } 5616 5617 SmallVector<Expr*, 32> exprs; 5618 5619 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5620 exprs.push_back(TheCall->getArg(i)); 5621 TheCall->setArg(i, nullptr); 5622 } 5623 5624 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5625 TheCall->getCallee()->getBeginLoc(), 5626 TheCall->getRParenLoc()); 5627 } 5628 5629 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5630 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5631 SourceLocation BuiltinLoc, 5632 SourceLocation RParenLoc) { 5633 ExprValueKind VK = VK_RValue; 5634 ExprObjectKind OK = OK_Ordinary; 5635 QualType DstTy = TInfo->getType(); 5636 QualType SrcTy = E->getType(); 5637 5638 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5639 return ExprError(Diag(BuiltinLoc, 5640 diag::err_convertvector_non_vector) 5641 << E->getSourceRange()); 5642 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5643 return ExprError(Diag(BuiltinLoc, 5644 diag::err_convertvector_non_vector_type)); 5645 5646 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5647 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5648 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5649 if (SrcElts != DstElts) 5650 return ExprError(Diag(BuiltinLoc, 5651 diag::err_convertvector_incompatible_vector) 5652 << E->getSourceRange()); 5653 } 5654 5655 return new (Context) 5656 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5657 } 5658 5659 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5660 // This is declared to take (const void*, ...) and can take two 5661 // optional constant int args. 5662 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5663 unsigned NumArgs = TheCall->getNumArgs(); 5664 5665 if (NumArgs > 3) 5666 return Diag(TheCall->getEndLoc(), 5667 diag::err_typecheck_call_too_many_args_at_most) 5668 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5669 5670 // Argument 0 is checked for us and the remaining arguments must be 5671 // constant integers. 5672 for (unsigned i = 1; i != NumArgs; ++i) 5673 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5674 return true; 5675 5676 return false; 5677 } 5678 5679 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5680 // __assume does not evaluate its arguments, and should warn if its argument 5681 // has side effects. 5682 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5683 Expr *Arg = TheCall->getArg(0); 5684 if (Arg->isInstantiationDependent()) return false; 5685 5686 if (Arg->HasSideEffects(Context)) 5687 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5688 << Arg->getSourceRange() 5689 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5690 5691 return false; 5692 } 5693 5694 /// Handle __builtin_alloca_with_align. This is declared 5695 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5696 /// than 8. 5697 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5698 // The alignment must be a constant integer. 5699 Expr *Arg = TheCall->getArg(1); 5700 5701 // We can't check the value of a dependent argument. 5702 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5703 if (const auto *UE = 5704 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5705 if (UE->getKind() == UETT_AlignOf) 5706 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5707 << Arg->getSourceRange(); 5708 5709 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5710 5711 if (!Result.isPowerOf2()) 5712 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5713 << Arg->getSourceRange(); 5714 5715 if (Result < Context.getCharWidth()) 5716 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5717 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5718 5719 if (Result > std::numeric_limits<int32_t>::max()) 5720 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5721 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5722 } 5723 5724 return false; 5725 } 5726 5727 /// Handle __builtin_assume_aligned. This is declared 5728 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5729 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5730 unsigned NumArgs = TheCall->getNumArgs(); 5731 5732 if (NumArgs > 3) 5733 return Diag(TheCall->getEndLoc(), 5734 diag::err_typecheck_call_too_many_args_at_most) 5735 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5736 5737 // The alignment must be a constant integer. 5738 Expr *Arg = TheCall->getArg(1); 5739 5740 // We can't check the value of a dependent argument. 5741 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5742 llvm::APSInt Result; 5743 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5744 return true; 5745 5746 if (!Result.isPowerOf2()) 5747 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5748 << Arg->getSourceRange(); 5749 } 5750 5751 if (NumArgs > 2) { 5752 ExprResult Arg(TheCall->getArg(2)); 5753 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5754 Context.getSizeType(), false); 5755 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5756 if (Arg.isInvalid()) return true; 5757 TheCall->setArg(2, Arg.get()); 5758 } 5759 5760 return false; 5761 } 5762 5763 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5764 unsigned BuiltinID = 5765 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5766 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5767 5768 unsigned NumArgs = TheCall->getNumArgs(); 5769 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5770 if (NumArgs < NumRequiredArgs) { 5771 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5772 << 0 /* function call */ << NumRequiredArgs << NumArgs 5773 << TheCall->getSourceRange(); 5774 } 5775 if (NumArgs >= NumRequiredArgs + 0x100) { 5776 return Diag(TheCall->getEndLoc(), 5777 diag::err_typecheck_call_too_many_args_at_most) 5778 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5779 << TheCall->getSourceRange(); 5780 } 5781 unsigned i = 0; 5782 5783 // For formatting call, check buffer arg. 5784 if (!IsSizeCall) { 5785 ExprResult Arg(TheCall->getArg(i)); 5786 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5787 Context, Context.VoidPtrTy, false); 5788 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5789 if (Arg.isInvalid()) 5790 return true; 5791 TheCall->setArg(i, Arg.get()); 5792 i++; 5793 } 5794 5795 // Check string literal arg. 5796 unsigned FormatIdx = i; 5797 { 5798 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5799 if (Arg.isInvalid()) 5800 return true; 5801 TheCall->setArg(i, Arg.get()); 5802 i++; 5803 } 5804 5805 // Make sure variadic args are scalar. 5806 unsigned FirstDataArg = i; 5807 while (i < NumArgs) { 5808 ExprResult Arg = DefaultVariadicArgumentPromotion( 5809 TheCall->getArg(i), VariadicFunction, nullptr); 5810 if (Arg.isInvalid()) 5811 return true; 5812 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5813 if (ArgSize.getQuantity() >= 0x100) { 5814 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5815 << i << (int)ArgSize.getQuantity() << 0xff 5816 << TheCall->getSourceRange(); 5817 } 5818 TheCall->setArg(i, Arg.get()); 5819 i++; 5820 } 5821 5822 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5823 // call to avoid duplicate diagnostics. 5824 if (!IsSizeCall) { 5825 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5826 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5827 bool Success = CheckFormatArguments( 5828 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5829 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5830 CheckedVarArgs); 5831 if (!Success) 5832 return true; 5833 } 5834 5835 if (IsSizeCall) { 5836 TheCall->setType(Context.getSizeType()); 5837 } else { 5838 TheCall->setType(Context.VoidPtrTy); 5839 } 5840 return false; 5841 } 5842 5843 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5844 /// TheCall is a constant expression. 5845 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5846 llvm::APSInt &Result) { 5847 Expr *Arg = TheCall->getArg(ArgNum); 5848 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5849 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5850 5851 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5852 5853 if (!Arg->isIntegerConstantExpr(Result, Context)) 5854 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5855 << FDecl->getDeclName() << Arg->getSourceRange(); 5856 5857 return false; 5858 } 5859 5860 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5861 /// TheCall is a constant expression in the range [Low, High]. 5862 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5863 int Low, int High, bool RangeIsError) { 5864 llvm::APSInt Result; 5865 5866 // We can't check the value of a dependent argument. 5867 Expr *Arg = TheCall->getArg(ArgNum); 5868 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5869 return false; 5870 5871 // Check constant-ness first. 5872 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5873 return true; 5874 5875 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5876 if (RangeIsError) 5877 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5878 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5879 else 5880 // Defer the warning until we know if the code will be emitted so that 5881 // dead code can ignore this. 5882 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5883 PDiag(diag::warn_argument_invalid_range) 5884 << Result.toString(10) << Low << High 5885 << Arg->getSourceRange()); 5886 } 5887 5888 return false; 5889 } 5890 5891 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5892 /// TheCall is a constant expression is a multiple of Num.. 5893 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5894 unsigned Num) { 5895 llvm::APSInt Result; 5896 5897 // We can't check the value of a dependent argument. 5898 Expr *Arg = TheCall->getArg(ArgNum); 5899 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5900 return false; 5901 5902 // Check constant-ness first. 5903 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5904 return true; 5905 5906 if (Result.getSExtValue() % Num != 0) 5907 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5908 << Num << Arg->getSourceRange(); 5909 5910 return false; 5911 } 5912 5913 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5914 /// TheCall is an ARM/AArch64 special register string literal. 5915 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5916 int ArgNum, unsigned ExpectedFieldNum, 5917 bool AllowName) { 5918 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5919 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5920 BuiltinID == ARM::BI__builtin_arm_rsr || 5921 BuiltinID == ARM::BI__builtin_arm_rsrp || 5922 BuiltinID == ARM::BI__builtin_arm_wsr || 5923 BuiltinID == ARM::BI__builtin_arm_wsrp; 5924 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5925 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5926 BuiltinID == AArch64::BI__builtin_arm_rsr || 5927 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5928 BuiltinID == AArch64::BI__builtin_arm_wsr || 5929 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5930 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5931 5932 // We can't check the value of a dependent argument. 5933 Expr *Arg = TheCall->getArg(ArgNum); 5934 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5935 return false; 5936 5937 // Check if the argument is a string literal. 5938 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5939 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 5940 << Arg->getSourceRange(); 5941 5942 // Check the type of special register given. 5943 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 5944 SmallVector<StringRef, 6> Fields; 5945 Reg.split(Fields, ":"); 5946 5947 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 5948 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5949 << Arg->getSourceRange(); 5950 5951 // If the string is the name of a register then we cannot check that it is 5952 // valid here but if the string is of one the forms described in ACLE then we 5953 // can check that the supplied fields are integers and within the valid 5954 // ranges. 5955 if (Fields.size() > 1) { 5956 bool FiveFields = Fields.size() == 5; 5957 5958 bool ValidString = true; 5959 if (IsARMBuiltin) { 5960 ValidString &= Fields[0].startswith_lower("cp") || 5961 Fields[0].startswith_lower("p"); 5962 if (ValidString) 5963 Fields[0] = 5964 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 5965 5966 ValidString &= Fields[2].startswith_lower("c"); 5967 if (ValidString) 5968 Fields[2] = Fields[2].drop_front(1); 5969 5970 if (FiveFields) { 5971 ValidString &= Fields[3].startswith_lower("c"); 5972 if (ValidString) 5973 Fields[3] = Fields[3].drop_front(1); 5974 } 5975 } 5976 5977 SmallVector<int, 5> Ranges; 5978 if (FiveFields) 5979 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 5980 else 5981 Ranges.append({15, 7, 15}); 5982 5983 for (unsigned i=0; i<Fields.size(); ++i) { 5984 int IntField; 5985 ValidString &= !Fields[i].getAsInteger(10, IntField); 5986 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 5987 } 5988 5989 if (!ValidString) 5990 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5991 << Arg->getSourceRange(); 5992 } else if (IsAArch64Builtin && Fields.size() == 1) { 5993 // If the register name is one of those that appear in the condition below 5994 // and the special register builtin being used is one of the write builtins, 5995 // then we require that the argument provided for writing to the register 5996 // is an integer constant expression. This is because it will be lowered to 5997 // an MSR (immediate) instruction, so we need to know the immediate at 5998 // compile time. 5999 if (TheCall->getNumArgs() != 2) 6000 return false; 6001 6002 std::string RegLower = Reg.lower(); 6003 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6004 RegLower != "pan" && RegLower != "uao") 6005 return false; 6006 6007 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6008 } 6009 6010 return false; 6011 } 6012 6013 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6014 /// This checks that the target supports __builtin_longjmp and 6015 /// that val is a constant 1. 6016 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6017 if (!Context.getTargetInfo().hasSjLjLowering()) 6018 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6019 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6020 6021 Expr *Arg = TheCall->getArg(1); 6022 llvm::APSInt Result; 6023 6024 // TODO: This is less than ideal. Overload this to take a value. 6025 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6026 return true; 6027 6028 if (Result != 1) 6029 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6030 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6031 6032 return false; 6033 } 6034 6035 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6036 /// This checks that the target supports __builtin_setjmp. 6037 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6038 if (!Context.getTargetInfo().hasSjLjLowering()) 6039 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6040 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6041 return false; 6042 } 6043 6044 namespace { 6045 6046 class UncoveredArgHandler { 6047 enum { Unknown = -1, AllCovered = -2 }; 6048 6049 signed FirstUncoveredArg = Unknown; 6050 SmallVector<const Expr *, 4> DiagnosticExprs; 6051 6052 public: 6053 UncoveredArgHandler() = default; 6054 6055 bool hasUncoveredArg() const { 6056 return (FirstUncoveredArg >= 0); 6057 } 6058 6059 unsigned getUncoveredArg() const { 6060 assert(hasUncoveredArg() && "no uncovered argument"); 6061 return FirstUncoveredArg; 6062 } 6063 6064 void setAllCovered() { 6065 // A string has been found with all arguments covered, so clear out 6066 // the diagnostics. 6067 DiagnosticExprs.clear(); 6068 FirstUncoveredArg = AllCovered; 6069 } 6070 6071 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6072 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6073 6074 // Don't update if a previous string covers all arguments. 6075 if (FirstUncoveredArg == AllCovered) 6076 return; 6077 6078 // UncoveredArgHandler tracks the highest uncovered argument index 6079 // and with it all the strings that match this index. 6080 if (NewFirstUncoveredArg == FirstUncoveredArg) 6081 DiagnosticExprs.push_back(StrExpr); 6082 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6083 DiagnosticExprs.clear(); 6084 DiagnosticExprs.push_back(StrExpr); 6085 FirstUncoveredArg = NewFirstUncoveredArg; 6086 } 6087 } 6088 6089 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6090 }; 6091 6092 enum StringLiteralCheckType { 6093 SLCT_NotALiteral, 6094 SLCT_UncheckedLiteral, 6095 SLCT_CheckedLiteral 6096 }; 6097 6098 } // namespace 6099 6100 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6101 BinaryOperatorKind BinOpKind, 6102 bool AddendIsRight) { 6103 unsigned BitWidth = Offset.getBitWidth(); 6104 unsigned AddendBitWidth = Addend.getBitWidth(); 6105 // There might be negative interim results. 6106 if (Addend.isUnsigned()) { 6107 Addend = Addend.zext(++AddendBitWidth); 6108 Addend.setIsSigned(true); 6109 } 6110 // Adjust the bit width of the APSInts. 6111 if (AddendBitWidth > BitWidth) { 6112 Offset = Offset.sext(AddendBitWidth); 6113 BitWidth = AddendBitWidth; 6114 } else if (BitWidth > AddendBitWidth) { 6115 Addend = Addend.sext(BitWidth); 6116 } 6117 6118 bool Ov = false; 6119 llvm::APSInt ResOffset = Offset; 6120 if (BinOpKind == BO_Add) 6121 ResOffset = Offset.sadd_ov(Addend, Ov); 6122 else { 6123 assert(AddendIsRight && BinOpKind == BO_Sub && 6124 "operator must be add or sub with addend on the right"); 6125 ResOffset = Offset.ssub_ov(Addend, Ov); 6126 } 6127 6128 // We add an offset to a pointer here so we should support an offset as big as 6129 // possible. 6130 if (Ov) { 6131 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6132 "index (intermediate) result too big"); 6133 Offset = Offset.sext(2 * BitWidth); 6134 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6135 return; 6136 } 6137 6138 Offset = ResOffset; 6139 } 6140 6141 namespace { 6142 6143 // This is a wrapper class around StringLiteral to support offsetted string 6144 // literals as format strings. It takes the offset into account when returning 6145 // the string and its length or the source locations to display notes correctly. 6146 class FormatStringLiteral { 6147 const StringLiteral *FExpr; 6148 int64_t Offset; 6149 6150 public: 6151 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6152 : FExpr(fexpr), Offset(Offset) {} 6153 6154 StringRef getString() const { 6155 return FExpr->getString().drop_front(Offset); 6156 } 6157 6158 unsigned getByteLength() const { 6159 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6160 } 6161 6162 unsigned getLength() const { return FExpr->getLength() - Offset; } 6163 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6164 6165 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6166 6167 QualType getType() const { return FExpr->getType(); } 6168 6169 bool isAscii() const { return FExpr->isAscii(); } 6170 bool isWide() const { return FExpr->isWide(); } 6171 bool isUTF8() const { return FExpr->isUTF8(); } 6172 bool isUTF16() const { return FExpr->isUTF16(); } 6173 bool isUTF32() const { return FExpr->isUTF32(); } 6174 bool isPascal() const { return FExpr->isPascal(); } 6175 6176 SourceLocation getLocationOfByte( 6177 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6178 const TargetInfo &Target, unsigned *StartToken = nullptr, 6179 unsigned *StartTokenByteOffset = nullptr) const { 6180 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6181 StartToken, StartTokenByteOffset); 6182 } 6183 6184 SourceLocation getBeginLoc() const LLVM_READONLY { 6185 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6186 } 6187 6188 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6189 }; 6190 6191 } // namespace 6192 6193 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6194 const Expr *OrigFormatExpr, 6195 ArrayRef<const Expr *> Args, 6196 bool HasVAListArg, unsigned format_idx, 6197 unsigned firstDataArg, 6198 Sema::FormatStringType Type, 6199 bool inFunctionCall, 6200 Sema::VariadicCallType CallType, 6201 llvm::SmallBitVector &CheckedVarArgs, 6202 UncoveredArgHandler &UncoveredArg); 6203 6204 // Determine if an expression is a string literal or constant string. 6205 // If this function returns false on the arguments to a function expecting a 6206 // format string, we will usually need to emit a warning. 6207 // True string literals are then checked by CheckFormatString. 6208 static StringLiteralCheckType 6209 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6210 bool HasVAListArg, unsigned format_idx, 6211 unsigned firstDataArg, Sema::FormatStringType Type, 6212 Sema::VariadicCallType CallType, bool InFunctionCall, 6213 llvm::SmallBitVector &CheckedVarArgs, 6214 UncoveredArgHandler &UncoveredArg, 6215 llvm::APSInt Offset) { 6216 tryAgain: 6217 assert(Offset.isSigned() && "invalid offset"); 6218 6219 if (E->isTypeDependent() || E->isValueDependent()) 6220 return SLCT_NotALiteral; 6221 6222 E = E->IgnoreParenCasts(); 6223 6224 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6225 // Technically -Wformat-nonliteral does not warn about this case. 6226 // The behavior of printf and friends in this case is implementation 6227 // dependent. Ideally if the format string cannot be null then 6228 // it should have a 'nonnull' attribute in the function prototype. 6229 return SLCT_UncheckedLiteral; 6230 6231 switch (E->getStmtClass()) { 6232 case Stmt::BinaryConditionalOperatorClass: 6233 case Stmt::ConditionalOperatorClass: { 6234 // The expression is a literal if both sub-expressions were, and it was 6235 // completely checked only if both sub-expressions were checked. 6236 const AbstractConditionalOperator *C = 6237 cast<AbstractConditionalOperator>(E); 6238 6239 // Determine whether it is necessary to check both sub-expressions, for 6240 // example, because the condition expression is a constant that can be 6241 // evaluated at compile time. 6242 bool CheckLeft = true, CheckRight = true; 6243 6244 bool Cond; 6245 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6246 if (Cond) 6247 CheckRight = false; 6248 else 6249 CheckLeft = false; 6250 } 6251 6252 // We need to maintain the offsets for the right and the left hand side 6253 // separately to check if every possible indexed expression is a valid 6254 // string literal. They might have different offsets for different string 6255 // literals in the end. 6256 StringLiteralCheckType Left; 6257 if (!CheckLeft) 6258 Left = SLCT_UncheckedLiteral; 6259 else { 6260 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6261 HasVAListArg, format_idx, firstDataArg, 6262 Type, CallType, InFunctionCall, 6263 CheckedVarArgs, UncoveredArg, Offset); 6264 if (Left == SLCT_NotALiteral || !CheckRight) { 6265 return Left; 6266 } 6267 } 6268 6269 StringLiteralCheckType Right = 6270 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6271 HasVAListArg, format_idx, firstDataArg, 6272 Type, CallType, InFunctionCall, CheckedVarArgs, 6273 UncoveredArg, Offset); 6274 6275 return (CheckLeft && Left < Right) ? Left : Right; 6276 } 6277 6278 case Stmt::ImplicitCastExprClass: 6279 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6280 goto tryAgain; 6281 6282 case Stmt::OpaqueValueExprClass: 6283 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6284 E = src; 6285 goto tryAgain; 6286 } 6287 return SLCT_NotALiteral; 6288 6289 case Stmt::PredefinedExprClass: 6290 // While __func__, etc., are technically not string literals, they 6291 // cannot contain format specifiers and thus are not a security 6292 // liability. 6293 return SLCT_UncheckedLiteral; 6294 6295 case Stmt::DeclRefExprClass: { 6296 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6297 6298 // As an exception, do not flag errors for variables binding to 6299 // const string literals. 6300 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6301 bool isConstant = false; 6302 QualType T = DR->getType(); 6303 6304 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6305 isConstant = AT->getElementType().isConstant(S.Context); 6306 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6307 isConstant = T.isConstant(S.Context) && 6308 PT->getPointeeType().isConstant(S.Context); 6309 } else if (T->isObjCObjectPointerType()) { 6310 // In ObjC, there is usually no "const ObjectPointer" type, 6311 // so don't check if the pointee type is constant. 6312 isConstant = T.isConstant(S.Context); 6313 } 6314 6315 if (isConstant) { 6316 if (const Expr *Init = VD->getAnyInitializer()) { 6317 // Look through initializers like const char c[] = { "foo" } 6318 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6319 if (InitList->isStringLiteralInit()) 6320 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6321 } 6322 return checkFormatStringExpr(S, Init, Args, 6323 HasVAListArg, format_idx, 6324 firstDataArg, Type, CallType, 6325 /*InFunctionCall*/ false, CheckedVarArgs, 6326 UncoveredArg, Offset); 6327 } 6328 } 6329 6330 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6331 // special check to see if the format string is a function parameter 6332 // of the function calling the printf function. If the function 6333 // has an attribute indicating it is a printf-like function, then we 6334 // should suppress warnings concerning non-literals being used in a call 6335 // to a vprintf function. For example: 6336 // 6337 // void 6338 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6339 // va_list ap; 6340 // va_start(ap, fmt); 6341 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6342 // ... 6343 // } 6344 if (HasVAListArg) { 6345 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6346 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6347 int PVIndex = PV->getFunctionScopeIndex() + 1; 6348 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6349 // adjust for implicit parameter 6350 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6351 if (MD->isInstance()) 6352 ++PVIndex; 6353 // We also check if the formats are compatible. 6354 // We can't pass a 'scanf' string to a 'printf' function. 6355 if (PVIndex == PVFormat->getFormatIdx() && 6356 Type == S.GetFormatStringType(PVFormat)) 6357 return SLCT_UncheckedLiteral; 6358 } 6359 } 6360 } 6361 } 6362 } 6363 6364 return SLCT_NotALiteral; 6365 } 6366 6367 case Stmt::CallExprClass: 6368 case Stmt::CXXMemberCallExprClass: { 6369 const CallExpr *CE = cast<CallExpr>(E); 6370 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6371 bool IsFirst = true; 6372 StringLiteralCheckType CommonResult; 6373 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6374 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6375 StringLiteralCheckType Result = checkFormatStringExpr( 6376 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6377 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6378 if (IsFirst) { 6379 CommonResult = Result; 6380 IsFirst = false; 6381 } 6382 } 6383 if (!IsFirst) 6384 return CommonResult; 6385 6386 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6387 unsigned BuiltinID = FD->getBuiltinID(); 6388 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6389 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6390 const Expr *Arg = CE->getArg(0); 6391 return checkFormatStringExpr(S, Arg, Args, 6392 HasVAListArg, format_idx, 6393 firstDataArg, Type, CallType, 6394 InFunctionCall, CheckedVarArgs, 6395 UncoveredArg, Offset); 6396 } 6397 } 6398 } 6399 6400 return SLCT_NotALiteral; 6401 } 6402 case Stmt::ObjCMessageExprClass: { 6403 const auto *ME = cast<ObjCMessageExpr>(E); 6404 if (const auto *ND = ME->getMethodDecl()) { 6405 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6406 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6407 return checkFormatStringExpr( 6408 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6409 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6410 } 6411 } 6412 6413 return SLCT_NotALiteral; 6414 } 6415 case Stmt::ObjCStringLiteralClass: 6416 case Stmt::StringLiteralClass: { 6417 const StringLiteral *StrE = nullptr; 6418 6419 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6420 StrE = ObjCFExpr->getString(); 6421 else 6422 StrE = cast<StringLiteral>(E); 6423 6424 if (StrE) { 6425 if (Offset.isNegative() || Offset > StrE->getLength()) { 6426 // TODO: It would be better to have an explicit warning for out of 6427 // bounds literals. 6428 return SLCT_NotALiteral; 6429 } 6430 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6431 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6432 firstDataArg, Type, InFunctionCall, CallType, 6433 CheckedVarArgs, UncoveredArg); 6434 return SLCT_CheckedLiteral; 6435 } 6436 6437 return SLCT_NotALiteral; 6438 } 6439 case Stmt::BinaryOperatorClass: { 6440 llvm::APSInt LResult; 6441 llvm::APSInt RResult; 6442 6443 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6444 6445 // A string literal + an int offset is still a string literal. 6446 if (BinOp->isAdditiveOp()) { 6447 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6448 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6449 6450 if (LIsInt != RIsInt) { 6451 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6452 6453 if (LIsInt) { 6454 if (BinOpKind == BO_Add) { 6455 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 6456 E = BinOp->getRHS(); 6457 goto tryAgain; 6458 } 6459 } else { 6460 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 6461 E = BinOp->getLHS(); 6462 goto tryAgain; 6463 } 6464 } 6465 } 6466 6467 return SLCT_NotALiteral; 6468 } 6469 case Stmt::UnaryOperatorClass: { 6470 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6471 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6472 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6473 llvm::APSInt IndexResult; 6474 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6475 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 6476 E = ASE->getBase(); 6477 goto tryAgain; 6478 } 6479 } 6480 6481 return SLCT_NotALiteral; 6482 } 6483 6484 default: 6485 return SLCT_NotALiteral; 6486 } 6487 } 6488 6489 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6490 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6491 .Case("scanf", FST_Scanf) 6492 .Cases("printf", "printf0", FST_Printf) 6493 .Cases("NSString", "CFString", FST_NSString) 6494 .Case("strftime", FST_Strftime) 6495 .Case("strfmon", FST_Strfmon) 6496 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6497 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6498 .Case("os_trace", FST_OSLog) 6499 .Case("os_log", FST_OSLog) 6500 .Default(FST_Unknown); 6501 } 6502 6503 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6504 /// functions) for correct use of format strings. 6505 /// Returns true if a format string has been fully checked. 6506 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6507 ArrayRef<const Expr *> Args, 6508 bool IsCXXMember, 6509 VariadicCallType CallType, 6510 SourceLocation Loc, SourceRange Range, 6511 llvm::SmallBitVector &CheckedVarArgs) { 6512 FormatStringInfo FSI; 6513 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6514 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6515 FSI.FirstDataArg, GetFormatStringType(Format), 6516 CallType, Loc, Range, CheckedVarArgs); 6517 return false; 6518 } 6519 6520 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6521 bool HasVAListArg, unsigned format_idx, 6522 unsigned firstDataArg, FormatStringType Type, 6523 VariadicCallType CallType, 6524 SourceLocation Loc, SourceRange Range, 6525 llvm::SmallBitVector &CheckedVarArgs) { 6526 // CHECK: printf/scanf-like function is called with no format string. 6527 if (format_idx >= Args.size()) { 6528 Diag(Loc, diag::warn_missing_format_string) << Range; 6529 return false; 6530 } 6531 6532 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6533 6534 // CHECK: format string is not a string literal. 6535 // 6536 // Dynamically generated format strings are difficult to 6537 // automatically vet at compile time. Requiring that format strings 6538 // are string literals: (1) permits the checking of format strings by 6539 // the compiler and thereby (2) can practically remove the source of 6540 // many format string exploits. 6541 6542 // Format string can be either ObjC string (e.g. @"%d") or 6543 // C string (e.g. "%d") 6544 // ObjC string uses the same format specifiers as C string, so we can use 6545 // the same format string checking logic for both ObjC and C strings. 6546 UncoveredArgHandler UncoveredArg; 6547 StringLiteralCheckType CT = 6548 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6549 format_idx, firstDataArg, Type, CallType, 6550 /*IsFunctionCall*/ true, CheckedVarArgs, 6551 UncoveredArg, 6552 /*no string offset*/ llvm::APSInt(64, false) = 0); 6553 6554 // Generate a diagnostic where an uncovered argument is detected. 6555 if (UncoveredArg.hasUncoveredArg()) { 6556 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6557 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6558 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6559 } 6560 6561 if (CT != SLCT_NotALiteral) 6562 // Literal format string found, check done! 6563 return CT == SLCT_CheckedLiteral; 6564 6565 // Strftime is particular as it always uses a single 'time' argument, 6566 // so it is safe to pass a non-literal string. 6567 if (Type == FST_Strftime) 6568 return false; 6569 6570 // Do not emit diag when the string param is a macro expansion and the 6571 // format is either NSString or CFString. This is a hack to prevent 6572 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6573 // which are usually used in place of NS and CF string literals. 6574 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6575 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6576 return false; 6577 6578 // If there are no arguments specified, warn with -Wformat-security, otherwise 6579 // warn only with -Wformat-nonliteral. 6580 if (Args.size() == firstDataArg) { 6581 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6582 << OrigFormatExpr->getSourceRange(); 6583 switch (Type) { 6584 default: 6585 break; 6586 case FST_Kprintf: 6587 case FST_FreeBSDKPrintf: 6588 case FST_Printf: 6589 Diag(FormatLoc, diag::note_format_security_fixit) 6590 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6591 break; 6592 case FST_NSString: 6593 Diag(FormatLoc, diag::note_format_security_fixit) 6594 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6595 break; 6596 } 6597 } else { 6598 Diag(FormatLoc, diag::warn_format_nonliteral) 6599 << OrigFormatExpr->getSourceRange(); 6600 } 6601 return false; 6602 } 6603 6604 namespace { 6605 6606 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6607 protected: 6608 Sema &S; 6609 const FormatStringLiteral *FExpr; 6610 const Expr *OrigFormatExpr; 6611 const Sema::FormatStringType FSType; 6612 const unsigned FirstDataArg; 6613 const unsigned NumDataArgs; 6614 const char *Beg; // Start of format string. 6615 const bool HasVAListArg; 6616 ArrayRef<const Expr *> Args; 6617 unsigned FormatIdx; 6618 llvm::SmallBitVector CoveredArgs; 6619 bool usesPositionalArgs = false; 6620 bool atFirstArg = true; 6621 bool inFunctionCall; 6622 Sema::VariadicCallType CallType; 6623 llvm::SmallBitVector &CheckedVarArgs; 6624 UncoveredArgHandler &UncoveredArg; 6625 6626 public: 6627 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6628 const Expr *origFormatExpr, 6629 const Sema::FormatStringType type, unsigned firstDataArg, 6630 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6631 ArrayRef<const Expr *> Args, unsigned formatIdx, 6632 bool inFunctionCall, Sema::VariadicCallType callType, 6633 llvm::SmallBitVector &CheckedVarArgs, 6634 UncoveredArgHandler &UncoveredArg) 6635 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6636 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6637 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6638 inFunctionCall(inFunctionCall), CallType(callType), 6639 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6640 CoveredArgs.resize(numDataArgs); 6641 CoveredArgs.reset(); 6642 } 6643 6644 void DoneProcessing(); 6645 6646 void HandleIncompleteSpecifier(const char *startSpecifier, 6647 unsigned specifierLen) override; 6648 6649 void HandleInvalidLengthModifier( 6650 const analyze_format_string::FormatSpecifier &FS, 6651 const analyze_format_string::ConversionSpecifier &CS, 6652 const char *startSpecifier, unsigned specifierLen, 6653 unsigned DiagID); 6654 6655 void HandleNonStandardLengthModifier( 6656 const analyze_format_string::FormatSpecifier &FS, 6657 const char *startSpecifier, unsigned specifierLen); 6658 6659 void HandleNonStandardConversionSpecifier( 6660 const analyze_format_string::ConversionSpecifier &CS, 6661 const char *startSpecifier, unsigned specifierLen); 6662 6663 void HandlePosition(const char *startPos, unsigned posLen) override; 6664 6665 void HandleInvalidPosition(const char *startSpecifier, 6666 unsigned specifierLen, 6667 analyze_format_string::PositionContext p) override; 6668 6669 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6670 6671 void HandleNullChar(const char *nullCharacter) override; 6672 6673 template <typename Range> 6674 static void 6675 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6676 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6677 bool IsStringLocation, Range StringRange, 6678 ArrayRef<FixItHint> Fixit = None); 6679 6680 protected: 6681 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6682 const char *startSpec, 6683 unsigned specifierLen, 6684 const char *csStart, unsigned csLen); 6685 6686 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6687 const char *startSpec, 6688 unsigned specifierLen); 6689 6690 SourceRange getFormatStringRange(); 6691 CharSourceRange getSpecifierRange(const char *startSpecifier, 6692 unsigned specifierLen); 6693 SourceLocation getLocationOfByte(const char *x); 6694 6695 const Expr *getDataArg(unsigned i) const; 6696 6697 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6698 const analyze_format_string::ConversionSpecifier &CS, 6699 const char *startSpecifier, unsigned specifierLen, 6700 unsigned argIndex); 6701 6702 template <typename Range> 6703 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6704 bool IsStringLocation, Range StringRange, 6705 ArrayRef<FixItHint> Fixit = None); 6706 }; 6707 6708 } // namespace 6709 6710 SourceRange CheckFormatHandler::getFormatStringRange() { 6711 return OrigFormatExpr->getSourceRange(); 6712 } 6713 6714 CharSourceRange CheckFormatHandler:: 6715 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6716 SourceLocation Start = getLocationOfByte(startSpecifier); 6717 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6718 6719 // Advance the end SourceLocation by one due to half-open ranges. 6720 End = End.getLocWithOffset(1); 6721 6722 return CharSourceRange::getCharRange(Start, End); 6723 } 6724 6725 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6726 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6727 S.getLangOpts(), S.Context.getTargetInfo()); 6728 } 6729 6730 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6731 unsigned specifierLen){ 6732 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6733 getLocationOfByte(startSpecifier), 6734 /*IsStringLocation*/true, 6735 getSpecifierRange(startSpecifier, specifierLen)); 6736 } 6737 6738 void CheckFormatHandler::HandleInvalidLengthModifier( 6739 const analyze_format_string::FormatSpecifier &FS, 6740 const analyze_format_string::ConversionSpecifier &CS, 6741 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6742 using namespace analyze_format_string; 6743 6744 const LengthModifier &LM = FS.getLengthModifier(); 6745 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6746 6747 // See if we know how to fix this length modifier. 6748 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6749 if (FixedLM) { 6750 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6751 getLocationOfByte(LM.getStart()), 6752 /*IsStringLocation*/true, 6753 getSpecifierRange(startSpecifier, specifierLen)); 6754 6755 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6756 << FixedLM->toString() 6757 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6758 6759 } else { 6760 FixItHint Hint; 6761 if (DiagID == diag::warn_format_nonsensical_length) 6762 Hint = FixItHint::CreateRemoval(LMRange); 6763 6764 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6765 getLocationOfByte(LM.getStart()), 6766 /*IsStringLocation*/true, 6767 getSpecifierRange(startSpecifier, specifierLen), 6768 Hint); 6769 } 6770 } 6771 6772 void CheckFormatHandler::HandleNonStandardLengthModifier( 6773 const analyze_format_string::FormatSpecifier &FS, 6774 const char *startSpecifier, unsigned specifierLen) { 6775 using namespace analyze_format_string; 6776 6777 const LengthModifier &LM = FS.getLengthModifier(); 6778 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6779 6780 // See if we know how to fix this length modifier. 6781 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6782 if (FixedLM) { 6783 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6784 << LM.toString() << 0, 6785 getLocationOfByte(LM.getStart()), 6786 /*IsStringLocation*/true, 6787 getSpecifierRange(startSpecifier, specifierLen)); 6788 6789 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6790 << FixedLM->toString() 6791 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6792 6793 } else { 6794 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6795 << LM.toString() << 0, 6796 getLocationOfByte(LM.getStart()), 6797 /*IsStringLocation*/true, 6798 getSpecifierRange(startSpecifier, specifierLen)); 6799 } 6800 } 6801 6802 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6803 const analyze_format_string::ConversionSpecifier &CS, 6804 const char *startSpecifier, unsigned specifierLen) { 6805 using namespace analyze_format_string; 6806 6807 // See if we know how to fix this conversion specifier. 6808 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6809 if (FixedCS) { 6810 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6811 << CS.toString() << /*conversion specifier*/1, 6812 getLocationOfByte(CS.getStart()), 6813 /*IsStringLocation*/true, 6814 getSpecifierRange(startSpecifier, specifierLen)); 6815 6816 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6817 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6818 << FixedCS->toString() 6819 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6820 } else { 6821 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6822 << CS.toString() << /*conversion specifier*/1, 6823 getLocationOfByte(CS.getStart()), 6824 /*IsStringLocation*/true, 6825 getSpecifierRange(startSpecifier, specifierLen)); 6826 } 6827 } 6828 6829 void CheckFormatHandler::HandlePosition(const char *startPos, 6830 unsigned posLen) { 6831 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6832 getLocationOfByte(startPos), 6833 /*IsStringLocation*/true, 6834 getSpecifierRange(startPos, posLen)); 6835 } 6836 6837 void 6838 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 6839 analyze_format_string::PositionContext p) { 6840 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 6841 << (unsigned) p, 6842 getLocationOfByte(startPos), /*IsStringLocation*/true, 6843 getSpecifierRange(startPos, posLen)); 6844 } 6845 6846 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6847 unsigned posLen) { 6848 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6849 getLocationOfByte(startPos), 6850 /*IsStringLocation*/true, 6851 getSpecifierRange(startPos, posLen)); 6852 } 6853 6854 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6855 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6856 // The presence of a null character is likely an error. 6857 EmitFormatDiagnostic( 6858 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6859 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6860 getFormatStringRange()); 6861 } 6862 } 6863 6864 // Note that this may return NULL if there was an error parsing or building 6865 // one of the argument expressions. 6866 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6867 return Args[FirstDataArg + i]; 6868 } 6869 6870 void CheckFormatHandler::DoneProcessing() { 6871 // Does the number of data arguments exceed the number of 6872 // format conversions in the format string? 6873 if (!HasVAListArg) { 6874 // Find any arguments that weren't covered. 6875 CoveredArgs.flip(); 6876 signed notCoveredArg = CoveredArgs.find_first(); 6877 if (notCoveredArg >= 0) { 6878 assert((unsigned)notCoveredArg < NumDataArgs); 6879 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6880 } else { 6881 UncoveredArg.setAllCovered(); 6882 } 6883 } 6884 } 6885 6886 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6887 const Expr *ArgExpr) { 6888 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6889 "Invalid state"); 6890 6891 if (!ArgExpr) 6892 return; 6893 6894 SourceLocation Loc = ArgExpr->getBeginLoc(); 6895 6896 if (S.getSourceManager().isInSystemMacro(Loc)) 6897 return; 6898 6899 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6900 for (auto E : DiagnosticExprs) 6901 PDiag << E->getSourceRange(); 6902 6903 CheckFormatHandler::EmitFormatDiagnostic( 6904 S, IsFunctionCall, DiagnosticExprs[0], 6905 PDiag, Loc, /*IsStringLocation*/false, 6906 DiagnosticExprs[0]->getSourceRange()); 6907 } 6908 6909 bool 6910 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6911 SourceLocation Loc, 6912 const char *startSpec, 6913 unsigned specifierLen, 6914 const char *csStart, 6915 unsigned csLen) { 6916 bool keepGoing = true; 6917 if (argIndex < NumDataArgs) { 6918 // Consider the argument coverered, even though the specifier doesn't 6919 // make sense. 6920 CoveredArgs.set(argIndex); 6921 } 6922 else { 6923 // If argIndex exceeds the number of data arguments we 6924 // don't issue a warning because that is just a cascade of warnings (and 6925 // they may have intended '%%' anyway). We don't want to continue processing 6926 // the format string after this point, however, as we will like just get 6927 // gibberish when trying to match arguments. 6928 keepGoing = false; 6929 } 6930 6931 StringRef Specifier(csStart, csLen); 6932 6933 // If the specifier in non-printable, it could be the first byte of a UTF-8 6934 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6935 // hex value. 6936 std::string CodePointStr; 6937 if (!llvm::sys::locale::isPrint(*csStart)) { 6938 llvm::UTF32 CodePoint; 6939 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6940 const llvm::UTF8 *E = 6941 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6942 llvm::ConversionResult Result = 6943 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6944 6945 if (Result != llvm::conversionOK) { 6946 unsigned char FirstChar = *csStart; 6947 CodePoint = (llvm::UTF32)FirstChar; 6948 } 6949 6950 llvm::raw_string_ostream OS(CodePointStr); 6951 if (CodePoint < 256) 6952 OS << "\\x" << llvm::format("%02x", CodePoint); 6953 else if (CodePoint <= 0xFFFF) 6954 OS << "\\u" << llvm::format("%04x", CodePoint); 6955 else 6956 OS << "\\U" << llvm::format("%08x", CodePoint); 6957 OS.flush(); 6958 Specifier = CodePointStr; 6959 } 6960 6961 EmitFormatDiagnostic( 6962 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 6963 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 6964 6965 return keepGoing; 6966 } 6967 6968 void 6969 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 6970 const char *startSpec, 6971 unsigned specifierLen) { 6972 EmitFormatDiagnostic( 6973 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 6974 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 6975 } 6976 6977 bool 6978 CheckFormatHandler::CheckNumArgs( 6979 const analyze_format_string::FormatSpecifier &FS, 6980 const analyze_format_string::ConversionSpecifier &CS, 6981 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 6982 6983 if (argIndex >= NumDataArgs) { 6984 PartialDiagnostic PDiag = FS.usesPositionalArg() 6985 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 6986 << (argIndex+1) << NumDataArgs) 6987 : S.PDiag(diag::warn_printf_insufficient_data_args); 6988 EmitFormatDiagnostic( 6989 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 6990 getSpecifierRange(startSpecifier, specifierLen)); 6991 6992 // Since more arguments than conversion tokens are given, by extension 6993 // all arguments are covered, so mark this as so. 6994 UncoveredArg.setAllCovered(); 6995 return false; 6996 } 6997 return true; 6998 } 6999 7000 template<typename Range> 7001 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7002 SourceLocation Loc, 7003 bool IsStringLocation, 7004 Range StringRange, 7005 ArrayRef<FixItHint> FixIt) { 7006 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7007 Loc, IsStringLocation, StringRange, FixIt); 7008 } 7009 7010 /// If the format string is not within the function call, emit a note 7011 /// so that the function call and string are in diagnostic messages. 7012 /// 7013 /// \param InFunctionCall if true, the format string is within the function 7014 /// call and only one diagnostic message will be produced. Otherwise, an 7015 /// extra note will be emitted pointing to location of the format string. 7016 /// 7017 /// \param ArgumentExpr the expression that is passed as the format string 7018 /// argument in the function call. Used for getting locations when two 7019 /// diagnostics are emitted. 7020 /// 7021 /// \param PDiag the callee should already have provided any strings for the 7022 /// diagnostic message. This function only adds locations and fixits 7023 /// to diagnostics. 7024 /// 7025 /// \param Loc primary location for diagnostic. If two diagnostics are 7026 /// required, one will be at Loc and a new SourceLocation will be created for 7027 /// the other one. 7028 /// 7029 /// \param IsStringLocation if true, Loc points to the format string should be 7030 /// used for the note. Otherwise, Loc points to the argument list and will 7031 /// be used with PDiag. 7032 /// 7033 /// \param StringRange some or all of the string to highlight. This is 7034 /// templated so it can accept either a CharSourceRange or a SourceRange. 7035 /// 7036 /// \param FixIt optional fix it hint for the format string. 7037 template <typename Range> 7038 void CheckFormatHandler::EmitFormatDiagnostic( 7039 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7040 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7041 Range StringRange, ArrayRef<FixItHint> FixIt) { 7042 if (InFunctionCall) { 7043 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7044 D << StringRange; 7045 D << FixIt; 7046 } else { 7047 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7048 << ArgumentExpr->getSourceRange(); 7049 7050 const Sema::SemaDiagnosticBuilder &Note = 7051 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7052 diag::note_format_string_defined); 7053 7054 Note << StringRange; 7055 Note << FixIt; 7056 } 7057 } 7058 7059 //===--- CHECK: Printf format string checking ------------------------------===// 7060 7061 namespace { 7062 7063 class CheckPrintfHandler : public CheckFormatHandler { 7064 public: 7065 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7066 const Expr *origFormatExpr, 7067 const Sema::FormatStringType type, unsigned firstDataArg, 7068 unsigned numDataArgs, bool isObjC, const char *beg, 7069 bool hasVAListArg, ArrayRef<const Expr *> Args, 7070 unsigned formatIdx, bool inFunctionCall, 7071 Sema::VariadicCallType CallType, 7072 llvm::SmallBitVector &CheckedVarArgs, 7073 UncoveredArgHandler &UncoveredArg) 7074 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7075 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7076 inFunctionCall, CallType, CheckedVarArgs, 7077 UncoveredArg) {} 7078 7079 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7080 7081 /// Returns true if '%@' specifiers are allowed in the format string. 7082 bool allowsObjCArg() const { 7083 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7084 FSType == Sema::FST_OSTrace; 7085 } 7086 7087 bool HandleInvalidPrintfConversionSpecifier( 7088 const analyze_printf::PrintfSpecifier &FS, 7089 const char *startSpecifier, 7090 unsigned specifierLen) override; 7091 7092 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7093 const char *startSpecifier, 7094 unsigned specifierLen) override; 7095 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7096 const char *StartSpecifier, 7097 unsigned SpecifierLen, 7098 const Expr *E); 7099 7100 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7101 const char *startSpecifier, unsigned specifierLen); 7102 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7103 const analyze_printf::OptionalAmount &Amt, 7104 unsigned type, 7105 const char *startSpecifier, unsigned specifierLen); 7106 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7107 const analyze_printf::OptionalFlag &flag, 7108 const char *startSpecifier, unsigned specifierLen); 7109 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7110 const analyze_printf::OptionalFlag &ignoredFlag, 7111 const analyze_printf::OptionalFlag &flag, 7112 const char *startSpecifier, unsigned specifierLen); 7113 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7114 const Expr *E); 7115 7116 void HandleEmptyObjCModifierFlag(const char *startFlag, 7117 unsigned flagLen) override; 7118 7119 void HandleInvalidObjCModifierFlag(const char *startFlag, 7120 unsigned flagLen) override; 7121 7122 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7123 const char *flagsEnd, 7124 const char *conversionPosition) 7125 override; 7126 }; 7127 7128 } // namespace 7129 7130 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7131 const analyze_printf::PrintfSpecifier &FS, 7132 const char *startSpecifier, 7133 unsigned specifierLen) { 7134 const analyze_printf::PrintfConversionSpecifier &CS = 7135 FS.getConversionSpecifier(); 7136 7137 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7138 getLocationOfByte(CS.getStart()), 7139 startSpecifier, specifierLen, 7140 CS.getStart(), CS.getLength()); 7141 } 7142 7143 bool CheckPrintfHandler::HandleAmount( 7144 const analyze_format_string::OptionalAmount &Amt, 7145 unsigned k, const char *startSpecifier, 7146 unsigned specifierLen) { 7147 if (Amt.hasDataArgument()) { 7148 if (!HasVAListArg) { 7149 unsigned argIndex = Amt.getArgIndex(); 7150 if (argIndex >= NumDataArgs) { 7151 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7152 << k, 7153 getLocationOfByte(Amt.getStart()), 7154 /*IsStringLocation*/true, 7155 getSpecifierRange(startSpecifier, specifierLen)); 7156 // Don't do any more checking. We will just emit 7157 // spurious errors. 7158 return false; 7159 } 7160 7161 // Type check the data argument. It should be an 'int'. 7162 // Although not in conformance with C99, we also allow the argument to be 7163 // an 'unsigned int' as that is a reasonably safe case. GCC also 7164 // doesn't emit a warning for that case. 7165 CoveredArgs.set(argIndex); 7166 const Expr *Arg = getDataArg(argIndex); 7167 if (!Arg) 7168 return false; 7169 7170 QualType T = Arg->getType(); 7171 7172 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7173 assert(AT.isValid()); 7174 7175 if (!AT.matchesType(S.Context, T)) { 7176 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7177 << k << AT.getRepresentativeTypeName(S.Context) 7178 << T << Arg->getSourceRange(), 7179 getLocationOfByte(Amt.getStart()), 7180 /*IsStringLocation*/true, 7181 getSpecifierRange(startSpecifier, specifierLen)); 7182 // Don't do any more checking. We will just emit 7183 // spurious errors. 7184 return false; 7185 } 7186 } 7187 } 7188 return true; 7189 } 7190 7191 void CheckPrintfHandler::HandleInvalidAmount( 7192 const analyze_printf::PrintfSpecifier &FS, 7193 const analyze_printf::OptionalAmount &Amt, 7194 unsigned type, 7195 const char *startSpecifier, 7196 unsigned specifierLen) { 7197 const analyze_printf::PrintfConversionSpecifier &CS = 7198 FS.getConversionSpecifier(); 7199 7200 FixItHint fixit = 7201 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7202 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7203 Amt.getConstantLength())) 7204 : FixItHint(); 7205 7206 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7207 << type << CS.toString(), 7208 getLocationOfByte(Amt.getStart()), 7209 /*IsStringLocation*/true, 7210 getSpecifierRange(startSpecifier, specifierLen), 7211 fixit); 7212 } 7213 7214 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7215 const analyze_printf::OptionalFlag &flag, 7216 const char *startSpecifier, 7217 unsigned specifierLen) { 7218 // Warn about pointless flag with a fixit removal. 7219 const analyze_printf::PrintfConversionSpecifier &CS = 7220 FS.getConversionSpecifier(); 7221 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7222 << flag.toString() << CS.toString(), 7223 getLocationOfByte(flag.getPosition()), 7224 /*IsStringLocation*/true, 7225 getSpecifierRange(startSpecifier, specifierLen), 7226 FixItHint::CreateRemoval( 7227 getSpecifierRange(flag.getPosition(), 1))); 7228 } 7229 7230 void CheckPrintfHandler::HandleIgnoredFlag( 7231 const analyze_printf::PrintfSpecifier &FS, 7232 const analyze_printf::OptionalFlag &ignoredFlag, 7233 const analyze_printf::OptionalFlag &flag, 7234 const char *startSpecifier, 7235 unsigned specifierLen) { 7236 // Warn about ignored flag with a fixit removal. 7237 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7238 << ignoredFlag.toString() << flag.toString(), 7239 getLocationOfByte(ignoredFlag.getPosition()), 7240 /*IsStringLocation*/true, 7241 getSpecifierRange(startSpecifier, specifierLen), 7242 FixItHint::CreateRemoval( 7243 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7244 } 7245 7246 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7247 unsigned flagLen) { 7248 // Warn about an empty flag. 7249 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7250 getLocationOfByte(startFlag), 7251 /*IsStringLocation*/true, 7252 getSpecifierRange(startFlag, flagLen)); 7253 } 7254 7255 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7256 unsigned flagLen) { 7257 // Warn about an invalid flag. 7258 auto Range = getSpecifierRange(startFlag, flagLen); 7259 StringRef flag(startFlag, flagLen); 7260 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7261 getLocationOfByte(startFlag), 7262 /*IsStringLocation*/true, 7263 Range, FixItHint::CreateRemoval(Range)); 7264 } 7265 7266 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7267 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7268 // Warn about using '[...]' without a '@' conversion. 7269 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7270 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7271 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7272 getLocationOfByte(conversionPosition), 7273 /*IsStringLocation*/true, 7274 Range, FixItHint::CreateRemoval(Range)); 7275 } 7276 7277 // Determines if the specified is a C++ class or struct containing 7278 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7279 // "c_str()"). 7280 template<typename MemberKind> 7281 static llvm::SmallPtrSet<MemberKind*, 1> 7282 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7283 const RecordType *RT = Ty->getAs<RecordType>(); 7284 llvm::SmallPtrSet<MemberKind*, 1> Results; 7285 7286 if (!RT) 7287 return Results; 7288 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7289 if (!RD || !RD->getDefinition()) 7290 return Results; 7291 7292 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7293 Sema::LookupMemberName); 7294 R.suppressDiagnostics(); 7295 7296 // We just need to include all members of the right kind turned up by the 7297 // filter, at this point. 7298 if (S.LookupQualifiedName(R, RT->getDecl())) 7299 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7300 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7301 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7302 Results.insert(FK); 7303 } 7304 return Results; 7305 } 7306 7307 /// Check if we could call '.c_str()' on an object. 7308 /// 7309 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7310 /// allow the call, or if it would be ambiguous). 7311 bool Sema::hasCStrMethod(const Expr *E) { 7312 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7313 7314 MethodSet Results = 7315 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7316 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7317 MI != ME; ++MI) 7318 if ((*MI)->getMinRequiredArguments() == 0) 7319 return true; 7320 return false; 7321 } 7322 7323 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7324 // better diagnostic if so. AT is assumed to be valid. 7325 // Returns true when a c_str() conversion method is found. 7326 bool CheckPrintfHandler::checkForCStrMembers( 7327 const analyze_printf::ArgType &AT, const Expr *E) { 7328 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7329 7330 MethodSet Results = 7331 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7332 7333 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7334 MI != ME; ++MI) { 7335 const CXXMethodDecl *Method = *MI; 7336 if (Method->getMinRequiredArguments() == 0 && 7337 AT.matchesType(S.Context, Method->getReturnType())) { 7338 // FIXME: Suggest parens if the expression needs them. 7339 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7340 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7341 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7342 return true; 7343 } 7344 } 7345 7346 return false; 7347 } 7348 7349 bool 7350 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7351 &FS, 7352 const char *startSpecifier, 7353 unsigned specifierLen) { 7354 using namespace analyze_format_string; 7355 using namespace analyze_printf; 7356 7357 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7358 7359 if (FS.consumesDataArgument()) { 7360 if (atFirstArg) { 7361 atFirstArg = false; 7362 usesPositionalArgs = FS.usesPositionalArg(); 7363 } 7364 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7365 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7366 startSpecifier, specifierLen); 7367 return false; 7368 } 7369 } 7370 7371 // First check if the field width, precision, and conversion specifier 7372 // have matching data arguments. 7373 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7374 startSpecifier, specifierLen)) { 7375 return false; 7376 } 7377 7378 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7379 startSpecifier, specifierLen)) { 7380 return false; 7381 } 7382 7383 if (!CS.consumesDataArgument()) { 7384 // FIXME: Technically specifying a precision or field width here 7385 // makes no sense. Worth issuing a warning at some point. 7386 return true; 7387 } 7388 7389 // Consume the argument. 7390 unsigned argIndex = FS.getArgIndex(); 7391 if (argIndex < NumDataArgs) { 7392 // The check to see if the argIndex is valid will come later. 7393 // We set the bit here because we may exit early from this 7394 // function if we encounter some other error. 7395 CoveredArgs.set(argIndex); 7396 } 7397 7398 // FreeBSD kernel extensions. 7399 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7400 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7401 // We need at least two arguments. 7402 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7403 return false; 7404 7405 // Claim the second argument. 7406 CoveredArgs.set(argIndex + 1); 7407 7408 // Type check the first argument (int for %b, pointer for %D) 7409 const Expr *Ex = getDataArg(argIndex); 7410 const analyze_printf::ArgType &AT = 7411 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7412 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7413 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7414 EmitFormatDiagnostic( 7415 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7416 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7417 << false << Ex->getSourceRange(), 7418 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7419 getSpecifierRange(startSpecifier, specifierLen)); 7420 7421 // Type check the second argument (char * for both %b and %D) 7422 Ex = getDataArg(argIndex + 1); 7423 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7424 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7425 EmitFormatDiagnostic( 7426 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7427 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7428 << false << Ex->getSourceRange(), 7429 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7430 getSpecifierRange(startSpecifier, specifierLen)); 7431 7432 return true; 7433 } 7434 7435 // Check for using an Objective-C specific conversion specifier 7436 // in a non-ObjC literal. 7437 if (!allowsObjCArg() && CS.isObjCArg()) { 7438 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7439 specifierLen); 7440 } 7441 7442 // %P can only be used with os_log. 7443 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7444 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7445 specifierLen); 7446 } 7447 7448 // %n is not allowed with os_log. 7449 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7450 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7451 getLocationOfByte(CS.getStart()), 7452 /*IsStringLocation*/ false, 7453 getSpecifierRange(startSpecifier, specifierLen)); 7454 7455 return true; 7456 } 7457 7458 // Only scalars are allowed for os_trace. 7459 if (FSType == Sema::FST_OSTrace && 7460 (CS.getKind() == ConversionSpecifier::PArg || 7461 CS.getKind() == ConversionSpecifier::sArg || 7462 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7463 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7464 specifierLen); 7465 } 7466 7467 // Check for use of public/private annotation outside of os_log(). 7468 if (FSType != Sema::FST_OSLog) { 7469 if (FS.isPublic().isSet()) { 7470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7471 << "public", 7472 getLocationOfByte(FS.isPublic().getPosition()), 7473 /*IsStringLocation*/ false, 7474 getSpecifierRange(startSpecifier, specifierLen)); 7475 } 7476 if (FS.isPrivate().isSet()) { 7477 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7478 << "private", 7479 getLocationOfByte(FS.isPrivate().getPosition()), 7480 /*IsStringLocation*/ false, 7481 getSpecifierRange(startSpecifier, specifierLen)); 7482 } 7483 } 7484 7485 // Check for invalid use of field width 7486 if (!FS.hasValidFieldWidth()) { 7487 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7488 startSpecifier, specifierLen); 7489 } 7490 7491 // Check for invalid use of precision 7492 if (!FS.hasValidPrecision()) { 7493 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7494 startSpecifier, specifierLen); 7495 } 7496 7497 // Precision is mandatory for %P specifier. 7498 if (CS.getKind() == ConversionSpecifier::PArg && 7499 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7501 getLocationOfByte(startSpecifier), 7502 /*IsStringLocation*/ false, 7503 getSpecifierRange(startSpecifier, specifierLen)); 7504 } 7505 7506 // Check each flag does not conflict with any other component. 7507 if (!FS.hasValidThousandsGroupingPrefix()) 7508 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7509 if (!FS.hasValidLeadingZeros()) 7510 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7511 if (!FS.hasValidPlusPrefix()) 7512 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7513 if (!FS.hasValidSpacePrefix()) 7514 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7515 if (!FS.hasValidAlternativeForm()) 7516 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7517 if (!FS.hasValidLeftJustified()) 7518 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7519 7520 // Check that flags are not ignored by another flag 7521 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7522 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7523 startSpecifier, specifierLen); 7524 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7525 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7526 startSpecifier, specifierLen); 7527 7528 // Check the length modifier is valid with the given conversion specifier. 7529 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7530 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7531 diag::warn_format_nonsensical_length); 7532 else if (!FS.hasStandardLengthModifier()) 7533 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7534 else if (!FS.hasStandardLengthConversionCombination()) 7535 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7536 diag::warn_format_non_standard_conversion_spec); 7537 7538 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7539 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7540 7541 // The remaining checks depend on the data arguments. 7542 if (HasVAListArg) 7543 return true; 7544 7545 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7546 return false; 7547 7548 const Expr *Arg = getDataArg(argIndex); 7549 if (!Arg) 7550 return true; 7551 7552 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7553 } 7554 7555 static bool requiresParensToAddCast(const Expr *E) { 7556 // FIXME: We should have a general way to reason about operator 7557 // precedence and whether parens are actually needed here. 7558 // Take care of a few common cases where they aren't. 7559 const Expr *Inside = E->IgnoreImpCasts(); 7560 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7561 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7562 7563 switch (Inside->getStmtClass()) { 7564 case Stmt::ArraySubscriptExprClass: 7565 case Stmt::CallExprClass: 7566 case Stmt::CharacterLiteralClass: 7567 case Stmt::CXXBoolLiteralExprClass: 7568 case Stmt::DeclRefExprClass: 7569 case Stmt::FloatingLiteralClass: 7570 case Stmt::IntegerLiteralClass: 7571 case Stmt::MemberExprClass: 7572 case Stmt::ObjCArrayLiteralClass: 7573 case Stmt::ObjCBoolLiteralExprClass: 7574 case Stmt::ObjCBoxedExprClass: 7575 case Stmt::ObjCDictionaryLiteralClass: 7576 case Stmt::ObjCEncodeExprClass: 7577 case Stmt::ObjCIvarRefExprClass: 7578 case Stmt::ObjCMessageExprClass: 7579 case Stmt::ObjCPropertyRefExprClass: 7580 case Stmt::ObjCStringLiteralClass: 7581 case Stmt::ObjCSubscriptRefExprClass: 7582 case Stmt::ParenExprClass: 7583 case Stmt::StringLiteralClass: 7584 case Stmt::UnaryOperatorClass: 7585 return false; 7586 default: 7587 return true; 7588 } 7589 } 7590 7591 static std::pair<QualType, StringRef> 7592 shouldNotPrintDirectly(const ASTContext &Context, 7593 QualType IntendedTy, 7594 const Expr *E) { 7595 // Use a 'while' to peel off layers of typedefs. 7596 QualType TyTy = IntendedTy; 7597 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7598 StringRef Name = UserTy->getDecl()->getName(); 7599 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7600 .Case("CFIndex", Context.getNSIntegerType()) 7601 .Case("NSInteger", Context.getNSIntegerType()) 7602 .Case("NSUInteger", Context.getNSUIntegerType()) 7603 .Case("SInt32", Context.IntTy) 7604 .Case("UInt32", Context.UnsignedIntTy) 7605 .Default(QualType()); 7606 7607 if (!CastTy.isNull()) 7608 return std::make_pair(CastTy, Name); 7609 7610 TyTy = UserTy->desugar(); 7611 } 7612 7613 // Strip parens if necessary. 7614 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7615 return shouldNotPrintDirectly(Context, 7616 PE->getSubExpr()->getType(), 7617 PE->getSubExpr()); 7618 7619 // If this is a conditional expression, then its result type is constructed 7620 // via usual arithmetic conversions and thus there might be no necessary 7621 // typedef sugar there. Recurse to operands to check for NSInteger & 7622 // Co. usage condition. 7623 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7624 QualType TrueTy, FalseTy; 7625 StringRef TrueName, FalseName; 7626 7627 std::tie(TrueTy, TrueName) = 7628 shouldNotPrintDirectly(Context, 7629 CO->getTrueExpr()->getType(), 7630 CO->getTrueExpr()); 7631 std::tie(FalseTy, FalseName) = 7632 shouldNotPrintDirectly(Context, 7633 CO->getFalseExpr()->getType(), 7634 CO->getFalseExpr()); 7635 7636 if (TrueTy == FalseTy) 7637 return std::make_pair(TrueTy, TrueName); 7638 else if (TrueTy.isNull()) 7639 return std::make_pair(FalseTy, FalseName); 7640 else if (FalseTy.isNull()) 7641 return std::make_pair(TrueTy, TrueName); 7642 } 7643 7644 return std::make_pair(QualType(), StringRef()); 7645 } 7646 7647 bool 7648 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7649 const char *StartSpecifier, 7650 unsigned SpecifierLen, 7651 const Expr *E) { 7652 using namespace analyze_format_string; 7653 using namespace analyze_printf; 7654 7655 // Now type check the data expression that matches the 7656 // format specifier. 7657 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7658 if (!AT.isValid()) 7659 return true; 7660 7661 QualType ExprTy = E->getType(); 7662 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7663 ExprTy = TET->getUnderlyingExpr()->getType(); 7664 } 7665 7666 const analyze_printf::ArgType::MatchKind Match = 7667 AT.matchesType(S.Context, ExprTy); 7668 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7669 if (Match == analyze_printf::ArgType::Match) 7670 return true; 7671 7672 // Look through argument promotions for our error message's reported type. 7673 // This includes the integral and floating promotions, but excludes array 7674 // and function pointer decay; seeing that an argument intended to be a 7675 // string has type 'char [6]' is probably more confusing than 'char *'. 7676 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7677 if (ICE->getCastKind() == CK_IntegralCast || 7678 ICE->getCastKind() == CK_FloatingCast) { 7679 E = ICE->getSubExpr(); 7680 ExprTy = E->getType(); 7681 7682 // Check if we didn't match because of an implicit cast from a 'char' 7683 // or 'short' to an 'int'. This is done because printf is a varargs 7684 // function. 7685 if (ICE->getType() == S.Context.IntTy || 7686 ICE->getType() == S.Context.UnsignedIntTy) { 7687 // All further checking is done on the subexpression. 7688 if (AT.matchesType(S.Context, ExprTy)) 7689 return true; 7690 } 7691 } 7692 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7693 // Special case for 'a', which has type 'int' in C. 7694 // Note, however, that we do /not/ want to treat multibyte constants like 7695 // 'MooV' as characters! This form is deprecated but still exists. 7696 if (ExprTy == S.Context.IntTy) 7697 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7698 ExprTy = S.Context.CharTy; 7699 } 7700 7701 // Look through enums to their underlying type. 7702 bool IsEnum = false; 7703 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7704 ExprTy = EnumTy->getDecl()->getIntegerType(); 7705 IsEnum = true; 7706 } 7707 7708 // %C in an Objective-C context prints a unichar, not a wchar_t. 7709 // If the argument is an integer of some kind, believe the %C and suggest 7710 // a cast instead of changing the conversion specifier. 7711 QualType IntendedTy = ExprTy; 7712 if (isObjCContext() && 7713 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7714 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7715 !ExprTy->isCharType()) { 7716 // 'unichar' is defined as a typedef of unsigned short, but we should 7717 // prefer using the typedef if it is visible. 7718 IntendedTy = S.Context.UnsignedShortTy; 7719 7720 // While we are here, check if the value is an IntegerLiteral that happens 7721 // to be within the valid range. 7722 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7723 const llvm::APInt &V = IL->getValue(); 7724 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7725 return true; 7726 } 7727 7728 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7729 Sema::LookupOrdinaryName); 7730 if (S.LookupName(Result, S.getCurScope())) { 7731 NamedDecl *ND = Result.getFoundDecl(); 7732 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7733 if (TD->getUnderlyingType() == IntendedTy) 7734 IntendedTy = S.Context.getTypedefType(TD); 7735 } 7736 } 7737 } 7738 7739 // Special-case some of Darwin's platform-independence types by suggesting 7740 // casts to primitive types that are known to be large enough. 7741 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7742 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7743 QualType CastTy; 7744 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7745 if (!CastTy.isNull()) { 7746 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7747 // (long in ASTContext). Only complain to pedants. 7748 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7749 (AT.isSizeT() || AT.isPtrdiffT()) && 7750 AT.matchesType(S.Context, CastTy)) 7751 Pedantic = true; 7752 IntendedTy = CastTy; 7753 ShouldNotPrintDirectly = true; 7754 } 7755 } 7756 7757 // We may be able to offer a FixItHint if it is a supported type. 7758 PrintfSpecifier fixedFS = FS; 7759 bool Success = 7760 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7761 7762 if (Success) { 7763 // Get the fix string from the fixed format specifier 7764 SmallString<16> buf; 7765 llvm::raw_svector_ostream os(buf); 7766 fixedFS.toString(os); 7767 7768 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7769 7770 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7771 unsigned Diag = 7772 Pedantic 7773 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7774 : diag::warn_format_conversion_argument_type_mismatch; 7775 // In this case, the specifier is wrong and should be changed to match 7776 // the argument. 7777 EmitFormatDiagnostic(S.PDiag(Diag) 7778 << AT.getRepresentativeTypeName(S.Context) 7779 << IntendedTy << IsEnum << E->getSourceRange(), 7780 E->getBeginLoc(), 7781 /*IsStringLocation*/ false, SpecRange, 7782 FixItHint::CreateReplacement(SpecRange, os.str())); 7783 } else { 7784 // The canonical type for formatting this value is different from the 7785 // actual type of the expression. (This occurs, for example, with Darwin's 7786 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7787 // should be printed as 'long' for 64-bit compatibility.) 7788 // Rather than emitting a normal format/argument mismatch, we want to 7789 // add a cast to the recommended type (and correct the format string 7790 // if necessary). 7791 SmallString<16> CastBuf; 7792 llvm::raw_svector_ostream CastFix(CastBuf); 7793 CastFix << "("; 7794 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7795 CastFix << ")"; 7796 7797 SmallVector<FixItHint,4> Hints; 7798 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 7799 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7800 7801 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7802 // If there's already a cast present, just replace it. 7803 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7804 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7805 7806 } else if (!requiresParensToAddCast(E)) { 7807 // If the expression has high enough precedence, 7808 // just write the C-style cast. 7809 Hints.push_back( 7810 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7811 } else { 7812 // Otherwise, add parens around the expression as well as the cast. 7813 CastFix << "("; 7814 Hints.push_back( 7815 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7816 7817 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 7818 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7819 } 7820 7821 if (ShouldNotPrintDirectly) { 7822 // The expression has a type that should not be printed directly. 7823 // We extract the name from the typedef because we don't want to show 7824 // the underlying type in the diagnostic. 7825 StringRef Name; 7826 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 7827 Name = TypedefTy->getDecl()->getName(); 7828 else 7829 Name = CastTyName; 7830 unsigned Diag = Pedantic 7831 ? diag::warn_format_argument_needs_cast_pedantic 7832 : diag::warn_format_argument_needs_cast; 7833 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7834 << E->getSourceRange(), 7835 E->getBeginLoc(), /*IsStringLocation=*/false, 7836 SpecRange, Hints); 7837 } else { 7838 // In this case, the expression could be printed using a different 7839 // specifier, but we've decided that the specifier is probably correct 7840 // and we should cast instead. Just use the normal warning message. 7841 EmitFormatDiagnostic( 7842 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7843 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 7844 << E->getSourceRange(), 7845 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7846 } 7847 } 7848 } else { 7849 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7850 SpecifierLen); 7851 // Since the warning for passing non-POD types to variadic functions 7852 // was deferred until now, we emit a warning for non-POD 7853 // arguments here. 7854 switch (S.isValidVarArgType(ExprTy)) { 7855 case Sema::VAK_Valid: 7856 case Sema::VAK_ValidInCXX11: { 7857 unsigned Diag = 7858 Pedantic 7859 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7860 : diag::warn_format_conversion_argument_type_mismatch; 7861 7862 EmitFormatDiagnostic( 7863 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7864 << IsEnum << CSR << E->getSourceRange(), 7865 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7866 break; 7867 } 7868 case Sema::VAK_Undefined: 7869 case Sema::VAK_MSVCUndefined: 7870 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 7871 << S.getLangOpts().CPlusPlus11 << ExprTy 7872 << CallType 7873 << AT.getRepresentativeTypeName(S.Context) << CSR 7874 << E->getSourceRange(), 7875 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7876 checkForCStrMembers(AT, E); 7877 break; 7878 7879 case Sema::VAK_Invalid: 7880 if (ExprTy->isObjCObjectType()) 7881 EmitFormatDiagnostic( 7882 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7883 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 7884 << AT.getRepresentativeTypeName(S.Context) << CSR 7885 << E->getSourceRange(), 7886 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7887 else 7888 // FIXME: If this is an initializer list, suggest removing the braces 7889 // or inserting a cast to the target type. 7890 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 7891 << isa<InitListExpr>(E) << ExprTy << CallType 7892 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 7893 break; 7894 } 7895 7896 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7897 "format string specifier index out of range"); 7898 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7899 } 7900 7901 return true; 7902 } 7903 7904 //===--- CHECK: Scanf format string checking ------------------------------===// 7905 7906 namespace { 7907 7908 class CheckScanfHandler : public CheckFormatHandler { 7909 public: 7910 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7911 const Expr *origFormatExpr, Sema::FormatStringType type, 7912 unsigned firstDataArg, unsigned numDataArgs, 7913 const char *beg, bool hasVAListArg, 7914 ArrayRef<const Expr *> Args, unsigned formatIdx, 7915 bool inFunctionCall, Sema::VariadicCallType CallType, 7916 llvm::SmallBitVector &CheckedVarArgs, 7917 UncoveredArgHandler &UncoveredArg) 7918 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7919 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7920 inFunctionCall, CallType, CheckedVarArgs, 7921 UncoveredArg) {} 7922 7923 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7924 const char *startSpecifier, 7925 unsigned specifierLen) override; 7926 7927 bool HandleInvalidScanfConversionSpecifier( 7928 const analyze_scanf::ScanfSpecifier &FS, 7929 const char *startSpecifier, 7930 unsigned specifierLen) override; 7931 7932 void HandleIncompleteScanList(const char *start, const char *end) override; 7933 }; 7934 7935 } // namespace 7936 7937 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7938 const char *end) { 7939 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7940 getLocationOfByte(end), /*IsStringLocation*/true, 7941 getSpecifierRange(start, end - start)); 7942 } 7943 7944 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7945 const analyze_scanf::ScanfSpecifier &FS, 7946 const char *startSpecifier, 7947 unsigned specifierLen) { 7948 const analyze_scanf::ScanfConversionSpecifier &CS = 7949 FS.getConversionSpecifier(); 7950 7951 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7952 getLocationOfByte(CS.getStart()), 7953 startSpecifier, specifierLen, 7954 CS.getStart(), CS.getLength()); 7955 } 7956 7957 bool CheckScanfHandler::HandleScanfSpecifier( 7958 const analyze_scanf::ScanfSpecifier &FS, 7959 const char *startSpecifier, 7960 unsigned specifierLen) { 7961 using namespace analyze_scanf; 7962 using namespace analyze_format_string; 7963 7964 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 7965 7966 // Handle case where '%' and '*' don't consume an argument. These shouldn't 7967 // be used to decide if we are using positional arguments consistently. 7968 if (FS.consumesDataArgument()) { 7969 if (atFirstArg) { 7970 atFirstArg = false; 7971 usesPositionalArgs = FS.usesPositionalArg(); 7972 } 7973 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7974 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7975 startSpecifier, specifierLen); 7976 return false; 7977 } 7978 } 7979 7980 // Check if the field with is non-zero. 7981 const OptionalAmount &Amt = FS.getFieldWidth(); 7982 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 7983 if (Amt.getConstantAmount() == 0) { 7984 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 7985 Amt.getConstantLength()); 7986 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 7987 getLocationOfByte(Amt.getStart()), 7988 /*IsStringLocation*/true, R, 7989 FixItHint::CreateRemoval(R)); 7990 } 7991 } 7992 7993 if (!FS.consumesDataArgument()) { 7994 // FIXME: Technically specifying a precision or field width here 7995 // makes no sense. Worth issuing a warning at some point. 7996 return true; 7997 } 7998 7999 // Consume the argument. 8000 unsigned argIndex = FS.getArgIndex(); 8001 if (argIndex < NumDataArgs) { 8002 // The check to see if the argIndex is valid will come later. 8003 // We set the bit here because we may exit early from this 8004 // function if we encounter some other error. 8005 CoveredArgs.set(argIndex); 8006 } 8007 8008 // Check the length modifier is valid with the given conversion specifier. 8009 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 8010 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8011 diag::warn_format_nonsensical_length); 8012 else if (!FS.hasStandardLengthModifier()) 8013 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8014 else if (!FS.hasStandardLengthConversionCombination()) 8015 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8016 diag::warn_format_non_standard_conversion_spec); 8017 8018 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8019 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8020 8021 // The remaining checks depend on the data arguments. 8022 if (HasVAListArg) 8023 return true; 8024 8025 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8026 return false; 8027 8028 // Check that the argument type matches the format specifier. 8029 const Expr *Ex = getDataArg(argIndex); 8030 if (!Ex) 8031 return true; 8032 8033 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8034 8035 if (!AT.isValid()) { 8036 return true; 8037 } 8038 8039 analyze_format_string::ArgType::MatchKind Match = 8040 AT.matchesType(S.Context, Ex->getType()); 8041 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8042 if (Match == analyze_format_string::ArgType::Match) 8043 return true; 8044 8045 ScanfSpecifier fixedFS = FS; 8046 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8047 S.getLangOpts(), S.Context); 8048 8049 unsigned Diag = 8050 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8051 : diag::warn_format_conversion_argument_type_mismatch; 8052 8053 if (Success) { 8054 // Get the fix string from the fixed format specifier. 8055 SmallString<128> buf; 8056 llvm::raw_svector_ostream os(buf); 8057 fixedFS.toString(os); 8058 8059 EmitFormatDiagnostic( 8060 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8061 << Ex->getType() << false << Ex->getSourceRange(), 8062 Ex->getBeginLoc(), 8063 /*IsStringLocation*/ false, 8064 getSpecifierRange(startSpecifier, specifierLen), 8065 FixItHint::CreateReplacement( 8066 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8067 } else { 8068 EmitFormatDiagnostic(S.PDiag(Diag) 8069 << AT.getRepresentativeTypeName(S.Context) 8070 << Ex->getType() << false << Ex->getSourceRange(), 8071 Ex->getBeginLoc(), 8072 /*IsStringLocation*/ false, 8073 getSpecifierRange(startSpecifier, specifierLen)); 8074 } 8075 8076 return true; 8077 } 8078 8079 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8080 const Expr *OrigFormatExpr, 8081 ArrayRef<const Expr *> Args, 8082 bool HasVAListArg, unsigned format_idx, 8083 unsigned firstDataArg, 8084 Sema::FormatStringType Type, 8085 bool inFunctionCall, 8086 Sema::VariadicCallType CallType, 8087 llvm::SmallBitVector &CheckedVarArgs, 8088 UncoveredArgHandler &UncoveredArg) { 8089 // CHECK: is the format string a wide literal? 8090 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8091 CheckFormatHandler::EmitFormatDiagnostic( 8092 S, inFunctionCall, Args[format_idx], 8093 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8094 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8095 return; 8096 } 8097 8098 // Str - The format string. NOTE: this is NOT null-terminated! 8099 StringRef StrRef = FExpr->getString(); 8100 const char *Str = StrRef.data(); 8101 // Account for cases where the string literal is truncated in a declaration. 8102 const ConstantArrayType *T = 8103 S.Context.getAsConstantArrayType(FExpr->getType()); 8104 assert(T && "String literal not of constant array type!"); 8105 size_t TypeSize = T->getSize().getZExtValue(); 8106 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8107 const unsigned numDataArgs = Args.size() - firstDataArg; 8108 8109 // Emit a warning if the string literal is truncated and does not contain an 8110 // embedded null character. 8111 if (TypeSize <= StrRef.size() && 8112 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8113 CheckFormatHandler::EmitFormatDiagnostic( 8114 S, inFunctionCall, Args[format_idx], 8115 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8116 FExpr->getBeginLoc(), 8117 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8118 return; 8119 } 8120 8121 // CHECK: empty format string? 8122 if (StrLen == 0 && numDataArgs > 0) { 8123 CheckFormatHandler::EmitFormatDiagnostic( 8124 S, inFunctionCall, Args[format_idx], 8125 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8126 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8127 return; 8128 } 8129 8130 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8131 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8132 Type == Sema::FST_OSTrace) { 8133 CheckPrintfHandler H( 8134 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8135 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8136 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8137 CheckedVarArgs, UncoveredArg); 8138 8139 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8140 S.getLangOpts(), 8141 S.Context.getTargetInfo(), 8142 Type == Sema::FST_FreeBSDKPrintf)) 8143 H.DoneProcessing(); 8144 } else if (Type == Sema::FST_Scanf) { 8145 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8146 numDataArgs, Str, HasVAListArg, Args, format_idx, 8147 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8148 8149 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8150 S.getLangOpts(), 8151 S.Context.getTargetInfo())) 8152 H.DoneProcessing(); 8153 } // TODO: handle other formats 8154 } 8155 8156 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8157 // Str - The format string. NOTE: this is NOT null-terminated! 8158 StringRef StrRef = FExpr->getString(); 8159 const char *Str = StrRef.data(); 8160 // Account for cases where the string literal is truncated in a declaration. 8161 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8162 assert(T && "String literal not of constant array type!"); 8163 size_t TypeSize = T->getSize().getZExtValue(); 8164 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8165 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8166 getLangOpts(), 8167 Context.getTargetInfo()); 8168 } 8169 8170 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8171 8172 // Returns the related absolute value function that is larger, of 0 if one 8173 // does not exist. 8174 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8175 switch (AbsFunction) { 8176 default: 8177 return 0; 8178 8179 case Builtin::BI__builtin_abs: 8180 return Builtin::BI__builtin_labs; 8181 case Builtin::BI__builtin_labs: 8182 return Builtin::BI__builtin_llabs; 8183 case Builtin::BI__builtin_llabs: 8184 return 0; 8185 8186 case Builtin::BI__builtin_fabsf: 8187 return Builtin::BI__builtin_fabs; 8188 case Builtin::BI__builtin_fabs: 8189 return Builtin::BI__builtin_fabsl; 8190 case Builtin::BI__builtin_fabsl: 8191 return 0; 8192 8193 case Builtin::BI__builtin_cabsf: 8194 return Builtin::BI__builtin_cabs; 8195 case Builtin::BI__builtin_cabs: 8196 return Builtin::BI__builtin_cabsl; 8197 case Builtin::BI__builtin_cabsl: 8198 return 0; 8199 8200 case Builtin::BIabs: 8201 return Builtin::BIlabs; 8202 case Builtin::BIlabs: 8203 return Builtin::BIllabs; 8204 case Builtin::BIllabs: 8205 return 0; 8206 8207 case Builtin::BIfabsf: 8208 return Builtin::BIfabs; 8209 case Builtin::BIfabs: 8210 return Builtin::BIfabsl; 8211 case Builtin::BIfabsl: 8212 return 0; 8213 8214 case Builtin::BIcabsf: 8215 return Builtin::BIcabs; 8216 case Builtin::BIcabs: 8217 return Builtin::BIcabsl; 8218 case Builtin::BIcabsl: 8219 return 0; 8220 } 8221 } 8222 8223 // Returns the argument type of the absolute value function. 8224 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8225 unsigned AbsType) { 8226 if (AbsType == 0) 8227 return QualType(); 8228 8229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8230 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8231 if (Error != ASTContext::GE_None) 8232 return QualType(); 8233 8234 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8235 if (!FT) 8236 return QualType(); 8237 8238 if (FT->getNumParams() != 1) 8239 return QualType(); 8240 8241 return FT->getParamType(0); 8242 } 8243 8244 // Returns the best absolute value function, or zero, based on type and 8245 // current absolute value function. 8246 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8247 unsigned AbsFunctionKind) { 8248 unsigned BestKind = 0; 8249 uint64_t ArgSize = Context.getTypeSize(ArgType); 8250 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8251 Kind = getLargerAbsoluteValueFunction(Kind)) { 8252 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8253 if (Context.getTypeSize(ParamType) >= ArgSize) { 8254 if (BestKind == 0) 8255 BestKind = Kind; 8256 else if (Context.hasSameType(ParamType, ArgType)) { 8257 BestKind = Kind; 8258 break; 8259 } 8260 } 8261 } 8262 return BestKind; 8263 } 8264 8265 enum AbsoluteValueKind { 8266 AVK_Integer, 8267 AVK_Floating, 8268 AVK_Complex 8269 }; 8270 8271 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8272 if (T->isIntegralOrEnumerationType()) 8273 return AVK_Integer; 8274 if (T->isRealFloatingType()) 8275 return AVK_Floating; 8276 if (T->isAnyComplexType()) 8277 return AVK_Complex; 8278 8279 llvm_unreachable("Type not integer, floating, or complex"); 8280 } 8281 8282 // Changes the absolute value function to a different type. Preserves whether 8283 // the function is a builtin. 8284 static unsigned changeAbsFunction(unsigned AbsKind, 8285 AbsoluteValueKind ValueKind) { 8286 switch (ValueKind) { 8287 case AVK_Integer: 8288 switch (AbsKind) { 8289 default: 8290 return 0; 8291 case Builtin::BI__builtin_fabsf: 8292 case Builtin::BI__builtin_fabs: 8293 case Builtin::BI__builtin_fabsl: 8294 case Builtin::BI__builtin_cabsf: 8295 case Builtin::BI__builtin_cabs: 8296 case Builtin::BI__builtin_cabsl: 8297 return Builtin::BI__builtin_abs; 8298 case Builtin::BIfabsf: 8299 case Builtin::BIfabs: 8300 case Builtin::BIfabsl: 8301 case Builtin::BIcabsf: 8302 case Builtin::BIcabs: 8303 case Builtin::BIcabsl: 8304 return Builtin::BIabs; 8305 } 8306 case AVK_Floating: 8307 switch (AbsKind) { 8308 default: 8309 return 0; 8310 case Builtin::BI__builtin_abs: 8311 case Builtin::BI__builtin_labs: 8312 case Builtin::BI__builtin_llabs: 8313 case Builtin::BI__builtin_cabsf: 8314 case Builtin::BI__builtin_cabs: 8315 case Builtin::BI__builtin_cabsl: 8316 return Builtin::BI__builtin_fabsf; 8317 case Builtin::BIabs: 8318 case Builtin::BIlabs: 8319 case Builtin::BIllabs: 8320 case Builtin::BIcabsf: 8321 case Builtin::BIcabs: 8322 case Builtin::BIcabsl: 8323 return Builtin::BIfabsf; 8324 } 8325 case AVK_Complex: 8326 switch (AbsKind) { 8327 default: 8328 return 0; 8329 case Builtin::BI__builtin_abs: 8330 case Builtin::BI__builtin_labs: 8331 case Builtin::BI__builtin_llabs: 8332 case Builtin::BI__builtin_fabsf: 8333 case Builtin::BI__builtin_fabs: 8334 case Builtin::BI__builtin_fabsl: 8335 return Builtin::BI__builtin_cabsf; 8336 case Builtin::BIabs: 8337 case Builtin::BIlabs: 8338 case Builtin::BIllabs: 8339 case Builtin::BIfabsf: 8340 case Builtin::BIfabs: 8341 case Builtin::BIfabsl: 8342 return Builtin::BIcabsf; 8343 } 8344 } 8345 llvm_unreachable("Unable to convert function"); 8346 } 8347 8348 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8349 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8350 if (!FnInfo) 8351 return 0; 8352 8353 switch (FDecl->getBuiltinID()) { 8354 default: 8355 return 0; 8356 case Builtin::BI__builtin_abs: 8357 case Builtin::BI__builtin_fabs: 8358 case Builtin::BI__builtin_fabsf: 8359 case Builtin::BI__builtin_fabsl: 8360 case Builtin::BI__builtin_labs: 8361 case Builtin::BI__builtin_llabs: 8362 case Builtin::BI__builtin_cabs: 8363 case Builtin::BI__builtin_cabsf: 8364 case Builtin::BI__builtin_cabsl: 8365 case Builtin::BIabs: 8366 case Builtin::BIlabs: 8367 case Builtin::BIllabs: 8368 case Builtin::BIfabs: 8369 case Builtin::BIfabsf: 8370 case Builtin::BIfabsl: 8371 case Builtin::BIcabs: 8372 case Builtin::BIcabsf: 8373 case Builtin::BIcabsl: 8374 return FDecl->getBuiltinID(); 8375 } 8376 llvm_unreachable("Unknown Builtin type"); 8377 } 8378 8379 // If the replacement is valid, emit a note with replacement function. 8380 // Additionally, suggest including the proper header if not already included. 8381 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8382 unsigned AbsKind, QualType ArgType) { 8383 bool EmitHeaderHint = true; 8384 const char *HeaderName = nullptr; 8385 const char *FunctionName = nullptr; 8386 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8387 FunctionName = "std::abs"; 8388 if (ArgType->isIntegralOrEnumerationType()) { 8389 HeaderName = "cstdlib"; 8390 } else if (ArgType->isRealFloatingType()) { 8391 HeaderName = "cmath"; 8392 } else { 8393 llvm_unreachable("Invalid Type"); 8394 } 8395 8396 // Lookup all std::abs 8397 if (NamespaceDecl *Std = S.getStdNamespace()) { 8398 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8399 R.suppressDiagnostics(); 8400 S.LookupQualifiedName(R, Std); 8401 8402 for (const auto *I : R) { 8403 const FunctionDecl *FDecl = nullptr; 8404 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8405 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8406 } else { 8407 FDecl = dyn_cast<FunctionDecl>(I); 8408 } 8409 if (!FDecl) 8410 continue; 8411 8412 // Found std::abs(), check that they are the right ones. 8413 if (FDecl->getNumParams() != 1) 8414 continue; 8415 8416 // Check that the parameter type can handle the argument. 8417 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8418 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8419 S.Context.getTypeSize(ArgType) <= 8420 S.Context.getTypeSize(ParamType)) { 8421 // Found a function, don't need the header hint. 8422 EmitHeaderHint = false; 8423 break; 8424 } 8425 } 8426 } 8427 } else { 8428 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8429 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8430 8431 if (HeaderName) { 8432 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8433 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8434 R.suppressDiagnostics(); 8435 S.LookupName(R, S.getCurScope()); 8436 8437 if (R.isSingleResult()) { 8438 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8439 if (FD && FD->getBuiltinID() == AbsKind) { 8440 EmitHeaderHint = false; 8441 } else { 8442 return; 8443 } 8444 } else if (!R.empty()) { 8445 return; 8446 } 8447 } 8448 } 8449 8450 S.Diag(Loc, diag::note_replace_abs_function) 8451 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8452 8453 if (!HeaderName) 8454 return; 8455 8456 if (!EmitHeaderHint) 8457 return; 8458 8459 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8460 << FunctionName; 8461 } 8462 8463 template <std::size_t StrLen> 8464 static bool IsStdFunction(const FunctionDecl *FDecl, 8465 const char (&Str)[StrLen]) { 8466 if (!FDecl) 8467 return false; 8468 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8469 return false; 8470 if (!FDecl->isInStdNamespace()) 8471 return false; 8472 8473 return true; 8474 } 8475 8476 // Warn when using the wrong abs() function. 8477 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8478 const FunctionDecl *FDecl) { 8479 if (Call->getNumArgs() != 1) 8480 return; 8481 8482 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8483 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8484 if (AbsKind == 0 && !IsStdAbs) 8485 return; 8486 8487 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8488 QualType ParamType = Call->getArg(0)->getType(); 8489 8490 // Unsigned types cannot be negative. Suggest removing the absolute value 8491 // function call. 8492 if (ArgType->isUnsignedIntegerType()) { 8493 const char *FunctionName = 8494 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8495 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8496 Diag(Call->getExprLoc(), diag::note_remove_abs) 8497 << FunctionName 8498 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8499 return; 8500 } 8501 8502 // Taking the absolute value of a pointer is very suspicious, they probably 8503 // wanted to index into an array, dereference a pointer, call a function, etc. 8504 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8505 unsigned DiagType = 0; 8506 if (ArgType->isFunctionType()) 8507 DiagType = 1; 8508 else if (ArgType->isArrayType()) 8509 DiagType = 2; 8510 8511 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8512 return; 8513 } 8514 8515 // std::abs has overloads which prevent most of the absolute value problems 8516 // from occurring. 8517 if (IsStdAbs) 8518 return; 8519 8520 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8521 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8522 8523 // The argument and parameter are the same kind. Check if they are the right 8524 // size. 8525 if (ArgValueKind == ParamValueKind) { 8526 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8527 return; 8528 8529 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8530 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8531 << FDecl << ArgType << ParamType; 8532 8533 if (NewAbsKind == 0) 8534 return; 8535 8536 emitReplacement(*this, Call->getExprLoc(), 8537 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8538 return; 8539 } 8540 8541 // ArgValueKind != ParamValueKind 8542 // The wrong type of absolute value function was used. Attempt to find the 8543 // proper one. 8544 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8545 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8546 if (NewAbsKind == 0) 8547 return; 8548 8549 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8550 << FDecl << ParamValueKind << ArgValueKind; 8551 8552 emitReplacement(*this, Call->getExprLoc(), 8553 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8554 } 8555 8556 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8557 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8558 const FunctionDecl *FDecl) { 8559 if (!Call || !FDecl) return; 8560 8561 // Ignore template specializations and macros. 8562 if (inTemplateInstantiation()) return; 8563 if (Call->getExprLoc().isMacroID()) return; 8564 8565 // Only care about the one template argument, two function parameter std::max 8566 if (Call->getNumArgs() != 2) return; 8567 if (!IsStdFunction(FDecl, "max")) return; 8568 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8569 if (!ArgList) return; 8570 if (ArgList->size() != 1) return; 8571 8572 // Check that template type argument is unsigned integer. 8573 const auto& TA = ArgList->get(0); 8574 if (TA.getKind() != TemplateArgument::Type) return; 8575 QualType ArgType = TA.getAsType(); 8576 if (!ArgType->isUnsignedIntegerType()) return; 8577 8578 // See if either argument is a literal zero. 8579 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8580 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8581 if (!MTE) return false; 8582 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8583 if (!Num) return false; 8584 if (Num->getValue() != 0) return false; 8585 return true; 8586 }; 8587 8588 const Expr *FirstArg = Call->getArg(0); 8589 const Expr *SecondArg = Call->getArg(1); 8590 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8591 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8592 8593 // Only warn when exactly one argument is zero. 8594 if (IsFirstArgZero == IsSecondArgZero) return; 8595 8596 SourceRange FirstRange = FirstArg->getSourceRange(); 8597 SourceRange SecondRange = SecondArg->getSourceRange(); 8598 8599 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8600 8601 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8602 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8603 8604 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8605 SourceRange RemovalRange; 8606 if (IsFirstArgZero) { 8607 RemovalRange = SourceRange(FirstRange.getBegin(), 8608 SecondRange.getBegin().getLocWithOffset(-1)); 8609 } else { 8610 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8611 SecondRange.getEnd()); 8612 } 8613 8614 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8615 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8616 << FixItHint::CreateRemoval(RemovalRange); 8617 } 8618 8619 //===--- CHECK: Standard memory functions ---------------------------------===// 8620 8621 /// Takes the expression passed to the size_t parameter of functions 8622 /// such as memcmp, strncat, etc and warns if it's a comparison. 8623 /// 8624 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8625 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8626 IdentifierInfo *FnName, 8627 SourceLocation FnLoc, 8628 SourceLocation RParenLoc) { 8629 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8630 if (!Size) 8631 return false; 8632 8633 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8634 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8635 return false; 8636 8637 SourceRange SizeRange = Size->getSourceRange(); 8638 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8639 << SizeRange << FnName; 8640 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8641 << FnName 8642 << FixItHint::CreateInsertion( 8643 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8644 << FixItHint::CreateRemoval(RParenLoc); 8645 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8646 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8647 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8648 ")"); 8649 8650 return true; 8651 } 8652 8653 /// Determine whether the given type is or contains a dynamic class type 8654 /// (e.g., whether it has a vtable). 8655 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8656 bool &IsContained) { 8657 // Look through array types while ignoring qualifiers. 8658 const Type *Ty = T->getBaseElementTypeUnsafe(); 8659 IsContained = false; 8660 8661 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8662 RD = RD ? RD->getDefinition() : nullptr; 8663 if (!RD || RD->isInvalidDecl()) 8664 return nullptr; 8665 8666 if (RD->isDynamicClass()) 8667 return RD; 8668 8669 // Check all the fields. If any bases were dynamic, the class is dynamic. 8670 // It's impossible for a class to transitively contain itself by value, so 8671 // infinite recursion is impossible. 8672 for (auto *FD : RD->fields()) { 8673 bool SubContained; 8674 if (const CXXRecordDecl *ContainedRD = 8675 getContainedDynamicClass(FD->getType(), SubContained)) { 8676 IsContained = true; 8677 return ContainedRD; 8678 } 8679 } 8680 8681 return nullptr; 8682 } 8683 8684 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8685 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8686 if (Unary->getKind() == UETT_SizeOf) 8687 return Unary; 8688 return nullptr; 8689 } 8690 8691 /// If E is a sizeof expression, returns its argument expression, 8692 /// otherwise returns NULL. 8693 static const Expr *getSizeOfExprArg(const Expr *E) { 8694 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8695 if (!SizeOf->isArgumentType()) 8696 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8697 return nullptr; 8698 } 8699 8700 /// If E is a sizeof expression, returns its argument type. 8701 static QualType getSizeOfArgType(const Expr *E) { 8702 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8703 return SizeOf->getTypeOfArgument(); 8704 return QualType(); 8705 } 8706 8707 namespace { 8708 8709 struct SearchNonTrivialToInitializeField 8710 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8711 using Super = 8712 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8713 8714 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8715 8716 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8717 SourceLocation SL) { 8718 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8719 asDerived().visitArray(PDIK, AT, SL); 8720 return; 8721 } 8722 8723 Super::visitWithKind(PDIK, FT, SL); 8724 } 8725 8726 void visitARCStrong(QualType FT, SourceLocation SL) { 8727 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8728 } 8729 void visitARCWeak(QualType FT, SourceLocation SL) { 8730 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8731 } 8732 void visitStruct(QualType FT, SourceLocation SL) { 8733 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8734 visit(FD->getType(), FD->getLocation()); 8735 } 8736 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8737 const ArrayType *AT, SourceLocation SL) { 8738 visit(getContext().getBaseElementType(AT), SL); 8739 } 8740 void visitTrivial(QualType FT, SourceLocation SL) {} 8741 8742 static void diag(QualType RT, const Expr *E, Sema &S) { 8743 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8744 } 8745 8746 ASTContext &getContext() { return S.getASTContext(); } 8747 8748 const Expr *E; 8749 Sema &S; 8750 }; 8751 8752 struct SearchNonTrivialToCopyField 8753 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8754 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8755 8756 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8757 8758 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8759 SourceLocation SL) { 8760 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8761 asDerived().visitArray(PCK, AT, SL); 8762 return; 8763 } 8764 8765 Super::visitWithKind(PCK, FT, SL); 8766 } 8767 8768 void visitARCStrong(QualType FT, SourceLocation SL) { 8769 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8770 } 8771 void visitARCWeak(QualType FT, SourceLocation SL) { 8772 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8773 } 8774 void visitStruct(QualType FT, SourceLocation SL) { 8775 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8776 visit(FD->getType(), FD->getLocation()); 8777 } 8778 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8779 SourceLocation SL) { 8780 visit(getContext().getBaseElementType(AT), SL); 8781 } 8782 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8783 SourceLocation SL) {} 8784 void visitTrivial(QualType FT, SourceLocation SL) {} 8785 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8786 8787 static void diag(QualType RT, const Expr *E, Sema &S) { 8788 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8789 } 8790 8791 ASTContext &getContext() { return S.getASTContext(); } 8792 8793 const Expr *E; 8794 Sema &S; 8795 }; 8796 8797 } 8798 8799 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8800 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8801 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8802 8803 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8804 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8805 return false; 8806 8807 return doesExprLikelyComputeSize(BO->getLHS()) || 8808 doesExprLikelyComputeSize(BO->getRHS()); 8809 } 8810 8811 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8812 } 8813 8814 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8815 /// 8816 /// \code 8817 /// #define MACRO 0 8818 /// foo(MACRO); 8819 /// foo(0); 8820 /// \endcode 8821 /// 8822 /// This should return true for the first call to foo, but not for the second 8823 /// (regardless of whether foo is a macro or function). 8824 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8825 SourceLocation CallLoc, 8826 SourceLocation ArgLoc) { 8827 if (!CallLoc.isMacroID()) 8828 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8829 8830 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8831 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8832 } 8833 8834 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8835 /// last two arguments transposed. 8836 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8837 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8838 return; 8839 8840 const Expr *SizeArg = 8841 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8842 8843 auto isLiteralZero = [](const Expr *E) { 8844 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 8845 }; 8846 8847 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8848 SourceLocation CallLoc = Call->getRParenLoc(); 8849 SourceManager &SM = S.getSourceManager(); 8850 if (isLiteralZero(SizeArg) && 8851 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 8852 8853 SourceLocation DiagLoc = SizeArg->getExprLoc(); 8854 8855 // Some platforms #define bzero to __builtin_memset. See if this is the 8856 // case, and if so, emit a better diagnostic. 8857 if (BId == Builtin::BIbzero || 8858 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 8859 CallLoc, SM, S.getLangOpts()) == "bzero")) { 8860 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 8861 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 8862 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 8863 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 8864 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 8865 } 8866 return; 8867 } 8868 8869 // If the second argument to a memset is a sizeof expression and the third 8870 // isn't, this is also likely an error. This should catch 8871 // 'memset(buf, sizeof(buf), 0xff)'. 8872 if (BId == Builtin::BImemset && 8873 doesExprLikelyComputeSize(Call->getArg(1)) && 8874 !doesExprLikelyComputeSize(Call->getArg(2))) { 8875 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 8876 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 8877 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 8878 return; 8879 } 8880 } 8881 8882 /// Check for dangerous or invalid arguments to memset(). 8883 /// 8884 /// This issues warnings on known problematic, dangerous or unspecified 8885 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 8886 /// function calls. 8887 /// 8888 /// \param Call The call expression to diagnose. 8889 void Sema::CheckMemaccessArguments(const CallExpr *Call, 8890 unsigned BId, 8891 IdentifierInfo *FnName) { 8892 assert(BId != 0); 8893 8894 // It is possible to have a non-standard definition of memset. Validate 8895 // we have enough arguments, and if not, abort further checking. 8896 unsigned ExpectedNumArgs = 8897 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 8898 if (Call->getNumArgs() < ExpectedNumArgs) 8899 return; 8900 8901 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 8902 BId == Builtin::BIstrndup ? 1 : 2); 8903 unsigned LenArg = 8904 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 8905 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 8906 8907 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 8908 Call->getBeginLoc(), Call->getRParenLoc())) 8909 return; 8910 8911 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 8912 CheckMemaccessSize(*this, BId, Call); 8913 8914 // We have special checking when the length is a sizeof expression. 8915 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 8916 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 8917 llvm::FoldingSetNodeID SizeOfArgID; 8918 8919 // Although widely used, 'bzero' is not a standard function. Be more strict 8920 // with the argument types before allowing diagnostics and only allow the 8921 // form bzero(ptr, sizeof(...)). 8922 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8923 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 8924 return; 8925 8926 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 8927 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 8928 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 8929 8930 QualType DestTy = Dest->getType(); 8931 QualType PointeeTy; 8932 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 8933 PointeeTy = DestPtrTy->getPointeeType(); 8934 8935 // Never warn about void type pointers. This can be used to suppress 8936 // false positives. 8937 if (PointeeTy->isVoidType()) 8938 continue; 8939 8940 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 8941 // actually comparing the expressions for equality. Because computing the 8942 // expression IDs can be expensive, we only do this if the diagnostic is 8943 // enabled. 8944 if (SizeOfArg && 8945 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 8946 SizeOfArg->getExprLoc())) { 8947 // We only compute IDs for expressions if the warning is enabled, and 8948 // cache the sizeof arg's ID. 8949 if (SizeOfArgID == llvm::FoldingSetNodeID()) 8950 SizeOfArg->Profile(SizeOfArgID, Context, true); 8951 llvm::FoldingSetNodeID DestID; 8952 Dest->Profile(DestID, Context, true); 8953 if (DestID == SizeOfArgID) { 8954 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 8955 // over sizeof(src) as well. 8956 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 8957 StringRef ReadableName = FnName->getName(); 8958 8959 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 8960 if (UnaryOp->getOpcode() == UO_AddrOf) 8961 ActionIdx = 1; // If its an address-of operator, just remove it. 8962 if (!PointeeTy->isIncompleteType() && 8963 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 8964 ActionIdx = 2; // If the pointee's size is sizeof(char), 8965 // suggest an explicit length. 8966 8967 // If the function is defined as a builtin macro, do not show macro 8968 // expansion. 8969 SourceLocation SL = SizeOfArg->getExprLoc(); 8970 SourceRange DSR = Dest->getSourceRange(); 8971 SourceRange SSR = SizeOfArg->getSourceRange(); 8972 SourceManager &SM = getSourceManager(); 8973 8974 if (SM.isMacroArgExpansion(SL)) { 8975 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 8976 SL = SM.getSpellingLoc(SL); 8977 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 8978 SM.getSpellingLoc(DSR.getEnd())); 8979 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 8980 SM.getSpellingLoc(SSR.getEnd())); 8981 } 8982 8983 DiagRuntimeBehavior(SL, SizeOfArg, 8984 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 8985 << ReadableName 8986 << PointeeTy 8987 << DestTy 8988 << DSR 8989 << SSR); 8990 DiagRuntimeBehavior(SL, SizeOfArg, 8991 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 8992 << ActionIdx 8993 << SSR); 8994 8995 break; 8996 } 8997 } 8998 8999 // Also check for cases where the sizeof argument is the exact same 9000 // type as the memory argument, and where it points to a user-defined 9001 // record type. 9002 if (SizeOfArgTy != QualType()) { 9003 if (PointeeTy->isRecordType() && 9004 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9005 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9006 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9007 << FnName << SizeOfArgTy << ArgIdx 9008 << PointeeTy << Dest->getSourceRange() 9009 << LenExpr->getSourceRange()); 9010 break; 9011 } 9012 } 9013 } else if (DestTy->isArrayType()) { 9014 PointeeTy = DestTy; 9015 } 9016 9017 if (PointeeTy == QualType()) 9018 continue; 9019 9020 // Always complain about dynamic classes. 9021 bool IsContained; 9022 if (const CXXRecordDecl *ContainedRD = 9023 getContainedDynamicClass(PointeeTy, IsContained)) { 9024 9025 unsigned OperationType = 0; 9026 // "overwritten" if we're warning about the destination for any call 9027 // but memcmp; otherwise a verb appropriate to the call. 9028 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 9029 if (BId == Builtin::BImemcpy) 9030 OperationType = 1; 9031 else if(BId == Builtin::BImemmove) 9032 OperationType = 2; 9033 else if (BId == Builtin::BImemcmp) 9034 OperationType = 3; 9035 } 9036 9037 DiagRuntimeBehavior( 9038 Dest->getExprLoc(), Dest, 9039 PDiag(diag::warn_dyn_class_memaccess) 9040 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 9041 << FnName << IsContained << ContainedRD << OperationType 9042 << Call->getCallee()->getSourceRange()); 9043 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9044 BId != Builtin::BImemset) 9045 DiagRuntimeBehavior( 9046 Dest->getExprLoc(), Dest, 9047 PDiag(diag::warn_arc_object_memaccess) 9048 << ArgIdx << FnName << PointeeTy 9049 << Call->getCallee()->getSourceRange()); 9050 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9051 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9052 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9053 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9054 PDiag(diag::warn_cstruct_memaccess) 9055 << ArgIdx << FnName << PointeeTy << 0); 9056 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9057 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9058 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9059 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9060 PDiag(diag::warn_cstruct_memaccess) 9061 << ArgIdx << FnName << PointeeTy << 1); 9062 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9063 } else { 9064 continue; 9065 } 9066 } else 9067 continue; 9068 9069 DiagRuntimeBehavior( 9070 Dest->getExprLoc(), Dest, 9071 PDiag(diag::note_bad_memaccess_silence) 9072 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9073 break; 9074 } 9075 } 9076 9077 // A little helper routine: ignore addition and subtraction of integer literals. 9078 // This intentionally does not ignore all integer constant expressions because 9079 // we don't want to remove sizeof(). 9080 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9081 Ex = Ex->IgnoreParenCasts(); 9082 9083 while (true) { 9084 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9085 if (!BO || !BO->isAdditiveOp()) 9086 break; 9087 9088 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9089 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9090 9091 if (isa<IntegerLiteral>(RHS)) 9092 Ex = LHS; 9093 else if (isa<IntegerLiteral>(LHS)) 9094 Ex = RHS; 9095 else 9096 break; 9097 } 9098 9099 return Ex; 9100 } 9101 9102 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9103 ASTContext &Context) { 9104 // Only handle constant-sized or VLAs, but not flexible members. 9105 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9106 // Only issue the FIXIT for arrays of size > 1. 9107 if (CAT->getSize().getSExtValue() <= 1) 9108 return false; 9109 } else if (!Ty->isVariableArrayType()) { 9110 return false; 9111 } 9112 return true; 9113 } 9114 9115 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9116 // be the size of the source, instead of the destination. 9117 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9118 IdentifierInfo *FnName) { 9119 9120 // Don't crash if the user has the wrong number of arguments 9121 unsigned NumArgs = Call->getNumArgs(); 9122 if ((NumArgs != 3) && (NumArgs != 4)) 9123 return; 9124 9125 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9126 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9127 const Expr *CompareWithSrc = nullptr; 9128 9129 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9130 Call->getBeginLoc(), Call->getRParenLoc())) 9131 return; 9132 9133 // Look for 'strlcpy(dst, x, sizeof(x))' 9134 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9135 CompareWithSrc = Ex; 9136 else { 9137 // Look for 'strlcpy(dst, x, strlen(x))' 9138 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9139 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9140 SizeCall->getNumArgs() == 1) 9141 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9142 } 9143 } 9144 9145 if (!CompareWithSrc) 9146 return; 9147 9148 // Determine if the argument to sizeof/strlen is equal to the source 9149 // argument. In principle there's all kinds of things you could do 9150 // here, for instance creating an == expression and evaluating it with 9151 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9152 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9153 if (!SrcArgDRE) 9154 return; 9155 9156 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9157 if (!CompareWithSrcDRE || 9158 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9159 return; 9160 9161 const Expr *OriginalSizeArg = Call->getArg(2); 9162 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9163 << OriginalSizeArg->getSourceRange() << FnName; 9164 9165 // Output a FIXIT hint if the destination is an array (rather than a 9166 // pointer to an array). This could be enhanced to handle some 9167 // pointers if we know the actual size, like if DstArg is 'array+2' 9168 // we could say 'sizeof(array)-2'. 9169 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9170 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9171 return; 9172 9173 SmallString<128> sizeString; 9174 llvm::raw_svector_ostream OS(sizeString); 9175 OS << "sizeof("; 9176 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9177 OS << ")"; 9178 9179 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9180 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9181 OS.str()); 9182 } 9183 9184 /// Check if two expressions refer to the same declaration. 9185 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9186 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9187 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9188 return D1->getDecl() == D2->getDecl(); 9189 return false; 9190 } 9191 9192 static const Expr *getStrlenExprArg(const Expr *E) { 9193 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9194 const FunctionDecl *FD = CE->getDirectCallee(); 9195 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9196 return nullptr; 9197 return CE->getArg(0)->IgnoreParenCasts(); 9198 } 9199 return nullptr; 9200 } 9201 9202 // Warn on anti-patterns as the 'size' argument to strncat. 9203 // The correct size argument should look like following: 9204 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9205 void Sema::CheckStrncatArguments(const CallExpr *CE, 9206 IdentifierInfo *FnName) { 9207 // Don't crash if the user has the wrong number of arguments. 9208 if (CE->getNumArgs() < 3) 9209 return; 9210 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9211 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9212 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9213 9214 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9215 CE->getRParenLoc())) 9216 return; 9217 9218 // Identify common expressions, which are wrongly used as the size argument 9219 // to strncat and may lead to buffer overflows. 9220 unsigned PatternType = 0; 9221 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9222 // - sizeof(dst) 9223 if (referToTheSameDecl(SizeOfArg, DstArg)) 9224 PatternType = 1; 9225 // - sizeof(src) 9226 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9227 PatternType = 2; 9228 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9229 if (BE->getOpcode() == BO_Sub) { 9230 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9231 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9232 // - sizeof(dst) - strlen(dst) 9233 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9234 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9235 PatternType = 1; 9236 // - sizeof(src) - (anything) 9237 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9238 PatternType = 2; 9239 } 9240 } 9241 9242 if (PatternType == 0) 9243 return; 9244 9245 // Generate the diagnostic. 9246 SourceLocation SL = LenArg->getBeginLoc(); 9247 SourceRange SR = LenArg->getSourceRange(); 9248 SourceManager &SM = getSourceManager(); 9249 9250 // If the function is defined as a builtin macro, do not show macro expansion. 9251 if (SM.isMacroArgExpansion(SL)) { 9252 SL = SM.getSpellingLoc(SL); 9253 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9254 SM.getSpellingLoc(SR.getEnd())); 9255 } 9256 9257 // Check if the destination is an array (rather than a pointer to an array). 9258 QualType DstTy = DstArg->getType(); 9259 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9260 Context); 9261 if (!isKnownSizeArray) { 9262 if (PatternType == 1) 9263 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9264 else 9265 Diag(SL, diag::warn_strncat_src_size) << SR; 9266 return; 9267 } 9268 9269 if (PatternType == 1) 9270 Diag(SL, diag::warn_strncat_large_size) << SR; 9271 else 9272 Diag(SL, diag::warn_strncat_src_size) << SR; 9273 9274 SmallString<128> sizeString; 9275 llvm::raw_svector_ostream OS(sizeString); 9276 OS << "sizeof("; 9277 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9278 OS << ") - "; 9279 OS << "strlen("; 9280 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9281 OS << ") - 1"; 9282 9283 Diag(SL, diag::note_strncat_wrong_size) 9284 << FixItHint::CreateReplacement(SR, OS.str()); 9285 } 9286 9287 void 9288 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9289 SourceLocation ReturnLoc, 9290 bool isObjCMethod, 9291 const AttrVec *Attrs, 9292 const FunctionDecl *FD) { 9293 // Check if the return value is null but should not be. 9294 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9295 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9296 CheckNonNullExpr(*this, RetValExp)) 9297 Diag(ReturnLoc, diag::warn_null_ret) 9298 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9299 9300 // C++11 [basic.stc.dynamic.allocation]p4: 9301 // If an allocation function declared with a non-throwing 9302 // exception-specification fails to allocate storage, it shall return 9303 // a null pointer. Any other allocation function that fails to allocate 9304 // storage shall indicate failure only by throwing an exception [...] 9305 if (FD) { 9306 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9307 if (Op == OO_New || Op == OO_Array_New) { 9308 const FunctionProtoType *Proto 9309 = FD->getType()->castAs<FunctionProtoType>(); 9310 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9311 CheckNonNullExpr(*this, RetValExp)) 9312 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9313 << FD << getLangOpts().CPlusPlus11; 9314 } 9315 } 9316 } 9317 9318 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9319 9320 /// Check for comparisons of floating point operands using != and ==. 9321 /// Issue a warning if these are no self-comparisons, as they are not likely 9322 /// to do what the programmer intended. 9323 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9324 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9325 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9326 9327 // Special case: check for x == x (which is OK). 9328 // Do not emit warnings for such cases. 9329 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9330 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9331 if (DRL->getDecl() == DRR->getDecl()) 9332 return; 9333 9334 // Special case: check for comparisons against literals that can be exactly 9335 // represented by APFloat. In such cases, do not emit a warning. This 9336 // is a heuristic: often comparison against such literals are used to 9337 // detect if a value in a variable has not changed. This clearly can 9338 // lead to false negatives. 9339 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9340 if (FLL->isExact()) 9341 return; 9342 } else 9343 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9344 if (FLR->isExact()) 9345 return; 9346 9347 // Check for comparisons with builtin types. 9348 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9349 if (CL->getBuiltinCallee()) 9350 return; 9351 9352 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9353 if (CR->getBuiltinCallee()) 9354 return; 9355 9356 // Emit the diagnostic. 9357 Diag(Loc, diag::warn_floatingpoint_eq) 9358 << LHS->getSourceRange() << RHS->getSourceRange(); 9359 } 9360 9361 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9362 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9363 9364 namespace { 9365 9366 /// Structure recording the 'active' range of an integer-valued 9367 /// expression. 9368 struct IntRange { 9369 /// The number of bits active in the int. 9370 unsigned Width; 9371 9372 /// True if the int is known not to have negative values. 9373 bool NonNegative; 9374 9375 IntRange(unsigned Width, bool NonNegative) 9376 : Width(Width), NonNegative(NonNegative) {} 9377 9378 /// Returns the range of the bool type. 9379 static IntRange forBoolType() { 9380 return IntRange(1, true); 9381 } 9382 9383 /// Returns the range of an opaque value of the given integral type. 9384 static IntRange forValueOfType(ASTContext &C, QualType T) { 9385 return forValueOfCanonicalType(C, 9386 T->getCanonicalTypeInternal().getTypePtr()); 9387 } 9388 9389 /// Returns the range of an opaque value of a canonical integral type. 9390 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9391 assert(T->isCanonicalUnqualified()); 9392 9393 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9394 T = VT->getElementType().getTypePtr(); 9395 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9396 T = CT->getElementType().getTypePtr(); 9397 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9398 T = AT->getValueType().getTypePtr(); 9399 9400 if (!C.getLangOpts().CPlusPlus) { 9401 // For enum types in C code, use the underlying datatype. 9402 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9403 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9404 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9405 // For enum types in C++, use the known bit width of the enumerators. 9406 EnumDecl *Enum = ET->getDecl(); 9407 // In C++11, enums can have a fixed underlying type. Use this type to 9408 // compute the range. 9409 if (Enum->isFixed()) { 9410 return IntRange(C.getIntWidth(QualType(T, 0)), 9411 !ET->isSignedIntegerOrEnumerationType()); 9412 } 9413 9414 unsigned NumPositive = Enum->getNumPositiveBits(); 9415 unsigned NumNegative = Enum->getNumNegativeBits(); 9416 9417 if (NumNegative == 0) 9418 return IntRange(NumPositive, true/*NonNegative*/); 9419 else 9420 return IntRange(std::max(NumPositive + 1, NumNegative), 9421 false/*NonNegative*/); 9422 } 9423 9424 const BuiltinType *BT = cast<BuiltinType>(T); 9425 assert(BT->isInteger()); 9426 9427 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9428 } 9429 9430 /// Returns the "target" range of a canonical integral type, i.e. 9431 /// the range of values expressible in the type. 9432 /// 9433 /// This matches forValueOfCanonicalType except that enums have the 9434 /// full range of their type, not the range of their enumerators. 9435 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9436 assert(T->isCanonicalUnqualified()); 9437 9438 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9439 T = VT->getElementType().getTypePtr(); 9440 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9441 T = CT->getElementType().getTypePtr(); 9442 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9443 T = AT->getValueType().getTypePtr(); 9444 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9445 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9446 9447 const BuiltinType *BT = cast<BuiltinType>(T); 9448 assert(BT->isInteger()); 9449 9450 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9451 } 9452 9453 /// Returns the supremum of two ranges: i.e. their conservative merge. 9454 static IntRange join(IntRange L, IntRange R) { 9455 return IntRange(std::max(L.Width, R.Width), 9456 L.NonNegative && R.NonNegative); 9457 } 9458 9459 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9460 static IntRange meet(IntRange L, IntRange R) { 9461 return IntRange(std::min(L.Width, R.Width), 9462 L.NonNegative || R.NonNegative); 9463 } 9464 }; 9465 9466 } // namespace 9467 9468 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9469 unsigned MaxWidth) { 9470 if (value.isSigned() && value.isNegative()) 9471 return IntRange(value.getMinSignedBits(), false); 9472 9473 if (value.getBitWidth() > MaxWidth) 9474 value = value.trunc(MaxWidth); 9475 9476 // isNonNegative() just checks the sign bit without considering 9477 // signedness. 9478 return IntRange(value.getActiveBits(), true); 9479 } 9480 9481 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9482 unsigned MaxWidth) { 9483 if (result.isInt()) 9484 return GetValueRange(C, result.getInt(), MaxWidth); 9485 9486 if (result.isVector()) { 9487 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9488 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9489 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9490 R = IntRange::join(R, El); 9491 } 9492 return R; 9493 } 9494 9495 if (result.isComplexInt()) { 9496 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9497 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9498 return IntRange::join(R, I); 9499 } 9500 9501 // This can happen with lossless casts to intptr_t of "based" lvalues. 9502 // Assume it might use arbitrary bits. 9503 // FIXME: The only reason we need to pass the type in here is to get 9504 // the sign right on this one case. It would be nice if APValue 9505 // preserved this. 9506 assert(result.isLValue() || result.isAddrLabelDiff()); 9507 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9508 } 9509 9510 static QualType GetExprType(const Expr *E) { 9511 QualType Ty = E->getType(); 9512 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9513 Ty = AtomicRHS->getValueType(); 9514 return Ty; 9515 } 9516 9517 /// Pseudo-evaluate the given integer expression, estimating the 9518 /// range of values it might take. 9519 /// 9520 /// \param MaxWidth - the width to which the value will be truncated 9521 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9522 E = E->IgnoreParens(); 9523 9524 // Try a full evaluation first. 9525 Expr::EvalResult result; 9526 if (E->EvaluateAsRValue(result, C)) 9527 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9528 9529 // I think we only want to look through implicit casts here; if the 9530 // user has an explicit widening cast, we should treat the value as 9531 // being of the new, wider type. 9532 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9533 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9534 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9535 9536 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9537 9538 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9539 CE->getCastKind() == CK_BooleanToSignedIntegral; 9540 9541 // Assume that non-integer casts can span the full range of the type. 9542 if (!isIntegerCast) 9543 return OutputTypeRange; 9544 9545 IntRange SubRange 9546 = GetExprRange(C, CE->getSubExpr(), 9547 std::min(MaxWidth, OutputTypeRange.Width)); 9548 9549 // Bail out if the subexpr's range is as wide as the cast type. 9550 if (SubRange.Width >= OutputTypeRange.Width) 9551 return OutputTypeRange; 9552 9553 // Otherwise, we take the smaller width, and we're non-negative if 9554 // either the output type or the subexpr is. 9555 return IntRange(SubRange.Width, 9556 SubRange.NonNegative || OutputTypeRange.NonNegative); 9557 } 9558 9559 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9560 // If we can fold the condition, just take that operand. 9561 bool CondResult; 9562 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9563 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9564 : CO->getFalseExpr(), 9565 MaxWidth); 9566 9567 // Otherwise, conservatively merge. 9568 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9569 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9570 return IntRange::join(L, R); 9571 } 9572 9573 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9574 switch (BO->getOpcode()) { 9575 case BO_Cmp: 9576 llvm_unreachable("builtin <=> should have class type"); 9577 9578 // Boolean-valued operations are single-bit and positive. 9579 case BO_LAnd: 9580 case BO_LOr: 9581 case BO_LT: 9582 case BO_GT: 9583 case BO_LE: 9584 case BO_GE: 9585 case BO_EQ: 9586 case BO_NE: 9587 return IntRange::forBoolType(); 9588 9589 // The type of the assignments is the type of the LHS, so the RHS 9590 // is not necessarily the same type. 9591 case BO_MulAssign: 9592 case BO_DivAssign: 9593 case BO_RemAssign: 9594 case BO_AddAssign: 9595 case BO_SubAssign: 9596 case BO_XorAssign: 9597 case BO_OrAssign: 9598 // TODO: bitfields? 9599 return IntRange::forValueOfType(C, GetExprType(E)); 9600 9601 // Simple assignments just pass through the RHS, which will have 9602 // been coerced to the LHS type. 9603 case BO_Assign: 9604 // TODO: bitfields? 9605 return GetExprRange(C, BO->getRHS(), MaxWidth); 9606 9607 // Operations with opaque sources are black-listed. 9608 case BO_PtrMemD: 9609 case BO_PtrMemI: 9610 return IntRange::forValueOfType(C, GetExprType(E)); 9611 9612 // Bitwise-and uses the *infinum* of the two source ranges. 9613 case BO_And: 9614 case BO_AndAssign: 9615 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9616 GetExprRange(C, BO->getRHS(), MaxWidth)); 9617 9618 // Left shift gets black-listed based on a judgement call. 9619 case BO_Shl: 9620 // ...except that we want to treat '1 << (blah)' as logically 9621 // positive. It's an important idiom. 9622 if (IntegerLiteral *I 9623 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9624 if (I->getValue() == 1) { 9625 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9626 return IntRange(R.Width, /*NonNegative*/ true); 9627 } 9628 } 9629 LLVM_FALLTHROUGH; 9630 9631 case BO_ShlAssign: 9632 return IntRange::forValueOfType(C, GetExprType(E)); 9633 9634 // Right shift by a constant can narrow its left argument. 9635 case BO_Shr: 9636 case BO_ShrAssign: { 9637 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9638 9639 // If the shift amount is a positive constant, drop the width by 9640 // that much. 9641 llvm::APSInt shift; 9642 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9643 shift.isNonNegative()) { 9644 unsigned zext = shift.getZExtValue(); 9645 if (zext >= L.Width) 9646 L.Width = (L.NonNegative ? 0 : 1); 9647 else 9648 L.Width -= zext; 9649 } 9650 9651 return L; 9652 } 9653 9654 // Comma acts as its right operand. 9655 case BO_Comma: 9656 return GetExprRange(C, BO->getRHS(), MaxWidth); 9657 9658 // Black-list pointer subtractions. 9659 case BO_Sub: 9660 if (BO->getLHS()->getType()->isPointerType()) 9661 return IntRange::forValueOfType(C, GetExprType(E)); 9662 break; 9663 9664 // The width of a division result is mostly determined by the size 9665 // of the LHS. 9666 case BO_Div: { 9667 // Don't 'pre-truncate' the operands. 9668 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9669 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9670 9671 // If the divisor is constant, use that. 9672 llvm::APSInt divisor; 9673 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9674 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9675 if (log2 >= L.Width) 9676 L.Width = (L.NonNegative ? 0 : 1); 9677 else 9678 L.Width = std::min(L.Width - log2, MaxWidth); 9679 return L; 9680 } 9681 9682 // Otherwise, just use the LHS's width. 9683 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9684 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9685 } 9686 9687 // The result of a remainder can't be larger than the result of 9688 // either side. 9689 case BO_Rem: { 9690 // Don't 'pre-truncate' the operands. 9691 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9692 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9693 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9694 9695 IntRange meet = IntRange::meet(L, R); 9696 meet.Width = std::min(meet.Width, MaxWidth); 9697 return meet; 9698 } 9699 9700 // The default behavior is okay for these. 9701 case BO_Mul: 9702 case BO_Add: 9703 case BO_Xor: 9704 case BO_Or: 9705 break; 9706 } 9707 9708 // The default case is to treat the operation as if it were closed 9709 // on the narrowest type that encompasses both operands. 9710 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9711 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9712 return IntRange::join(L, R); 9713 } 9714 9715 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9716 switch (UO->getOpcode()) { 9717 // Boolean-valued operations are white-listed. 9718 case UO_LNot: 9719 return IntRange::forBoolType(); 9720 9721 // Operations with opaque sources are black-listed. 9722 case UO_Deref: 9723 case UO_AddrOf: // should be impossible 9724 return IntRange::forValueOfType(C, GetExprType(E)); 9725 9726 default: 9727 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9728 } 9729 } 9730 9731 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9732 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9733 9734 if (const auto *BitField = E->getSourceBitField()) 9735 return IntRange(BitField->getBitWidthValue(C), 9736 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9737 9738 return IntRange::forValueOfType(C, GetExprType(E)); 9739 } 9740 9741 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9742 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9743 } 9744 9745 /// Checks whether the given value, which currently has the given 9746 /// source semantics, has the same value when coerced through the 9747 /// target semantics. 9748 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9749 const llvm::fltSemantics &Src, 9750 const llvm::fltSemantics &Tgt) { 9751 llvm::APFloat truncated = value; 9752 9753 bool ignored; 9754 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9755 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9756 9757 return truncated.bitwiseIsEqual(value); 9758 } 9759 9760 /// Checks whether the given value, which currently has the given 9761 /// source semantics, has the same value when coerced through the 9762 /// target semantics. 9763 /// 9764 /// The value might be a vector of floats (or a complex number). 9765 static bool IsSameFloatAfterCast(const APValue &value, 9766 const llvm::fltSemantics &Src, 9767 const llvm::fltSemantics &Tgt) { 9768 if (value.isFloat()) 9769 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9770 9771 if (value.isVector()) { 9772 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9773 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9774 return false; 9775 return true; 9776 } 9777 9778 assert(value.isComplexFloat()); 9779 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9780 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9781 } 9782 9783 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9784 9785 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9786 // Suppress cases where we are comparing against an enum constant. 9787 if (const DeclRefExpr *DR = 9788 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9789 if (isa<EnumConstantDecl>(DR->getDecl())) 9790 return true; 9791 9792 // Suppress cases where the '0' value is expanded from a macro. 9793 if (E->getBeginLoc().isMacroID()) 9794 return true; 9795 9796 return false; 9797 } 9798 9799 static bool isKnownToHaveUnsignedValue(Expr *E) { 9800 return E->getType()->isIntegerType() && 9801 (!E->getType()->isSignedIntegerType() || 9802 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9803 } 9804 9805 namespace { 9806 /// The promoted range of values of a type. In general this has the 9807 /// following structure: 9808 /// 9809 /// |-----------| . . . |-----------| 9810 /// ^ ^ ^ ^ 9811 /// Min HoleMin HoleMax Max 9812 /// 9813 /// ... where there is only a hole if a signed type is promoted to unsigned 9814 /// (in which case Min and Max are the smallest and largest representable 9815 /// values). 9816 struct PromotedRange { 9817 // Min, or HoleMax if there is a hole. 9818 llvm::APSInt PromotedMin; 9819 // Max, or HoleMin if there is a hole. 9820 llvm::APSInt PromotedMax; 9821 9822 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9823 if (R.Width == 0) 9824 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9825 else if (R.Width >= BitWidth && !Unsigned) { 9826 // Promotion made the type *narrower*. This happens when promoting 9827 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9828 // Treat all values of 'signed int' as being in range for now. 9829 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9830 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9831 } else { 9832 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9833 .extOrTrunc(BitWidth); 9834 PromotedMin.setIsUnsigned(Unsigned); 9835 9836 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9837 .extOrTrunc(BitWidth); 9838 PromotedMax.setIsUnsigned(Unsigned); 9839 } 9840 } 9841 9842 // Determine whether this range is contiguous (has no hole). 9843 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9844 9845 // Where a constant value is within the range. 9846 enum ComparisonResult { 9847 LT = 0x1, 9848 LE = 0x2, 9849 GT = 0x4, 9850 GE = 0x8, 9851 EQ = 0x10, 9852 NE = 0x20, 9853 InRangeFlag = 0x40, 9854 9855 Less = LE | LT | NE, 9856 Min = LE | InRangeFlag, 9857 InRange = InRangeFlag, 9858 Max = GE | InRangeFlag, 9859 Greater = GE | GT | NE, 9860 9861 OnlyValue = LE | GE | EQ | InRangeFlag, 9862 InHole = NE 9863 }; 9864 9865 ComparisonResult compare(const llvm::APSInt &Value) const { 9866 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9867 Value.isUnsigned() == PromotedMin.isUnsigned()); 9868 if (!isContiguous()) { 9869 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9870 if (Value.isMinValue()) return Min; 9871 if (Value.isMaxValue()) return Max; 9872 if (Value >= PromotedMin) return InRange; 9873 if (Value <= PromotedMax) return InRange; 9874 return InHole; 9875 } 9876 9877 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9878 case -1: return Less; 9879 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9880 case 1: 9881 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9882 case -1: return InRange; 9883 case 0: return Max; 9884 case 1: return Greater; 9885 } 9886 } 9887 9888 llvm_unreachable("impossible compare result"); 9889 } 9890 9891 static llvm::Optional<StringRef> 9892 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9893 if (Op == BO_Cmp) { 9894 ComparisonResult LTFlag = LT, GTFlag = GT; 9895 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9896 9897 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9898 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9899 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9900 return llvm::None; 9901 } 9902 9903 ComparisonResult TrueFlag, FalseFlag; 9904 if (Op == BO_EQ) { 9905 TrueFlag = EQ; 9906 FalseFlag = NE; 9907 } else if (Op == BO_NE) { 9908 TrueFlag = NE; 9909 FalseFlag = EQ; 9910 } else { 9911 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9912 TrueFlag = LT; 9913 FalseFlag = GE; 9914 } else { 9915 TrueFlag = GT; 9916 FalseFlag = LE; 9917 } 9918 if (Op == BO_GE || Op == BO_LE) 9919 std::swap(TrueFlag, FalseFlag); 9920 } 9921 if (R & TrueFlag) 9922 return StringRef("true"); 9923 if (R & FalseFlag) 9924 return StringRef("false"); 9925 return llvm::None; 9926 } 9927 }; 9928 } 9929 9930 static bool HasEnumType(Expr *E) { 9931 // Strip off implicit integral promotions. 9932 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9933 if (ICE->getCastKind() != CK_IntegralCast && 9934 ICE->getCastKind() != CK_NoOp) 9935 break; 9936 E = ICE->getSubExpr(); 9937 } 9938 9939 return E->getType()->isEnumeralType(); 9940 } 9941 9942 static int classifyConstantValue(Expr *Constant) { 9943 // The values of this enumeration are used in the diagnostics 9944 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9945 enum ConstantValueKind { 9946 Miscellaneous = 0, 9947 LiteralTrue, 9948 LiteralFalse 9949 }; 9950 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9951 return BL->getValue() ? ConstantValueKind::LiteralTrue 9952 : ConstantValueKind::LiteralFalse; 9953 return ConstantValueKind::Miscellaneous; 9954 } 9955 9956 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9957 Expr *Constant, Expr *Other, 9958 const llvm::APSInt &Value, 9959 bool RhsConstant) { 9960 if (S.inTemplateInstantiation()) 9961 return false; 9962 9963 Expr *OriginalOther = Other; 9964 9965 Constant = Constant->IgnoreParenImpCasts(); 9966 Other = Other->IgnoreParenImpCasts(); 9967 9968 // Suppress warnings on tautological comparisons between values of the same 9969 // enumeration type. There are only two ways we could warn on this: 9970 // - If the constant is outside the range of representable values of 9971 // the enumeration. In such a case, we should warn about the cast 9972 // to enumeration type, not about the comparison. 9973 // - If the constant is the maximum / minimum in-range value. For an 9974 // enumeratin type, such comparisons can be meaningful and useful. 9975 if (Constant->getType()->isEnumeralType() && 9976 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9977 return false; 9978 9979 // TODO: Investigate using GetExprRange() to get tighter bounds 9980 // on the bit ranges. 9981 QualType OtherT = Other->getType(); 9982 if (const auto *AT = OtherT->getAs<AtomicType>()) 9983 OtherT = AT->getValueType(); 9984 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9985 9986 // Whether we're treating Other as being a bool because of the form of 9987 // expression despite it having another type (typically 'int' in C). 9988 bool OtherIsBooleanDespiteType = 9989 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9990 if (OtherIsBooleanDespiteType) 9991 OtherRange = IntRange::forBoolType(); 9992 9993 // Determine the promoted range of the other type and see if a comparison of 9994 // the constant against that range is tautological. 9995 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9996 Value.isUnsigned()); 9997 auto Cmp = OtherPromotedRange.compare(Value); 9998 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9999 if (!Result) 10000 return false; 10001 10002 // Suppress the diagnostic for an in-range comparison if the constant comes 10003 // from a macro or enumerator. We don't want to diagnose 10004 // 10005 // some_long_value <= INT_MAX 10006 // 10007 // when sizeof(int) == sizeof(long). 10008 bool InRange = Cmp & PromotedRange::InRangeFlag; 10009 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10010 return false; 10011 10012 // If this is a comparison to an enum constant, include that 10013 // constant in the diagnostic. 10014 const EnumConstantDecl *ED = nullptr; 10015 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10016 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10017 10018 // Should be enough for uint128 (39 decimal digits) 10019 SmallString<64> PrettySourceValue; 10020 llvm::raw_svector_ostream OS(PrettySourceValue); 10021 if (ED) 10022 OS << '\'' << *ED << "' (" << Value << ")"; 10023 else 10024 OS << Value; 10025 10026 // FIXME: We use a somewhat different formatting for the in-range cases and 10027 // cases involving boolean values for historical reasons. We should pick a 10028 // consistent way of presenting these diagnostics. 10029 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10030 S.DiagRuntimeBehavior( 10031 E->getOperatorLoc(), E, 10032 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10033 : diag::warn_tautological_bool_compare) 10034 << OS.str() << classifyConstantValue(Constant) 10035 << OtherT << OtherIsBooleanDespiteType << *Result 10036 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10037 } else { 10038 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10039 ? (HasEnumType(OriginalOther) 10040 ? diag::warn_unsigned_enum_always_true_comparison 10041 : diag::warn_unsigned_always_true_comparison) 10042 : diag::warn_tautological_constant_compare; 10043 10044 S.Diag(E->getOperatorLoc(), Diag) 10045 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10046 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10047 } 10048 10049 return true; 10050 } 10051 10052 /// Analyze the operands of the given comparison. Implements the 10053 /// fallback case from AnalyzeComparison. 10054 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10055 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10056 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10057 } 10058 10059 /// Implements -Wsign-compare. 10060 /// 10061 /// \param E the binary operator to check for warnings 10062 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10063 // The type the comparison is being performed in. 10064 QualType T = E->getLHS()->getType(); 10065 10066 // Only analyze comparison operators where both sides have been converted to 10067 // the same type. 10068 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10069 return AnalyzeImpConvsInComparison(S, E); 10070 10071 // Don't analyze value-dependent comparisons directly. 10072 if (E->isValueDependent()) 10073 return AnalyzeImpConvsInComparison(S, E); 10074 10075 Expr *LHS = E->getLHS(); 10076 Expr *RHS = E->getRHS(); 10077 10078 if (T->isIntegralType(S.Context)) { 10079 llvm::APSInt RHSValue; 10080 llvm::APSInt LHSValue; 10081 10082 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10083 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10084 10085 // We don't care about expressions whose result is a constant. 10086 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10087 return AnalyzeImpConvsInComparison(S, E); 10088 10089 // We only care about expressions where just one side is literal 10090 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10091 // Is the constant on the RHS or LHS? 10092 const bool RhsConstant = IsRHSIntegralLiteral; 10093 Expr *Const = RhsConstant ? RHS : LHS; 10094 Expr *Other = RhsConstant ? LHS : RHS; 10095 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10096 10097 // Check whether an integer constant comparison results in a value 10098 // of 'true' or 'false'. 10099 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10100 return AnalyzeImpConvsInComparison(S, E); 10101 } 10102 } 10103 10104 if (!T->hasUnsignedIntegerRepresentation()) { 10105 // We don't do anything special if this isn't an unsigned integral 10106 // comparison: we're only interested in integral comparisons, and 10107 // signed comparisons only happen in cases we don't care to warn about. 10108 return AnalyzeImpConvsInComparison(S, E); 10109 } 10110 10111 LHS = LHS->IgnoreParenImpCasts(); 10112 RHS = RHS->IgnoreParenImpCasts(); 10113 10114 if (!S.getLangOpts().CPlusPlus) { 10115 // Avoid warning about comparison of integers with different signs when 10116 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10117 // the type of `E`. 10118 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10119 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10120 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10121 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10122 } 10123 10124 // Check to see if one of the (unmodified) operands is of different 10125 // signedness. 10126 Expr *signedOperand, *unsignedOperand; 10127 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10128 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10129 "unsigned comparison between two signed integer expressions?"); 10130 signedOperand = LHS; 10131 unsignedOperand = RHS; 10132 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10133 signedOperand = RHS; 10134 unsignedOperand = LHS; 10135 } else { 10136 return AnalyzeImpConvsInComparison(S, E); 10137 } 10138 10139 // Otherwise, calculate the effective range of the signed operand. 10140 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10141 10142 // Go ahead and analyze implicit conversions in the operands. Note 10143 // that we skip the implicit conversions on both sides. 10144 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10145 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10146 10147 // If the signed range is non-negative, -Wsign-compare won't fire. 10148 if (signedRange.NonNegative) 10149 return; 10150 10151 // For (in)equality comparisons, if the unsigned operand is a 10152 // constant which cannot collide with a overflowed signed operand, 10153 // then reinterpreting the signed operand as unsigned will not 10154 // change the result of the comparison. 10155 if (E->isEqualityOp()) { 10156 unsigned comparisonWidth = S.Context.getIntWidth(T); 10157 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10158 10159 // We should never be unable to prove that the unsigned operand is 10160 // non-negative. 10161 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10162 10163 if (unsignedRange.Width < comparisonWidth) 10164 return; 10165 } 10166 10167 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10168 S.PDiag(diag::warn_mixed_sign_comparison) 10169 << LHS->getType() << RHS->getType() 10170 << LHS->getSourceRange() << RHS->getSourceRange()); 10171 } 10172 10173 /// Analyzes an attempt to assign the given value to a bitfield. 10174 /// 10175 /// Returns true if there was something fishy about the attempt. 10176 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10177 SourceLocation InitLoc) { 10178 assert(Bitfield->isBitField()); 10179 if (Bitfield->isInvalidDecl()) 10180 return false; 10181 10182 // White-list bool bitfields. 10183 QualType BitfieldType = Bitfield->getType(); 10184 if (BitfieldType->isBooleanType()) 10185 return false; 10186 10187 if (BitfieldType->isEnumeralType()) { 10188 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10189 // If the underlying enum type was not explicitly specified as an unsigned 10190 // type and the enum contain only positive values, MSVC++ will cause an 10191 // inconsistency by storing this as a signed type. 10192 if (S.getLangOpts().CPlusPlus11 && 10193 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10194 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10195 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10196 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10197 << BitfieldEnumDecl->getNameAsString(); 10198 } 10199 } 10200 10201 if (Bitfield->getType()->isBooleanType()) 10202 return false; 10203 10204 // Ignore value- or type-dependent expressions. 10205 if (Bitfield->getBitWidth()->isValueDependent() || 10206 Bitfield->getBitWidth()->isTypeDependent() || 10207 Init->isValueDependent() || 10208 Init->isTypeDependent()) 10209 return false; 10210 10211 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10212 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10213 10214 llvm::APSInt Value; 10215 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 10216 Expr::SE_AllowSideEffects)) { 10217 // The RHS is not constant. If the RHS has an enum type, make sure the 10218 // bitfield is wide enough to hold all the values of the enum without 10219 // truncation. 10220 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10221 EnumDecl *ED = EnumTy->getDecl(); 10222 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10223 10224 // Enum types are implicitly signed on Windows, so check if there are any 10225 // negative enumerators to see if the enum was intended to be signed or 10226 // not. 10227 bool SignedEnum = ED->getNumNegativeBits() > 0; 10228 10229 // Check for surprising sign changes when assigning enum values to a 10230 // bitfield of different signedness. If the bitfield is signed and we 10231 // have exactly the right number of bits to store this unsigned enum, 10232 // suggest changing the enum to an unsigned type. This typically happens 10233 // on Windows where unfixed enums always use an underlying type of 'int'. 10234 unsigned DiagID = 0; 10235 if (SignedEnum && !SignedBitfield) { 10236 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10237 } else if (SignedBitfield && !SignedEnum && 10238 ED->getNumPositiveBits() == FieldWidth) { 10239 DiagID = diag::warn_signed_bitfield_enum_conversion; 10240 } 10241 10242 if (DiagID) { 10243 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10244 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10245 SourceRange TypeRange = 10246 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10247 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10248 << SignedEnum << TypeRange; 10249 } 10250 10251 // Compute the required bitwidth. If the enum has negative values, we need 10252 // one more bit than the normal number of positive bits to represent the 10253 // sign bit. 10254 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10255 ED->getNumNegativeBits()) 10256 : ED->getNumPositiveBits(); 10257 10258 // Check the bitwidth. 10259 if (BitsNeeded > FieldWidth) { 10260 Expr *WidthExpr = Bitfield->getBitWidth(); 10261 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10262 << Bitfield << ED; 10263 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10264 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10265 } 10266 } 10267 10268 return false; 10269 } 10270 10271 unsigned OriginalWidth = Value.getBitWidth(); 10272 10273 if (!Value.isSigned() || Value.isNegative()) 10274 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10275 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10276 OriginalWidth = Value.getMinSignedBits(); 10277 10278 if (OriginalWidth <= FieldWidth) 10279 return false; 10280 10281 // Compute the value which the bitfield will contain. 10282 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10283 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10284 10285 // Check whether the stored value is equal to the original value. 10286 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10287 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10288 return false; 10289 10290 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10291 // therefore don't strictly fit into a signed bitfield of width 1. 10292 if (FieldWidth == 1 && Value == 1) 10293 return false; 10294 10295 std::string PrettyValue = Value.toString(10); 10296 std::string PrettyTrunc = TruncatedValue.toString(10); 10297 10298 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10299 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10300 << Init->getSourceRange(); 10301 10302 return true; 10303 } 10304 10305 /// Analyze the given simple or compound assignment for warning-worthy 10306 /// operations. 10307 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10308 // Just recurse on the LHS. 10309 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10310 10311 // We want to recurse on the RHS as normal unless we're assigning to 10312 // a bitfield. 10313 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10314 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10315 E->getOperatorLoc())) { 10316 // Recurse, ignoring any implicit conversions on the RHS. 10317 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10318 E->getOperatorLoc()); 10319 } 10320 } 10321 10322 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10323 10324 // Diagnose implicitly sequentially-consistent atomic assignment. 10325 if (E->getLHS()->getType()->isAtomicType()) 10326 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10327 } 10328 10329 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10330 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10331 SourceLocation CContext, unsigned diag, 10332 bool pruneControlFlow = false) { 10333 if (pruneControlFlow) { 10334 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10335 S.PDiag(diag) 10336 << SourceType << T << E->getSourceRange() 10337 << SourceRange(CContext)); 10338 return; 10339 } 10340 S.Diag(E->getExprLoc(), diag) 10341 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10342 } 10343 10344 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10345 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10346 SourceLocation CContext, 10347 unsigned diag, bool pruneControlFlow = false) { 10348 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10349 } 10350 10351 /// Diagnose an implicit cast from a floating point value to an integer value. 10352 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10353 SourceLocation CContext) { 10354 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10355 const bool PruneWarnings = S.inTemplateInstantiation(); 10356 10357 Expr *InnerE = E->IgnoreParenImpCasts(); 10358 // We also want to warn on, e.g., "int i = -1.234" 10359 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10360 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10361 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10362 10363 const bool IsLiteral = 10364 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10365 10366 llvm::APFloat Value(0.0); 10367 bool IsConstant = 10368 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10369 if (!IsConstant) { 10370 return DiagnoseImpCast(S, E, T, CContext, 10371 diag::warn_impcast_float_integer, PruneWarnings); 10372 } 10373 10374 bool isExact = false; 10375 10376 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10377 T->hasUnsignedIntegerRepresentation()); 10378 llvm::APFloat::opStatus Result = Value.convertToInteger( 10379 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10380 10381 if (Result == llvm::APFloat::opOK && isExact) { 10382 if (IsLiteral) return; 10383 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10384 PruneWarnings); 10385 } 10386 10387 // Conversion of a floating-point value to a non-bool integer where the 10388 // integral part cannot be represented by the integer type is undefined. 10389 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10390 return DiagnoseImpCast( 10391 S, E, T, CContext, 10392 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10393 : diag::warn_impcast_float_to_integer_out_of_range, 10394 PruneWarnings); 10395 10396 unsigned DiagID = 0; 10397 if (IsLiteral) { 10398 // Warn on floating point literal to integer. 10399 DiagID = diag::warn_impcast_literal_float_to_integer; 10400 } else if (IntegerValue == 0) { 10401 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10402 return DiagnoseImpCast(S, E, T, CContext, 10403 diag::warn_impcast_float_integer, PruneWarnings); 10404 } 10405 // Warn on non-zero to zero conversion. 10406 DiagID = diag::warn_impcast_float_to_integer_zero; 10407 } else { 10408 if (IntegerValue.isUnsigned()) { 10409 if (!IntegerValue.isMaxValue()) { 10410 return DiagnoseImpCast(S, E, T, CContext, 10411 diag::warn_impcast_float_integer, PruneWarnings); 10412 } 10413 } else { // IntegerValue.isSigned() 10414 if (!IntegerValue.isMaxSignedValue() && 10415 !IntegerValue.isMinSignedValue()) { 10416 return DiagnoseImpCast(S, E, T, CContext, 10417 diag::warn_impcast_float_integer, PruneWarnings); 10418 } 10419 } 10420 // Warn on evaluatable floating point expression to integer conversion. 10421 DiagID = diag::warn_impcast_float_to_integer; 10422 } 10423 10424 // FIXME: Force the precision of the source value down so we don't print 10425 // digits which are usually useless (we don't really care here if we 10426 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10427 // would automatically print the shortest representation, but it's a bit 10428 // tricky to implement. 10429 SmallString<16> PrettySourceValue; 10430 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10431 precision = (precision * 59 + 195) / 196; 10432 Value.toString(PrettySourceValue, precision); 10433 10434 SmallString<16> PrettyTargetValue; 10435 if (IsBool) 10436 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10437 else 10438 IntegerValue.toString(PrettyTargetValue); 10439 10440 if (PruneWarnings) { 10441 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10442 S.PDiag(DiagID) 10443 << E->getType() << T.getUnqualifiedType() 10444 << PrettySourceValue << PrettyTargetValue 10445 << E->getSourceRange() << SourceRange(CContext)); 10446 } else { 10447 S.Diag(E->getExprLoc(), DiagID) 10448 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10449 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10450 } 10451 } 10452 10453 /// Analyze the given compound assignment for the possible losing of 10454 /// floating-point precision. 10455 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10456 assert(isa<CompoundAssignOperator>(E) && 10457 "Must be compound assignment operation"); 10458 // Recurse on the LHS and RHS in here 10459 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10460 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10461 10462 if (E->getLHS()->getType()->isAtomicType()) 10463 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10464 10465 // Now check the outermost expression 10466 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10467 const auto *RBT = cast<CompoundAssignOperator>(E) 10468 ->getComputationResultType() 10469 ->getAs<BuiltinType>(); 10470 10471 // The below checks assume source is floating point. 10472 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10473 10474 // If source is floating point but target is not. 10475 if (!ResultBT->isFloatingPoint()) 10476 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(), 10477 E->getExprLoc()); 10478 10479 // If both source and target are floating points. 10480 // Builtin FP kinds are ordered by increasing FP rank. 10481 if (ResultBT->getKind() < RBT->getKind() && 10482 // We don't want to warn for system macro. 10483 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10484 // warn about dropping FP rank. 10485 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10486 diag::warn_impcast_float_result_precision); 10487 } 10488 10489 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10490 IntRange Range) { 10491 if (!Range.Width) return "0"; 10492 10493 llvm::APSInt ValueInRange = Value; 10494 ValueInRange.setIsSigned(!Range.NonNegative); 10495 ValueInRange = ValueInRange.trunc(Range.Width); 10496 return ValueInRange.toString(10); 10497 } 10498 10499 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10500 if (!isa<ImplicitCastExpr>(Ex)) 10501 return false; 10502 10503 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10504 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10505 const Type *Source = 10506 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10507 if (Target->isDependentType()) 10508 return false; 10509 10510 const BuiltinType *FloatCandidateBT = 10511 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10512 const Type *BoolCandidateType = ToBool ? Target : Source; 10513 10514 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10515 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10516 } 10517 10518 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10519 SourceLocation CC) { 10520 unsigned NumArgs = TheCall->getNumArgs(); 10521 for (unsigned i = 0; i < NumArgs; ++i) { 10522 Expr *CurrA = TheCall->getArg(i); 10523 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10524 continue; 10525 10526 bool IsSwapped = ((i > 0) && 10527 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10528 IsSwapped |= ((i < (NumArgs - 1)) && 10529 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10530 if (IsSwapped) { 10531 // Warn on this floating-point to bool conversion. 10532 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10533 CurrA->getType(), CC, 10534 diag::warn_impcast_floating_point_to_bool); 10535 } 10536 } 10537 } 10538 10539 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10540 SourceLocation CC) { 10541 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10542 E->getExprLoc())) 10543 return; 10544 10545 // Don't warn on functions which have return type nullptr_t. 10546 if (isa<CallExpr>(E)) 10547 return; 10548 10549 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10550 const Expr::NullPointerConstantKind NullKind = 10551 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10552 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10553 return; 10554 10555 // Return if target type is a safe conversion. 10556 if (T->isAnyPointerType() || T->isBlockPointerType() || 10557 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10558 return; 10559 10560 SourceLocation Loc = E->getSourceRange().getBegin(); 10561 10562 // Venture through the macro stacks to get to the source of macro arguments. 10563 // The new location is a better location than the complete location that was 10564 // passed in. 10565 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10566 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10567 10568 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10569 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10570 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10571 Loc, S.SourceMgr, S.getLangOpts()); 10572 if (MacroName == "NULL") 10573 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10574 } 10575 10576 // Only warn if the null and context location are in the same macro expansion. 10577 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10578 return; 10579 10580 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10581 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10582 << FixItHint::CreateReplacement(Loc, 10583 S.getFixItZeroLiteralForType(T, Loc)); 10584 } 10585 10586 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10587 ObjCArrayLiteral *ArrayLiteral); 10588 10589 static void 10590 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10591 ObjCDictionaryLiteral *DictionaryLiteral); 10592 10593 /// Check a single element within a collection literal against the 10594 /// target element type. 10595 static void checkObjCCollectionLiteralElement(Sema &S, 10596 QualType TargetElementType, 10597 Expr *Element, 10598 unsigned ElementKind) { 10599 // Skip a bitcast to 'id' or qualified 'id'. 10600 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10601 if (ICE->getCastKind() == CK_BitCast && 10602 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10603 Element = ICE->getSubExpr(); 10604 } 10605 10606 QualType ElementType = Element->getType(); 10607 ExprResult ElementResult(Element); 10608 if (ElementType->getAs<ObjCObjectPointerType>() && 10609 S.CheckSingleAssignmentConstraints(TargetElementType, 10610 ElementResult, 10611 false, false) 10612 != Sema::Compatible) { 10613 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10614 << ElementType << ElementKind << TargetElementType 10615 << Element->getSourceRange(); 10616 } 10617 10618 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10619 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10620 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10621 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10622 } 10623 10624 /// Check an Objective-C array literal being converted to the given 10625 /// target type. 10626 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10627 ObjCArrayLiteral *ArrayLiteral) { 10628 if (!S.NSArrayDecl) 10629 return; 10630 10631 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10632 if (!TargetObjCPtr) 10633 return; 10634 10635 if (TargetObjCPtr->isUnspecialized() || 10636 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10637 != S.NSArrayDecl->getCanonicalDecl()) 10638 return; 10639 10640 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10641 if (TypeArgs.size() != 1) 10642 return; 10643 10644 QualType TargetElementType = TypeArgs[0]; 10645 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10646 checkObjCCollectionLiteralElement(S, TargetElementType, 10647 ArrayLiteral->getElement(I), 10648 0); 10649 } 10650 } 10651 10652 /// Check an Objective-C dictionary literal being converted to the given 10653 /// target type. 10654 static void 10655 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10656 ObjCDictionaryLiteral *DictionaryLiteral) { 10657 if (!S.NSDictionaryDecl) 10658 return; 10659 10660 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10661 if (!TargetObjCPtr) 10662 return; 10663 10664 if (TargetObjCPtr->isUnspecialized() || 10665 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10666 != S.NSDictionaryDecl->getCanonicalDecl()) 10667 return; 10668 10669 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10670 if (TypeArgs.size() != 2) 10671 return; 10672 10673 QualType TargetKeyType = TypeArgs[0]; 10674 QualType TargetObjectType = TypeArgs[1]; 10675 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10676 auto Element = DictionaryLiteral->getKeyValueElement(I); 10677 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10678 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10679 } 10680 } 10681 10682 // Helper function to filter out cases for constant width constant conversion. 10683 // Don't warn on char array initialization or for non-decimal values. 10684 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10685 SourceLocation CC) { 10686 // If initializing from a constant, and the constant starts with '0', 10687 // then it is a binary, octal, or hexadecimal. Allow these constants 10688 // to fill all the bits, even if there is a sign change. 10689 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10690 const char FirstLiteralCharacter = 10691 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10692 if (FirstLiteralCharacter == '0') 10693 return false; 10694 } 10695 10696 // If the CC location points to a '{', and the type is char, then assume 10697 // assume it is an array initialization. 10698 if (CC.isValid() && T->isCharType()) { 10699 const char FirstContextCharacter = 10700 S.getSourceManager().getCharacterData(CC)[0]; 10701 if (FirstContextCharacter == '{') 10702 return false; 10703 } 10704 10705 return true; 10706 } 10707 10708 static void 10709 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10710 bool *ICContext = nullptr) { 10711 if (E->isTypeDependent() || E->isValueDependent()) return; 10712 10713 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10714 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10715 if (Source == Target) return; 10716 if (Target->isDependentType()) return; 10717 10718 // If the conversion context location is invalid don't complain. We also 10719 // don't want to emit a warning if the issue occurs from the expansion of 10720 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10721 // delay this check as long as possible. Once we detect we are in that 10722 // scenario, we just return. 10723 if (CC.isInvalid()) 10724 return; 10725 10726 if (Source->isAtomicType()) 10727 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 10728 10729 // Diagnose implicit casts to bool. 10730 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10731 if (isa<StringLiteral>(E)) 10732 // Warn on string literal to bool. Checks for string literals in logical 10733 // and expressions, for instance, assert(0 && "error here"), are 10734 // prevented by a check in AnalyzeImplicitConversions(). 10735 return DiagnoseImpCast(S, E, T, CC, 10736 diag::warn_impcast_string_literal_to_bool); 10737 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10738 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10739 // This covers the literal expressions that evaluate to Objective-C 10740 // objects. 10741 return DiagnoseImpCast(S, E, T, CC, 10742 diag::warn_impcast_objective_c_literal_to_bool); 10743 } 10744 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10745 // Warn on pointer to bool conversion that is always true. 10746 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10747 SourceRange(CC)); 10748 } 10749 } 10750 10751 // Check implicit casts from Objective-C collection literals to specialized 10752 // collection types, e.g., NSArray<NSString *> *. 10753 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10754 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10755 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10756 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10757 10758 // Strip vector types. 10759 if (isa<VectorType>(Source)) { 10760 if (!isa<VectorType>(Target)) { 10761 if (S.SourceMgr.isInSystemMacro(CC)) 10762 return; 10763 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10764 } 10765 10766 // If the vector cast is cast between two vectors of the same size, it is 10767 // a bitcast, not a conversion. 10768 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10769 return; 10770 10771 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10772 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10773 } 10774 if (auto VecTy = dyn_cast<VectorType>(Target)) 10775 Target = VecTy->getElementType().getTypePtr(); 10776 10777 // Strip complex types. 10778 if (isa<ComplexType>(Source)) { 10779 if (!isa<ComplexType>(Target)) { 10780 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10781 return; 10782 10783 return DiagnoseImpCast(S, E, T, CC, 10784 S.getLangOpts().CPlusPlus 10785 ? diag::err_impcast_complex_scalar 10786 : diag::warn_impcast_complex_scalar); 10787 } 10788 10789 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10790 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10791 } 10792 10793 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10794 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10795 10796 // If the source is floating point... 10797 if (SourceBT && SourceBT->isFloatingPoint()) { 10798 // ...and the target is floating point... 10799 if (TargetBT && TargetBT->isFloatingPoint()) { 10800 // ...then warn if we're dropping FP rank. 10801 10802 // Builtin FP kinds are ordered by increasing FP rank. 10803 if (SourceBT->getKind() > TargetBT->getKind()) { 10804 // Don't warn about float constants that are precisely 10805 // representable in the target type. 10806 Expr::EvalResult result; 10807 if (E->EvaluateAsRValue(result, S.Context)) { 10808 // Value might be a float, a float vector, or a float complex. 10809 if (IsSameFloatAfterCast(result.Val, 10810 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10811 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10812 return; 10813 } 10814 10815 if (S.SourceMgr.isInSystemMacro(CC)) 10816 return; 10817 10818 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10819 } 10820 // ... or possibly if we're increasing rank, too 10821 else if (TargetBT->getKind() > SourceBT->getKind()) { 10822 if (S.SourceMgr.isInSystemMacro(CC)) 10823 return; 10824 10825 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10826 } 10827 return; 10828 } 10829 10830 // If the target is integral, always warn. 10831 if (TargetBT && TargetBT->isInteger()) { 10832 if (S.SourceMgr.isInSystemMacro(CC)) 10833 return; 10834 10835 DiagnoseFloatingImpCast(S, E, T, CC); 10836 } 10837 10838 // Detect the case where a call result is converted from floating-point to 10839 // to bool, and the final argument to the call is converted from bool, to 10840 // discover this typo: 10841 // 10842 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10843 // 10844 // FIXME: This is an incredibly special case; is there some more general 10845 // way to detect this class of misplaced-parentheses bug? 10846 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10847 // Check last argument of function call to see if it is an 10848 // implicit cast from a type matching the type the result 10849 // is being cast to. 10850 CallExpr *CEx = cast<CallExpr>(E); 10851 if (unsigned NumArgs = CEx->getNumArgs()) { 10852 Expr *LastA = CEx->getArg(NumArgs - 1); 10853 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10854 if (isa<ImplicitCastExpr>(LastA) && 10855 InnerE->getType()->isBooleanType()) { 10856 // Warn on this floating-point to bool conversion 10857 DiagnoseImpCast(S, E, T, CC, 10858 diag::warn_impcast_floating_point_to_bool); 10859 } 10860 } 10861 } 10862 return; 10863 } 10864 10865 DiagnoseNullConversion(S, E, T, CC); 10866 10867 S.DiscardMisalignedMemberAddress(Target, E); 10868 10869 if (!Source->isIntegerType() || !Target->isIntegerType()) 10870 return; 10871 10872 // TODO: remove this early return once the false positives for constant->bool 10873 // in templates, macros, etc, are reduced or removed. 10874 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10875 return; 10876 10877 IntRange SourceRange = GetExprRange(S.Context, E); 10878 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10879 10880 if (SourceRange.Width > TargetRange.Width) { 10881 // If the source is a constant, use a default-on diagnostic. 10882 // TODO: this should happen for bitfield stores, too. 10883 llvm::APSInt Value(32); 10884 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10885 if (S.SourceMgr.isInSystemMacro(CC)) 10886 return; 10887 10888 std::string PrettySourceValue = Value.toString(10); 10889 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10890 10891 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10892 S.PDiag(diag::warn_impcast_integer_precision_constant) 10893 << PrettySourceValue << PrettyTargetValue 10894 << E->getType() << T << E->getSourceRange() 10895 << clang::SourceRange(CC)); 10896 return; 10897 } 10898 10899 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10900 if (S.SourceMgr.isInSystemMacro(CC)) 10901 return; 10902 10903 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10904 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10905 /* pruneControlFlow */ true); 10906 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10907 } 10908 10909 if (TargetRange.Width > SourceRange.Width) { 10910 if (auto *UO = dyn_cast<UnaryOperator>(E)) 10911 if (UO->getOpcode() == UO_Minus) 10912 if (Source->isUnsignedIntegerType()) { 10913 if (Target->isUnsignedIntegerType()) 10914 return DiagnoseImpCast(S, E, T, CC, 10915 diag::warn_impcast_high_order_zero_bits); 10916 if (Target->isSignedIntegerType()) 10917 return DiagnoseImpCast(S, E, T, CC, 10918 diag::warn_impcast_nonnegative_result); 10919 } 10920 } 10921 10922 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10923 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10924 // Warn when doing a signed to signed conversion, warn if the positive 10925 // source value is exactly the width of the target type, which will 10926 // cause a negative value to be stored. 10927 10928 llvm::APSInt Value; 10929 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10930 !S.SourceMgr.isInSystemMacro(CC)) { 10931 if (isSameWidthConstantConversion(S, E, T, CC)) { 10932 std::string PrettySourceValue = Value.toString(10); 10933 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10934 10935 S.DiagRuntimeBehavior( 10936 E->getExprLoc(), E, 10937 S.PDiag(diag::warn_impcast_integer_precision_constant) 10938 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10939 << E->getSourceRange() << clang::SourceRange(CC)); 10940 return; 10941 } 10942 } 10943 10944 // Fall through for non-constants to give a sign conversion warning. 10945 } 10946 10947 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10948 (!TargetRange.NonNegative && SourceRange.NonNegative && 10949 SourceRange.Width == TargetRange.Width)) { 10950 if (S.SourceMgr.isInSystemMacro(CC)) 10951 return; 10952 10953 unsigned DiagID = diag::warn_impcast_integer_sign; 10954 10955 // Traditionally, gcc has warned about this under -Wsign-compare. 10956 // We also want to warn about it in -Wconversion. 10957 // So if -Wconversion is off, use a completely identical diagnostic 10958 // in the sign-compare group. 10959 // The conditional-checking code will 10960 if (ICContext) { 10961 DiagID = diag::warn_impcast_integer_sign_conditional; 10962 *ICContext = true; 10963 } 10964 10965 return DiagnoseImpCast(S, E, T, CC, DiagID); 10966 } 10967 10968 // Diagnose conversions between different enumeration types. 10969 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10970 // type, to give us better diagnostics. 10971 QualType SourceType = E->getType(); 10972 if (!S.getLangOpts().CPlusPlus) { 10973 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10974 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10975 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10976 SourceType = S.Context.getTypeDeclType(Enum); 10977 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10978 } 10979 } 10980 10981 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10982 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10983 if (SourceEnum->getDecl()->hasNameForLinkage() && 10984 TargetEnum->getDecl()->hasNameForLinkage() && 10985 SourceEnum != TargetEnum) { 10986 if (S.SourceMgr.isInSystemMacro(CC)) 10987 return; 10988 10989 return DiagnoseImpCast(S, E, SourceType, T, CC, 10990 diag::warn_impcast_different_enum_types); 10991 } 10992 } 10993 10994 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10995 SourceLocation CC, QualType T); 10996 10997 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10998 SourceLocation CC, bool &ICContext) { 10999 E = E->IgnoreParenImpCasts(); 11000 11001 if (isa<ConditionalOperator>(E)) 11002 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11003 11004 AnalyzeImplicitConversions(S, E, CC); 11005 if (E->getType() != T) 11006 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11007 } 11008 11009 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11010 SourceLocation CC, QualType T) { 11011 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11012 11013 bool Suspicious = false; 11014 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11015 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11016 11017 // If -Wconversion would have warned about either of the candidates 11018 // for a signedness conversion to the context type... 11019 if (!Suspicious) return; 11020 11021 // ...but it's currently ignored... 11022 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11023 return; 11024 11025 // ...then check whether it would have warned about either of the 11026 // candidates for a signedness conversion to the condition type. 11027 if (E->getType() == T) return; 11028 11029 Suspicious = false; 11030 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11031 E->getType(), CC, &Suspicious); 11032 if (!Suspicious) 11033 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11034 E->getType(), CC, &Suspicious); 11035 } 11036 11037 /// Check conversion of given expression to boolean. 11038 /// Input argument E is a logical expression. 11039 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11040 if (S.getLangOpts().Bool) 11041 return; 11042 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11043 return; 11044 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11045 } 11046 11047 /// AnalyzeImplicitConversions - Find and report any interesting 11048 /// implicit conversions in the given expression. There are a couple 11049 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11050 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11051 SourceLocation CC) { 11052 QualType T = OrigE->getType(); 11053 Expr *E = OrigE->IgnoreParenImpCasts(); 11054 11055 if (E->isTypeDependent() || E->isValueDependent()) 11056 return; 11057 11058 // For conditional operators, we analyze the arguments as if they 11059 // were being fed directly into the output. 11060 if (isa<ConditionalOperator>(E)) { 11061 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11062 CheckConditionalOperator(S, CO, CC, T); 11063 return; 11064 } 11065 11066 // Check implicit argument conversions for function calls. 11067 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11068 CheckImplicitArgumentConversions(S, Call, CC); 11069 11070 // Go ahead and check any implicit conversions we might have skipped. 11071 // The non-canonical typecheck is just an optimization; 11072 // CheckImplicitConversion will filter out dead implicit conversions. 11073 if (E->getType() != T) 11074 CheckImplicitConversion(S, E, T, CC); 11075 11076 // Now continue drilling into this expression. 11077 11078 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11079 // The bound subexpressions in a PseudoObjectExpr are not reachable 11080 // as transitive children. 11081 // FIXME: Use a more uniform representation for this. 11082 for (auto *SE : POE->semantics()) 11083 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11084 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11085 } 11086 11087 // Skip past explicit casts. 11088 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11089 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11090 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11091 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11092 return AnalyzeImplicitConversions(S, E, CC); 11093 } 11094 11095 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11096 // Do a somewhat different check with comparison operators. 11097 if (BO->isComparisonOp()) 11098 return AnalyzeComparison(S, BO); 11099 11100 // And with simple assignments. 11101 if (BO->getOpcode() == BO_Assign) 11102 return AnalyzeAssignment(S, BO); 11103 // And with compound assignments. 11104 if (BO->isAssignmentOp()) 11105 return AnalyzeCompoundAssignment(S, BO); 11106 } 11107 11108 // These break the otherwise-useful invariant below. Fortunately, 11109 // we don't really need to recurse into them, because any internal 11110 // expressions should have been analyzed already when they were 11111 // built into statements. 11112 if (isa<StmtExpr>(E)) return; 11113 11114 // Don't descend into unevaluated contexts. 11115 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11116 11117 // Now just recurse over the expression's children. 11118 CC = E->getExprLoc(); 11119 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11120 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11121 for (Stmt *SubStmt : E->children()) { 11122 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11123 if (!ChildExpr) 11124 continue; 11125 11126 if (IsLogicalAndOperator && 11127 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11128 // Ignore checking string literals that are in logical and operators. 11129 // This is a common pattern for asserts. 11130 continue; 11131 AnalyzeImplicitConversions(S, ChildExpr, CC); 11132 } 11133 11134 if (BO && BO->isLogicalOp()) { 11135 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11136 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11137 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11138 11139 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11140 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11141 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11142 } 11143 11144 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11145 if (U->getOpcode() == UO_LNot) { 11146 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11147 } else if (U->getOpcode() != UO_AddrOf) { 11148 if (U->getSubExpr()->getType()->isAtomicType()) 11149 S.Diag(U->getSubExpr()->getBeginLoc(), 11150 diag::warn_atomic_implicit_seq_cst); 11151 } 11152 } 11153 } 11154 11155 /// Diagnose integer type and any valid implicit conversion to it. 11156 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11157 // Taking into account implicit conversions, 11158 // allow any integer. 11159 if (!E->getType()->isIntegerType()) { 11160 S.Diag(E->getBeginLoc(), 11161 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11162 return true; 11163 } 11164 // Potentially emit standard warnings for implicit conversions if enabled 11165 // using -Wconversion. 11166 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11167 return false; 11168 } 11169 11170 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11171 // Returns true when emitting a warning about taking the address of a reference. 11172 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11173 const PartialDiagnostic &PD) { 11174 E = E->IgnoreParenImpCasts(); 11175 11176 const FunctionDecl *FD = nullptr; 11177 11178 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11179 if (!DRE->getDecl()->getType()->isReferenceType()) 11180 return false; 11181 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11182 if (!M->getMemberDecl()->getType()->isReferenceType()) 11183 return false; 11184 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11185 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11186 return false; 11187 FD = Call->getDirectCallee(); 11188 } else { 11189 return false; 11190 } 11191 11192 SemaRef.Diag(E->getExprLoc(), PD); 11193 11194 // If possible, point to location of function. 11195 if (FD) { 11196 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11197 } 11198 11199 return true; 11200 } 11201 11202 // Returns true if the SourceLocation is expanded from any macro body. 11203 // Returns false if the SourceLocation is invalid, is from not in a macro 11204 // expansion, or is from expanded from a top-level macro argument. 11205 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11206 if (Loc.isInvalid()) 11207 return false; 11208 11209 while (Loc.isMacroID()) { 11210 if (SM.isMacroBodyExpansion(Loc)) 11211 return true; 11212 Loc = SM.getImmediateMacroCallerLoc(Loc); 11213 } 11214 11215 return false; 11216 } 11217 11218 /// Diagnose pointers that are always non-null. 11219 /// \param E the expression containing the pointer 11220 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11221 /// compared to a null pointer 11222 /// \param IsEqual True when the comparison is equal to a null pointer 11223 /// \param Range Extra SourceRange to highlight in the diagnostic 11224 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11225 Expr::NullPointerConstantKind NullKind, 11226 bool IsEqual, SourceRange Range) { 11227 if (!E) 11228 return; 11229 11230 // Don't warn inside macros. 11231 if (E->getExprLoc().isMacroID()) { 11232 const SourceManager &SM = getSourceManager(); 11233 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11234 IsInAnyMacroBody(SM, Range.getBegin())) 11235 return; 11236 } 11237 E = E->IgnoreImpCasts(); 11238 11239 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11240 11241 if (isa<CXXThisExpr>(E)) { 11242 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11243 : diag::warn_this_bool_conversion; 11244 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11245 return; 11246 } 11247 11248 bool IsAddressOf = false; 11249 11250 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11251 if (UO->getOpcode() != UO_AddrOf) 11252 return; 11253 IsAddressOf = true; 11254 E = UO->getSubExpr(); 11255 } 11256 11257 if (IsAddressOf) { 11258 unsigned DiagID = IsCompare 11259 ? diag::warn_address_of_reference_null_compare 11260 : diag::warn_address_of_reference_bool_conversion; 11261 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11262 << IsEqual; 11263 if (CheckForReference(*this, E, PD)) { 11264 return; 11265 } 11266 } 11267 11268 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11269 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11270 std::string Str; 11271 llvm::raw_string_ostream S(Str); 11272 E->printPretty(S, nullptr, getPrintingPolicy()); 11273 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11274 : diag::warn_cast_nonnull_to_bool; 11275 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11276 << E->getSourceRange() << Range << IsEqual; 11277 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11278 }; 11279 11280 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11281 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11282 if (auto *Callee = Call->getDirectCallee()) { 11283 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11284 ComplainAboutNonnullParamOrCall(A); 11285 return; 11286 } 11287 } 11288 } 11289 11290 // Expect to find a single Decl. Skip anything more complicated. 11291 ValueDecl *D = nullptr; 11292 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11293 D = R->getDecl(); 11294 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11295 D = M->getMemberDecl(); 11296 } 11297 11298 // Weak Decls can be null. 11299 if (!D || D->isWeak()) 11300 return; 11301 11302 // Check for parameter decl with nonnull attribute 11303 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11304 if (getCurFunction() && 11305 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11306 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11307 ComplainAboutNonnullParamOrCall(A); 11308 return; 11309 } 11310 11311 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11312 auto ParamIter = llvm::find(FD->parameters(), PV); 11313 assert(ParamIter != FD->param_end()); 11314 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11315 11316 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11317 if (!NonNull->args_size()) { 11318 ComplainAboutNonnullParamOrCall(NonNull); 11319 return; 11320 } 11321 11322 for (const ParamIdx &ArgNo : NonNull->args()) { 11323 if (ArgNo.getASTIndex() == ParamNo) { 11324 ComplainAboutNonnullParamOrCall(NonNull); 11325 return; 11326 } 11327 } 11328 } 11329 } 11330 } 11331 } 11332 11333 QualType T = D->getType(); 11334 const bool IsArray = T->isArrayType(); 11335 const bool IsFunction = T->isFunctionType(); 11336 11337 // Address of function is used to silence the function warning. 11338 if (IsAddressOf && IsFunction) { 11339 return; 11340 } 11341 11342 // Found nothing. 11343 if (!IsAddressOf && !IsFunction && !IsArray) 11344 return; 11345 11346 // Pretty print the expression for the diagnostic. 11347 std::string Str; 11348 llvm::raw_string_ostream S(Str); 11349 E->printPretty(S, nullptr, getPrintingPolicy()); 11350 11351 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11352 : diag::warn_impcast_pointer_to_bool; 11353 enum { 11354 AddressOf, 11355 FunctionPointer, 11356 ArrayPointer 11357 } DiagType; 11358 if (IsAddressOf) 11359 DiagType = AddressOf; 11360 else if (IsFunction) 11361 DiagType = FunctionPointer; 11362 else if (IsArray) 11363 DiagType = ArrayPointer; 11364 else 11365 llvm_unreachable("Could not determine diagnostic."); 11366 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11367 << Range << IsEqual; 11368 11369 if (!IsFunction) 11370 return; 11371 11372 // Suggest '&' to silence the function warning. 11373 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11374 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11375 11376 // Check to see if '()' fixit should be emitted. 11377 QualType ReturnType; 11378 UnresolvedSet<4> NonTemplateOverloads; 11379 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11380 if (ReturnType.isNull()) 11381 return; 11382 11383 if (IsCompare) { 11384 // There are two cases here. If there is null constant, the only suggest 11385 // for a pointer return type. If the null is 0, then suggest if the return 11386 // type is a pointer or an integer type. 11387 if (!ReturnType->isPointerType()) { 11388 if (NullKind == Expr::NPCK_ZeroExpression || 11389 NullKind == Expr::NPCK_ZeroLiteral) { 11390 if (!ReturnType->isIntegerType()) 11391 return; 11392 } else { 11393 return; 11394 } 11395 } 11396 } else { // !IsCompare 11397 // For function to bool, only suggest if the function pointer has bool 11398 // return type. 11399 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11400 return; 11401 } 11402 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11403 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11404 } 11405 11406 /// Diagnoses "dangerous" implicit conversions within the given 11407 /// expression (which is a full expression). Implements -Wconversion 11408 /// and -Wsign-compare. 11409 /// 11410 /// \param CC the "context" location of the implicit conversion, i.e. 11411 /// the most location of the syntactic entity requiring the implicit 11412 /// conversion 11413 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11414 // Don't diagnose in unevaluated contexts. 11415 if (isUnevaluatedContext()) 11416 return; 11417 11418 // Don't diagnose for value- or type-dependent expressions. 11419 if (E->isTypeDependent() || E->isValueDependent()) 11420 return; 11421 11422 // Check for array bounds violations in cases where the check isn't triggered 11423 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11424 // ArraySubscriptExpr is on the RHS of a variable initialization. 11425 CheckArrayAccess(E); 11426 11427 // This is not the right CC for (e.g.) a variable initialization. 11428 AnalyzeImplicitConversions(*this, E, CC); 11429 } 11430 11431 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11432 /// Input argument E is a logical expression. 11433 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11434 ::CheckBoolLikeConversion(*this, E, CC); 11435 } 11436 11437 /// Diagnose when expression is an integer constant expression and its evaluation 11438 /// results in integer overflow 11439 void Sema::CheckForIntOverflow (Expr *E) { 11440 // Use a work list to deal with nested struct initializers. 11441 SmallVector<Expr *, 2> Exprs(1, E); 11442 11443 do { 11444 Expr *OriginalE = Exprs.pop_back_val(); 11445 Expr *E = OriginalE->IgnoreParenCasts(); 11446 11447 if (isa<BinaryOperator>(E)) { 11448 E->EvaluateForOverflow(Context); 11449 continue; 11450 } 11451 11452 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11453 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11454 else if (isa<ObjCBoxedExpr>(OriginalE)) 11455 E->EvaluateForOverflow(Context); 11456 else if (auto Call = dyn_cast<CallExpr>(E)) 11457 Exprs.append(Call->arg_begin(), Call->arg_end()); 11458 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11459 Exprs.append(Message->arg_begin(), Message->arg_end()); 11460 } while (!Exprs.empty()); 11461 } 11462 11463 namespace { 11464 11465 /// Visitor for expressions which looks for unsequenced operations on the 11466 /// same object. 11467 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11468 using Base = EvaluatedExprVisitor<SequenceChecker>; 11469 11470 /// A tree of sequenced regions within an expression. Two regions are 11471 /// unsequenced if one is an ancestor or a descendent of the other. When we 11472 /// finish processing an expression with sequencing, such as a comma 11473 /// expression, we fold its tree nodes into its parent, since they are 11474 /// unsequenced with respect to nodes we will visit later. 11475 class SequenceTree { 11476 struct Value { 11477 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11478 unsigned Parent : 31; 11479 unsigned Merged : 1; 11480 }; 11481 SmallVector<Value, 8> Values; 11482 11483 public: 11484 /// A region within an expression which may be sequenced with respect 11485 /// to some other region. 11486 class Seq { 11487 friend class SequenceTree; 11488 11489 unsigned Index = 0; 11490 11491 explicit Seq(unsigned N) : Index(N) {} 11492 11493 public: 11494 Seq() = default; 11495 }; 11496 11497 SequenceTree() { Values.push_back(Value(0)); } 11498 Seq root() const { return Seq(0); } 11499 11500 /// Create a new sequence of operations, which is an unsequenced 11501 /// subset of \p Parent. This sequence of operations is sequenced with 11502 /// respect to other children of \p Parent. 11503 Seq allocate(Seq Parent) { 11504 Values.push_back(Value(Parent.Index)); 11505 return Seq(Values.size() - 1); 11506 } 11507 11508 /// Merge a sequence of operations into its parent. 11509 void merge(Seq S) { 11510 Values[S.Index].Merged = true; 11511 } 11512 11513 /// Determine whether two operations are unsequenced. This operation 11514 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11515 /// should have been merged into its parent as appropriate. 11516 bool isUnsequenced(Seq Cur, Seq Old) { 11517 unsigned C = representative(Cur.Index); 11518 unsigned Target = representative(Old.Index); 11519 while (C >= Target) { 11520 if (C == Target) 11521 return true; 11522 C = Values[C].Parent; 11523 } 11524 return false; 11525 } 11526 11527 private: 11528 /// Pick a representative for a sequence. 11529 unsigned representative(unsigned K) { 11530 if (Values[K].Merged) 11531 // Perform path compression as we go. 11532 return Values[K].Parent = representative(Values[K].Parent); 11533 return K; 11534 } 11535 }; 11536 11537 /// An object for which we can track unsequenced uses. 11538 using Object = NamedDecl *; 11539 11540 /// Different flavors of object usage which we track. We only track the 11541 /// least-sequenced usage of each kind. 11542 enum UsageKind { 11543 /// A read of an object. Multiple unsequenced reads are OK. 11544 UK_Use, 11545 11546 /// A modification of an object which is sequenced before the value 11547 /// computation of the expression, such as ++n in C++. 11548 UK_ModAsValue, 11549 11550 /// A modification of an object which is not sequenced before the value 11551 /// computation of the expression, such as n++. 11552 UK_ModAsSideEffect, 11553 11554 UK_Count = UK_ModAsSideEffect + 1 11555 }; 11556 11557 struct Usage { 11558 Expr *Use = nullptr; 11559 SequenceTree::Seq Seq; 11560 11561 Usage() = default; 11562 }; 11563 11564 struct UsageInfo { 11565 Usage Uses[UK_Count]; 11566 11567 /// Have we issued a diagnostic for this variable already? 11568 bool Diagnosed = false; 11569 11570 UsageInfo() = default; 11571 }; 11572 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11573 11574 Sema &SemaRef; 11575 11576 /// Sequenced regions within the expression. 11577 SequenceTree Tree; 11578 11579 /// Declaration modifications and references which we have seen. 11580 UsageInfoMap UsageMap; 11581 11582 /// The region we are currently within. 11583 SequenceTree::Seq Region; 11584 11585 /// Filled in with declarations which were modified as a side-effect 11586 /// (that is, post-increment operations). 11587 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11588 11589 /// Expressions to check later. We defer checking these to reduce 11590 /// stack usage. 11591 SmallVectorImpl<Expr *> &WorkList; 11592 11593 /// RAII object wrapping the visitation of a sequenced subexpression of an 11594 /// expression. At the end of this process, the side-effects of the evaluation 11595 /// become sequenced with respect to the value computation of the result, so 11596 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11597 /// UK_ModAsValue. 11598 struct SequencedSubexpression { 11599 SequencedSubexpression(SequenceChecker &Self) 11600 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11601 Self.ModAsSideEffect = &ModAsSideEffect; 11602 } 11603 11604 ~SequencedSubexpression() { 11605 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11606 UsageInfo &U = Self.UsageMap[M.first]; 11607 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11608 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11609 SideEffectUsage = M.second; 11610 } 11611 Self.ModAsSideEffect = OldModAsSideEffect; 11612 } 11613 11614 SequenceChecker &Self; 11615 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11616 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11617 }; 11618 11619 /// RAII object wrapping the visitation of a subexpression which we might 11620 /// choose to evaluate as a constant. If any subexpression is evaluated and 11621 /// found to be non-constant, this allows us to suppress the evaluation of 11622 /// the outer expression. 11623 class EvaluationTracker { 11624 public: 11625 EvaluationTracker(SequenceChecker &Self) 11626 : Self(Self), Prev(Self.EvalTracker) { 11627 Self.EvalTracker = this; 11628 } 11629 11630 ~EvaluationTracker() { 11631 Self.EvalTracker = Prev; 11632 if (Prev) 11633 Prev->EvalOK &= EvalOK; 11634 } 11635 11636 bool evaluate(const Expr *E, bool &Result) { 11637 if (!EvalOK || E->isValueDependent()) 11638 return false; 11639 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11640 return EvalOK; 11641 } 11642 11643 private: 11644 SequenceChecker &Self; 11645 EvaluationTracker *Prev; 11646 bool EvalOK = true; 11647 } *EvalTracker = nullptr; 11648 11649 /// Find the object which is produced by the specified expression, 11650 /// if any. 11651 Object getObject(Expr *E, bool Mod) const { 11652 E = E->IgnoreParenCasts(); 11653 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11654 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11655 return getObject(UO->getSubExpr(), Mod); 11656 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11657 if (BO->getOpcode() == BO_Comma) 11658 return getObject(BO->getRHS(), Mod); 11659 if (Mod && BO->isAssignmentOp()) 11660 return getObject(BO->getLHS(), Mod); 11661 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11662 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11663 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11664 return ME->getMemberDecl(); 11665 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11666 // FIXME: If this is a reference, map through to its value. 11667 return DRE->getDecl(); 11668 return nullptr; 11669 } 11670 11671 /// Note that an object was modified or used by an expression. 11672 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11673 Usage &U = UI.Uses[UK]; 11674 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11675 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11676 ModAsSideEffect->push_back(std::make_pair(O, U)); 11677 U.Use = Ref; 11678 U.Seq = Region; 11679 } 11680 } 11681 11682 /// Check whether a modification or use conflicts with a prior usage. 11683 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11684 bool IsModMod) { 11685 if (UI.Diagnosed) 11686 return; 11687 11688 const Usage &U = UI.Uses[OtherKind]; 11689 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11690 return; 11691 11692 Expr *Mod = U.Use; 11693 Expr *ModOrUse = Ref; 11694 if (OtherKind == UK_Use) 11695 std::swap(Mod, ModOrUse); 11696 11697 SemaRef.Diag(Mod->getExprLoc(), 11698 IsModMod ? diag::warn_unsequenced_mod_mod 11699 : diag::warn_unsequenced_mod_use) 11700 << O << SourceRange(ModOrUse->getExprLoc()); 11701 UI.Diagnosed = true; 11702 } 11703 11704 void notePreUse(Object O, Expr *Use) { 11705 UsageInfo &U = UsageMap[O]; 11706 // Uses conflict with other modifications. 11707 checkUsage(O, U, Use, UK_ModAsValue, false); 11708 } 11709 11710 void notePostUse(Object O, Expr *Use) { 11711 UsageInfo &U = UsageMap[O]; 11712 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11713 addUsage(U, O, Use, UK_Use); 11714 } 11715 11716 void notePreMod(Object O, Expr *Mod) { 11717 UsageInfo &U = UsageMap[O]; 11718 // Modifications conflict with other modifications and with uses. 11719 checkUsage(O, U, Mod, UK_ModAsValue, true); 11720 checkUsage(O, U, Mod, UK_Use, false); 11721 } 11722 11723 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11724 UsageInfo &U = UsageMap[O]; 11725 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11726 addUsage(U, O, Use, UK); 11727 } 11728 11729 public: 11730 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11731 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11732 Visit(E); 11733 } 11734 11735 void VisitStmt(Stmt *S) { 11736 // Skip all statements which aren't expressions for now. 11737 } 11738 11739 void VisitExpr(Expr *E) { 11740 // By default, just recurse to evaluated subexpressions. 11741 Base::VisitStmt(E); 11742 } 11743 11744 void VisitCastExpr(CastExpr *E) { 11745 Object O = Object(); 11746 if (E->getCastKind() == CK_LValueToRValue) 11747 O = getObject(E->getSubExpr(), false); 11748 11749 if (O) 11750 notePreUse(O, E); 11751 VisitExpr(E); 11752 if (O) 11753 notePostUse(O, E); 11754 } 11755 11756 void VisitBinComma(BinaryOperator *BO) { 11757 // C++11 [expr.comma]p1: 11758 // Every value computation and side effect associated with the left 11759 // expression is sequenced before every value computation and side 11760 // effect associated with the right expression. 11761 SequenceTree::Seq LHS = Tree.allocate(Region); 11762 SequenceTree::Seq RHS = Tree.allocate(Region); 11763 SequenceTree::Seq OldRegion = Region; 11764 11765 { 11766 SequencedSubexpression SeqLHS(*this); 11767 Region = LHS; 11768 Visit(BO->getLHS()); 11769 } 11770 11771 Region = RHS; 11772 Visit(BO->getRHS()); 11773 11774 Region = OldRegion; 11775 11776 // Forget that LHS and RHS are sequenced. They are both unsequenced 11777 // with respect to other stuff. 11778 Tree.merge(LHS); 11779 Tree.merge(RHS); 11780 } 11781 11782 void VisitBinAssign(BinaryOperator *BO) { 11783 // The modification is sequenced after the value computation of the LHS 11784 // and RHS, so check it before inspecting the operands and update the 11785 // map afterwards. 11786 Object O = getObject(BO->getLHS(), true); 11787 if (!O) 11788 return VisitExpr(BO); 11789 11790 notePreMod(O, BO); 11791 11792 // C++11 [expr.ass]p7: 11793 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11794 // only once. 11795 // 11796 // Therefore, for a compound assignment operator, O is considered used 11797 // everywhere except within the evaluation of E1 itself. 11798 if (isa<CompoundAssignOperator>(BO)) 11799 notePreUse(O, BO); 11800 11801 Visit(BO->getLHS()); 11802 11803 if (isa<CompoundAssignOperator>(BO)) 11804 notePostUse(O, BO); 11805 11806 Visit(BO->getRHS()); 11807 11808 // C++11 [expr.ass]p1: 11809 // the assignment is sequenced [...] before the value computation of the 11810 // assignment expression. 11811 // C11 6.5.16/3 has no such rule. 11812 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11813 : UK_ModAsSideEffect); 11814 } 11815 11816 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11817 VisitBinAssign(CAO); 11818 } 11819 11820 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11821 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11822 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11823 Object O = getObject(UO->getSubExpr(), true); 11824 if (!O) 11825 return VisitExpr(UO); 11826 11827 notePreMod(O, UO); 11828 Visit(UO->getSubExpr()); 11829 // C++11 [expr.pre.incr]p1: 11830 // the expression ++x is equivalent to x+=1 11831 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11832 : UK_ModAsSideEffect); 11833 } 11834 11835 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11836 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11837 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11838 Object O = getObject(UO->getSubExpr(), true); 11839 if (!O) 11840 return VisitExpr(UO); 11841 11842 notePreMod(O, UO); 11843 Visit(UO->getSubExpr()); 11844 notePostMod(O, UO, UK_ModAsSideEffect); 11845 } 11846 11847 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11848 void VisitBinLOr(BinaryOperator *BO) { 11849 // The side-effects of the LHS of an '&&' are sequenced before the 11850 // value computation of the RHS, and hence before the value computation 11851 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11852 // as if they were unconditionally sequenced. 11853 EvaluationTracker Eval(*this); 11854 { 11855 SequencedSubexpression Sequenced(*this); 11856 Visit(BO->getLHS()); 11857 } 11858 11859 bool Result; 11860 if (Eval.evaluate(BO->getLHS(), Result)) { 11861 if (!Result) 11862 Visit(BO->getRHS()); 11863 } else { 11864 // Check for unsequenced operations in the RHS, treating it as an 11865 // entirely separate evaluation. 11866 // 11867 // FIXME: If there are operations in the RHS which are unsequenced 11868 // with respect to operations outside the RHS, and those operations 11869 // are unconditionally evaluated, diagnose them. 11870 WorkList.push_back(BO->getRHS()); 11871 } 11872 } 11873 void VisitBinLAnd(BinaryOperator *BO) { 11874 EvaluationTracker Eval(*this); 11875 { 11876 SequencedSubexpression Sequenced(*this); 11877 Visit(BO->getLHS()); 11878 } 11879 11880 bool Result; 11881 if (Eval.evaluate(BO->getLHS(), Result)) { 11882 if (Result) 11883 Visit(BO->getRHS()); 11884 } else { 11885 WorkList.push_back(BO->getRHS()); 11886 } 11887 } 11888 11889 // Only visit the condition, unless we can be sure which subexpression will 11890 // be chosen. 11891 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11892 EvaluationTracker Eval(*this); 11893 { 11894 SequencedSubexpression Sequenced(*this); 11895 Visit(CO->getCond()); 11896 } 11897 11898 bool Result; 11899 if (Eval.evaluate(CO->getCond(), Result)) 11900 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11901 else { 11902 WorkList.push_back(CO->getTrueExpr()); 11903 WorkList.push_back(CO->getFalseExpr()); 11904 } 11905 } 11906 11907 void VisitCallExpr(CallExpr *CE) { 11908 // C++11 [intro.execution]p15: 11909 // When calling a function [...], every value computation and side effect 11910 // associated with any argument expression, or with the postfix expression 11911 // designating the called function, is sequenced before execution of every 11912 // expression or statement in the body of the function [and thus before 11913 // the value computation of its result]. 11914 SequencedSubexpression Sequenced(*this); 11915 Base::VisitCallExpr(CE); 11916 11917 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11918 } 11919 11920 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11921 // This is a call, so all subexpressions are sequenced before the result. 11922 SequencedSubexpression Sequenced(*this); 11923 11924 if (!CCE->isListInitialization()) 11925 return VisitExpr(CCE); 11926 11927 // In C++11, list initializations are sequenced. 11928 SmallVector<SequenceTree::Seq, 32> Elts; 11929 SequenceTree::Seq Parent = Region; 11930 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11931 E = CCE->arg_end(); 11932 I != E; ++I) { 11933 Region = Tree.allocate(Parent); 11934 Elts.push_back(Region); 11935 Visit(*I); 11936 } 11937 11938 // Forget that the initializers are sequenced. 11939 Region = Parent; 11940 for (unsigned I = 0; I < Elts.size(); ++I) 11941 Tree.merge(Elts[I]); 11942 } 11943 11944 void VisitInitListExpr(InitListExpr *ILE) { 11945 if (!SemaRef.getLangOpts().CPlusPlus11) 11946 return VisitExpr(ILE); 11947 11948 // In C++11, list initializations are sequenced. 11949 SmallVector<SequenceTree::Seq, 32> Elts; 11950 SequenceTree::Seq Parent = Region; 11951 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11952 Expr *E = ILE->getInit(I); 11953 if (!E) continue; 11954 Region = Tree.allocate(Parent); 11955 Elts.push_back(Region); 11956 Visit(E); 11957 } 11958 11959 // Forget that the initializers are sequenced. 11960 Region = Parent; 11961 for (unsigned I = 0; I < Elts.size(); ++I) 11962 Tree.merge(Elts[I]); 11963 } 11964 }; 11965 11966 } // namespace 11967 11968 void Sema::CheckUnsequencedOperations(Expr *E) { 11969 SmallVector<Expr *, 8> WorkList; 11970 WorkList.push_back(E); 11971 while (!WorkList.empty()) { 11972 Expr *Item = WorkList.pop_back_val(); 11973 SequenceChecker(*this, Item, WorkList); 11974 } 11975 } 11976 11977 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11978 bool IsConstexpr) { 11979 CheckImplicitConversions(E, CheckLoc); 11980 if (!E->isInstantiationDependent()) 11981 CheckUnsequencedOperations(E); 11982 if (!IsConstexpr && !E->isValueDependent()) 11983 CheckForIntOverflow(E); 11984 DiagnoseMisalignedMembers(); 11985 } 11986 11987 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11988 FieldDecl *BitField, 11989 Expr *Init) { 11990 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11991 } 11992 11993 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11994 SourceLocation Loc) { 11995 if (!PType->isVariablyModifiedType()) 11996 return; 11997 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11998 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11999 return; 12000 } 12001 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12002 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12003 return; 12004 } 12005 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12006 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12007 return; 12008 } 12009 12010 const ArrayType *AT = S.Context.getAsArrayType(PType); 12011 if (!AT) 12012 return; 12013 12014 if (AT->getSizeModifier() != ArrayType::Star) { 12015 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12016 return; 12017 } 12018 12019 S.Diag(Loc, diag::err_array_star_in_function_definition); 12020 } 12021 12022 /// CheckParmsForFunctionDef - Check that the parameters of the given 12023 /// function are appropriate for the definition of a function. This 12024 /// takes care of any checks that cannot be performed on the 12025 /// declaration itself, e.g., that the types of each of the function 12026 /// parameters are complete. 12027 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12028 bool CheckParameterNames) { 12029 bool HasInvalidParm = false; 12030 for (ParmVarDecl *Param : Parameters) { 12031 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12032 // function declarator that is part of a function definition of 12033 // that function shall not have incomplete type. 12034 // 12035 // This is also C++ [dcl.fct]p6. 12036 if (!Param->isInvalidDecl() && 12037 RequireCompleteType(Param->getLocation(), Param->getType(), 12038 diag::err_typecheck_decl_incomplete_type)) { 12039 Param->setInvalidDecl(); 12040 HasInvalidParm = true; 12041 } 12042 12043 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12044 // declaration of each parameter shall include an identifier. 12045 if (CheckParameterNames && 12046 Param->getIdentifier() == nullptr && 12047 !Param->isImplicit() && 12048 !getLangOpts().CPlusPlus) 12049 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12050 12051 // C99 6.7.5.3p12: 12052 // If the function declarator is not part of a definition of that 12053 // function, parameters may have incomplete type and may use the [*] 12054 // notation in their sequences of declarator specifiers to specify 12055 // variable length array types. 12056 QualType PType = Param->getOriginalType(); 12057 // FIXME: This diagnostic should point the '[*]' if source-location 12058 // information is added for it. 12059 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12060 12061 // If the parameter is a c++ class type and it has to be destructed in the 12062 // callee function, declare the destructor so that it can be called by the 12063 // callee function. Do not perform any direct access check on the dtor here. 12064 if (!Param->isInvalidDecl()) { 12065 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12066 if (!ClassDecl->isInvalidDecl() && 12067 !ClassDecl->hasIrrelevantDestructor() && 12068 !ClassDecl->isDependentContext() && 12069 ClassDecl->isParamDestroyedInCallee()) { 12070 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12071 MarkFunctionReferenced(Param->getLocation(), Destructor); 12072 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12073 } 12074 } 12075 } 12076 12077 // Parameters with the pass_object_size attribute only need to be marked 12078 // constant at function definitions. Because we lack information about 12079 // whether we're on a declaration or definition when we're instantiating the 12080 // attribute, we need to check for constness here. 12081 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12082 if (!Param->getType().isConstQualified()) 12083 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12084 << Attr->getSpelling() << 1; 12085 } 12086 12087 return HasInvalidParm; 12088 } 12089 12090 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12091 /// or MemberExpr. 12092 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12093 ASTContext &Context) { 12094 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12095 return Context.getDeclAlign(DRE->getDecl()); 12096 12097 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12098 return Context.getDeclAlign(ME->getMemberDecl()); 12099 12100 return TypeAlign; 12101 } 12102 12103 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12104 /// pointer cast increases the alignment requirements. 12105 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12106 // This is actually a lot of work to potentially be doing on every 12107 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12108 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12109 return; 12110 12111 // Ignore dependent types. 12112 if (T->isDependentType() || Op->getType()->isDependentType()) 12113 return; 12114 12115 // Require that the destination be a pointer type. 12116 const PointerType *DestPtr = T->getAs<PointerType>(); 12117 if (!DestPtr) return; 12118 12119 // If the destination has alignment 1, we're done. 12120 QualType DestPointee = DestPtr->getPointeeType(); 12121 if (DestPointee->isIncompleteType()) return; 12122 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12123 if (DestAlign.isOne()) return; 12124 12125 // Require that the source be a pointer type. 12126 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12127 if (!SrcPtr) return; 12128 QualType SrcPointee = SrcPtr->getPointeeType(); 12129 12130 // Whitelist casts from cv void*. We already implicitly 12131 // whitelisted casts to cv void*, since they have alignment 1. 12132 // Also whitelist casts involving incomplete types, which implicitly 12133 // includes 'void'. 12134 if (SrcPointee->isIncompleteType()) return; 12135 12136 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12137 12138 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12139 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12140 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12141 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12142 if (UO->getOpcode() == UO_AddrOf) 12143 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12144 } 12145 12146 if (SrcAlign >= DestAlign) return; 12147 12148 Diag(TRange.getBegin(), diag::warn_cast_align) 12149 << Op->getType() << T 12150 << static_cast<unsigned>(SrcAlign.getQuantity()) 12151 << static_cast<unsigned>(DestAlign.getQuantity()) 12152 << TRange << Op->getSourceRange(); 12153 } 12154 12155 /// Check whether this array fits the idiom of a size-one tail padded 12156 /// array member of a struct. 12157 /// 12158 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12159 /// commonly used to emulate flexible arrays in C89 code. 12160 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12161 const NamedDecl *ND) { 12162 if (Size != 1 || !ND) return false; 12163 12164 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12165 if (!FD) return false; 12166 12167 // Don't consider sizes resulting from macro expansions or template argument 12168 // substitution to form C89 tail-padded arrays. 12169 12170 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12171 while (TInfo) { 12172 TypeLoc TL = TInfo->getTypeLoc(); 12173 // Look through typedefs. 12174 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12175 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12176 TInfo = TDL->getTypeSourceInfo(); 12177 continue; 12178 } 12179 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12180 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12181 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12182 return false; 12183 } 12184 break; 12185 } 12186 12187 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12188 if (!RD) return false; 12189 if (RD->isUnion()) return false; 12190 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12191 if (!CRD->isStandardLayout()) return false; 12192 } 12193 12194 // See if this is the last field decl in the record. 12195 const Decl *D = FD; 12196 while ((D = D->getNextDeclInContext())) 12197 if (isa<FieldDecl>(D)) 12198 return false; 12199 return true; 12200 } 12201 12202 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12203 const ArraySubscriptExpr *ASE, 12204 bool AllowOnePastEnd, bool IndexNegated) { 12205 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12206 if (IndexExpr->isValueDependent()) 12207 return; 12208 12209 const Type *EffectiveType = 12210 BaseExpr->getType()->getPointeeOrArrayElementType(); 12211 BaseExpr = BaseExpr->IgnoreParenCasts(); 12212 const ConstantArrayType *ArrayTy = 12213 Context.getAsConstantArrayType(BaseExpr->getType()); 12214 if (!ArrayTy) 12215 return; 12216 12217 llvm::APSInt index; 12218 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 12219 return; 12220 if (IndexNegated) 12221 index = -index; 12222 12223 const NamedDecl *ND = nullptr; 12224 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12225 ND = DRE->getDecl(); 12226 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12227 ND = ME->getMemberDecl(); 12228 12229 if (index.isUnsigned() || !index.isNegative()) { 12230 llvm::APInt size = ArrayTy->getSize(); 12231 if (!size.isStrictlyPositive()) 12232 return; 12233 12234 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 12235 if (BaseType != EffectiveType) { 12236 // Make sure we're comparing apples to apples when comparing index to size 12237 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12238 uint64_t array_typesize = Context.getTypeSize(BaseType); 12239 // Handle ptrarith_typesize being zero, such as when casting to void* 12240 if (!ptrarith_typesize) ptrarith_typesize = 1; 12241 if (ptrarith_typesize != array_typesize) { 12242 // There's a cast to a different size type involved 12243 uint64_t ratio = array_typesize / ptrarith_typesize; 12244 // TODO: Be smarter about handling cases where array_typesize is not a 12245 // multiple of ptrarith_typesize 12246 if (ptrarith_typesize * ratio == array_typesize) 12247 size *= llvm::APInt(size.getBitWidth(), ratio); 12248 } 12249 } 12250 12251 if (size.getBitWidth() > index.getBitWidth()) 12252 index = index.zext(size.getBitWidth()); 12253 else if (size.getBitWidth() < index.getBitWidth()) 12254 size = size.zext(index.getBitWidth()); 12255 12256 // For array subscripting the index must be less than size, but for pointer 12257 // arithmetic also allow the index (offset) to be equal to size since 12258 // computing the next address after the end of the array is legal and 12259 // commonly done e.g. in C++ iterators and range-based for loops. 12260 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12261 return; 12262 12263 // Also don't warn for arrays of size 1 which are members of some 12264 // structure. These are often used to approximate flexible arrays in C89 12265 // code. 12266 if (IsTailPaddedMemberArray(*this, size, ND)) 12267 return; 12268 12269 // Suppress the warning if the subscript expression (as identified by the 12270 // ']' location) and the index expression are both from macro expansions 12271 // within a system header. 12272 if (ASE) { 12273 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12274 ASE->getRBracketLoc()); 12275 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12276 SourceLocation IndexLoc = 12277 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12278 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12279 return; 12280 } 12281 } 12282 12283 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12284 if (ASE) 12285 DiagID = diag::warn_array_index_exceeds_bounds; 12286 12287 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12288 PDiag(DiagID) << index.toString(10, true) 12289 << size.toString(10, true) 12290 << (unsigned)size.getLimitedValue(~0U) 12291 << IndexExpr->getSourceRange()); 12292 } else { 12293 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12294 if (!ASE) { 12295 DiagID = diag::warn_ptr_arith_precedes_bounds; 12296 if (index.isNegative()) index = -index; 12297 } 12298 12299 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12300 PDiag(DiagID) << index.toString(10, true) 12301 << IndexExpr->getSourceRange()); 12302 } 12303 12304 if (!ND) { 12305 // Try harder to find a NamedDecl to point at in the note. 12306 while (const ArraySubscriptExpr *ASE = 12307 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12308 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12309 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12310 ND = DRE->getDecl(); 12311 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12312 ND = ME->getMemberDecl(); 12313 } 12314 12315 if (ND) 12316 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12317 PDiag(diag::note_array_index_out_of_bounds) 12318 << ND->getDeclName()); 12319 } 12320 12321 void Sema::CheckArrayAccess(const Expr *expr) { 12322 int AllowOnePastEnd = 0; 12323 while (expr) { 12324 expr = expr->IgnoreParenImpCasts(); 12325 switch (expr->getStmtClass()) { 12326 case Stmt::ArraySubscriptExprClass: { 12327 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12328 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12329 AllowOnePastEnd > 0); 12330 expr = ASE->getBase(); 12331 break; 12332 } 12333 case Stmt::MemberExprClass: { 12334 expr = cast<MemberExpr>(expr)->getBase(); 12335 break; 12336 } 12337 case Stmt::OMPArraySectionExprClass: { 12338 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12339 if (ASE->getLowerBound()) 12340 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12341 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12342 return; 12343 } 12344 case Stmt::UnaryOperatorClass: { 12345 // Only unwrap the * and & unary operators 12346 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12347 expr = UO->getSubExpr(); 12348 switch (UO->getOpcode()) { 12349 case UO_AddrOf: 12350 AllowOnePastEnd++; 12351 break; 12352 case UO_Deref: 12353 AllowOnePastEnd--; 12354 break; 12355 default: 12356 return; 12357 } 12358 break; 12359 } 12360 case Stmt::ConditionalOperatorClass: { 12361 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12362 if (const Expr *lhs = cond->getLHS()) 12363 CheckArrayAccess(lhs); 12364 if (const Expr *rhs = cond->getRHS()) 12365 CheckArrayAccess(rhs); 12366 return; 12367 } 12368 case Stmt::CXXOperatorCallExprClass: { 12369 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12370 for (const auto *Arg : OCE->arguments()) 12371 CheckArrayAccess(Arg); 12372 return; 12373 } 12374 default: 12375 return; 12376 } 12377 } 12378 } 12379 12380 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12381 12382 namespace { 12383 12384 struct RetainCycleOwner { 12385 VarDecl *Variable = nullptr; 12386 SourceRange Range; 12387 SourceLocation Loc; 12388 bool Indirect = false; 12389 12390 RetainCycleOwner() = default; 12391 12392 void setLocsFrom(Expr *e) { 12393 Loc = e->getExprLoc(); 12394 Range = e->getSourceRange(); 12395 } 12396 }; 12397 12398 } // namespace 12399 12400 /// Consider whether capturing the given variable can possibly lead to 12401 /// a retain cycle. 12402 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12403 // In ARC, it's captured strongly iff the variable has __strong 12404 // lifetime. In MRR, it's captured strongly if the variable is 12405 // __block and has an appropriate type. 12406 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12407 return false; 12408 12409 owner.Variable = var; 12410 if (ref) 12411 owner.setLocsFrom(ref); 12412 return true; 12413 } 12414 12415 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12416 while (true) { 12417 e = e->IgnoreParens(); 12418 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12419 switch (cast->getCastKind()) { 12420 case CK_BitCast: 12421 case CK_LValueBitCast: 12422 case CK_LValueToRValue: 12423 case CK_ARCReclaimReturnedObject: 12424 e = cast->getSubExpr(); 12425 continue; 12426 12427 default: 12428 return false; 12429 } 12430 } 12431 12432 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12433 ObjCIvarDecl *ivar = ref->getDecl(); 12434 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12435 return false; 12436 12437 // Try to find a retain cycle in the base. 12438 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12439 return false; 12440 12441 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12442 owner.Indirect = true; 12443 return true; 12444 } 12445 12446 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12447 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12448 if (!var) return false; 12449 return considerVariable(var, ref, owner); 12450 } 12451 12452 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12453 if (member->isArrow()) return false; 12454 12455 // Don't count this as an indirect ownership. 12456 e = member->getBase(); 12457 continue; 12458 } 12459 12460 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12461 // Only pay attention to pseudo-objects on property references. 12462 ObjCPropertyRefExpr *pre 12463 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12464 ->IgnoreParens()); 12465 if (!pre) return false; 12466 if (pre->isImplicitProperty()) return false; 12467 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12468 if (!property->isRetaining() && 12469 !(property->getPropertyIvarDecl() && 12470 property->getPropertyIvarDecl()->getType() 12471 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12472 return false; 12473 12474 owner.Indirect = true; 12475 if (pre->isSuperReceiver()) { 12476 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12477 if (!owner.Variable) 12478 return false; 12479 owner.Loc = pre->getLocation(); 12480 owner.Range = pre->getSourceRange(); 12481 return true; 12482 } 12483 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12484 ->getSourceExpr()); 12485 continue; 12486 } 12487 12488 // Array ivars? 12489 12490 return false; 12491 } 12492 } 12493 12494 namespace { 12495 12496 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12497 ASTContext &Context; 12498 VarDecl *Variable; 12499 Expr *Capturer = nullptr; 12500 bool VarWillBeReased = false; 12501 12502 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12503 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12504 Context(Context), Variable(variable) {} 12505 12506 void VisitDeclRefExpr(DeclRefExpr *ref) { 12507 if (ref->getDecl() == Variable && !Capturer) 12508 Capturer = ref; 12509 } 12510 12511 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12512 if (Capturer) return; 12513 Visit(ref->getBase()); 12514 if (Capturer && ref->isFreeIvar()) 12515 Capturer = ref; 12516 } 12517 12518 void VisitBlockExpr(BlockExpr *block) { 12519 // Look inside nested blocks 12520 if (block->getBlockDecl()->capturesVariable(Variable)) 12521 Visit(block->getBlockDecl()->getBody()); 12522 } 12523 12524 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12525 if (Capturer) return; 12526 if (OVE->getSourceExpr()) 12527 Visit(OVE->getSourceExpr()); 12528 } 12529 12530 void VisitBinaryOperator(BinaryOperator *BinOp) { 12531 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12532 return; 12533 Expr *LHS = BinOp->getLHS(); 12534 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12535 if (DRE->getDecl() != Variable) 12536 return; 12537 if (Expr *RHS = BinOp->getRHS()) { 12538 RHS = RHS->IgnoreParenCasts(); 12539 llvm::APSInt Value; 12540 VarWillBeReased = 12541 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12542 } 12543 } 12544 } 12545 }; 12546 12547 } // namespace 12548 12549 /// Check whether the given argument is a block which captures a 12550 /// variable. 12551 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12552 assert(owner.Variable && owner.Loc.isValid()); 12553 12554 e = e->IgnoreParenCasts(); 12555 12556 // Look through [^{...} copy] and Block_copy(^{...}). 12557 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12558 Selector Cmd = ME->getSelector(); 12559 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12560 e = ME->getInstanceReceiver(); 12561 if (!e) 12562 return nullptr; 12563 e = e->IgnoreParenCasts(); 12564 } 12565 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12566 if (CE->getNumArgs() == 1) { 12567 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12568 if (Fn) { 12569 const IdentifierInfo *FnI = Fn->getIdentifier(); 12570 if (FnI && FnI->isStr("_Block_copy")) { 12571 e = CE->getArg(0)->IgnoreParenCasts(); 12572 } 12573 } 12574 } 12575 } 12576 12577 BlockExpr *block = dyn_cast<BlockExpr>(e); 12578 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12579 return nullptr; 12580 12581 FindCaptureVisitor visitor(S.Context, owner.Variable); 12582 visitor.Visit(block->getBlockDecl()->getBody()); 12583 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12584 } 12585 12586 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12587 RetainCycleOwner &owner) { 12588 assert(capturer); 12589 assert(owner.Variable && owner.Loc.isValid()); 12590 12591 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12592 << owner.Variable << capturer->getSourceRange(); 12593 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12594 << owner.Indirect << owner.Range; 12595 } 12596 12597 /// Check for a keyword selector that starts with the word 'add' or 12598 /// 'set'. 12599 static bool isSetterLikeSelector(Selector sel) { 12600 if (sel.isUnarySelector()) return false; 12601 12602 StringRef str = sel.getNameForSlot(0); 12603 while (!str.empty() && str.front() == '_') str = str.substr(1); 12604 if (str.startswith("set")) 12605 str = str.substr(3); 12606 else if (str.startswith("add")) { 12607 // Specially whitelist 'addOperationWithBlock:'. 12608 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12609 return false; 12610 str = str.substr(3); 12611 } 12612 else 12613 return false; 12614 12615 if (str.empty()) return true; 12616 return !isLowercase(str.front()); 12617 } 12618 12619 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12620 ObjCMessageExpr *Message) { 12621 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12622 Message->getReceiverInterface(), 12623 NSAPI::ClassId_NSMutableArray); 12624 if (!IsMutableArray) { 12625 return None; 12626 } 12627 12628 Selector Sel = Message->getSelector(); 12629 12630 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12631 S.NSAPIObj->getNSArrayMethodKind(Sel); 12632 if (!MKOpt) { 12633 return None; 12634 } 12635 12636 NSAPI::NSArrayMethodKind MK = *MKOpt; 12637 12638 switch (MK) { 12639 case NSAPI::NSMutableArr_addObject: 12640 case NSAPI::NSMutableArr_insertObjectAtIndex: 12641 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12642 return 0; 12643 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12644 return 1; 12645 12646 default: 12647 return None; 12648 } 12649 12650 return None; 12651 } 12652 12653 static 12654 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12655 ObjCMessageExpr *Message) { 12656 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12657 Message->getReceiverInterface(), 12658 NSAPI::ClassId_NSMutableDictionary); 12659 if (!IsMutableDictionary) { 12660 return None; 12661 } 12662 12663 Selector Sel = Message->getSelector(); 12664 12665 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12666 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12667 if (!MKOpt) { 12668 return None; 12669 } 12670 12671 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12672 12673 switch (MK) { 12674 case NSAPI::NSMutableDict_setObjectForKey: 12675 case NSAPI::NSMutableDict_setValueForKey: 12676 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12677 return 0; 12678 12679 default: 12680 return None; 12681 } 12682 12683 return None; 12684 } 12685 12686 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12687 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12688 Message->getReceiverInterface(), 12689 NSAPI::ClassId_NSMutableSet); 12690 12691 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12692 Message->getReceiverInterface(), 12693 NSAPI::ClassId_NSMutableOrderedSet); 12694 if (!IsMutableSet && !IsMutableOrderedSet) { 12695 return None; 12696 } 12697 12698 Selector Sel = Message->getSelector(); 12699 12700 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12701 if (!MKOpt) { 12702 return None; 12703 } 12704 12705 NSAPI::NSSetMethodKind MK = *MKOpt; 12706 12707 switch (MK) { 12708 case NSAPI::NSMutableSet_addObject: 12709 case NSAPI::NSOrderedSet_setObjectAtIndex: 12710 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12711 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12712 return 0; 12713 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12714 return 1; 12715 } 12716 12717 return None; 12718 } 12719 12720 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12721 if (!Message->isInstanceMessage()) { 12722 return; 12723 } 12724 12725 Optional<int> ArgOpt; 12726 12727 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12728 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12729 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12730 return; 12731 } 12732 12733 int ArgIndex = *ArgOpt; 12734 12735 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12736 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12737 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12738 } 12739 12740 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12741 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12742 if (ArgRE->isObjCSelfExpr()) { 12743 Diag(Message->getSourceRange().getBegin(), 12744 diag::warn_objc_circular_container) 12745 << ArgRE->getDecl() << StringRef("'super'"); 12746 } 12747 } 12748 } else { 12749 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12750 12751 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12752 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12753 } 12754 12755 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12756 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12757 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12758 ValueDecl *Decl = ReceiverRE->getDecl(); 12759 Diag(Message->getSourceRange().getBegin(), 12760 diag::warn_objc_circular_container) 12761 << Decl << Decl; 12762 if (!ArgRE->isObjCSelfExpr()) { 12763 Diag(Decl->getLocation(), 12764 diag::note_objc_circular_container_declared_here) 12765 << Decl; 12766 } 12767 } 12768 } 12769 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12770 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12771 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12772 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12773 Diag(Message->getSourceRange().getBegin(), 12774 diag::warn_objc_circular_container) 12775 << Decl << Decl; 12776 Diag(Decl->getLocation(), 12777 diag::note_objc_circular_container_declared_here) 12778 << Decl; 12779 } 12780 } 12781 } 12782 } 12783 } 12784 12785 /// Check a message send to see if it's likely to cause a retain cycle. 12786 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12787 // Only check instance methods whose selector looks like a setter. 12788 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12789 return; 12790 12791 // Try to find a variable that the receiver is strongly owned by. 12792 RetainCycleOwner owner; 12793 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12794 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12795 return; 12796 } else { 12797 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12798 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12799 owner.Loc = msg->getSuperLoc(); 12800 owner.Range = msg->getSuperLoc(); 12801 } 12802 12803 // Check whether the receiver is captured by any of the arguments. 12804 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12805 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12806 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12807 // noescape blocks should not be retained by the method. 12808 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12809 continue; 12810 return diagnoseRetainCycle(*this, capturer, owner); 12811 } 12812 } 12813 } 12814 12815 /// Check a property assign to see if it's likely to cause a retain cycle. 12816 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12817 RetainCycleOwner owner; 12818 if (!findRetainCycleOwner(*this, receiver, owner)) 12819 return; 12820 12821 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12822 diagnoseRetainCycle(*this, capturer, owner); 12823 } 12824 12825 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12826 RetainCycleOwner Owner; 12827 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12828 return; 12829 12830 // Because we don't have an expression for the variable, we have to set the 12831 // location explicitly here. 12832 Owner.Loc = Var->getLocation(); 12833 Owner.Range = Var->getSourceRange(); 12834 12835 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12836 diagnoseRetainCycle(*this, Capturer, Owner); 12837 } 12838 12839 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12840 Expr *RHS, bool isProperty) { 12841 // Check if RHS is an Objective-C object literal, which also can get 12842 // immediately zapped in a weak reference. Note that we explicitly 12843 // allow ObjCStringLiterals, since those are designed to never really die. 12844 RHS = RHS->IgnoreParenImpCasts(); 12845 12846 // This enum needs to match with the 'select' in 12847 // warn_objc_arc_literal_assign (off-by-1). 12848 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12849 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12850 return false; 12851 12852 S.Diag(Loc, diag::warn_arc_literal_assign) 12853 << (unsigned) Kind 12854 << (isProperty ? 0 : 1) 12855 << RHS->getSourceRange(); 12856 12857 return true; 12858 } 12859 12860 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12861 Qualifiers::ObjCLifetime LT, 12862 Expr *RHS, bool isProperty) { 12863 // Strip off any implicit cast added to get to the one ARC-specific. 12864 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12865 if (cast->getCastKind() == CK_ARCConsumeObject) { 12866 S.Diag(Loc, diag::warn_arc_retained_assign) 12867 << (LT == Qualifiers::OCL_ExplicitNone) 12868 << (isProperty ? 0 : 1) 12869 << RHS->getSourceRange(); 12870 return true; 12871 } 12872 RHS = cast->getSubExpr(); 12873 } 12874 12875 if (LT == Qualifiers::OCL_Weak && 12876 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12877 return true; 12878 12879 return false; 12880 } 12881 12882 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12883 QualType LHS, Expr *RHS) { 12884 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12885 12886 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12887 return false; 12888 12889 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12890 return true; 12891 12892 return false; 12893 } 12894 12895 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12896 Expr *LHS, Expr *RHS) { 12897 QualType LHSType; 12898 // PropertyRef on LHS type need be directly obtained from 12899 // its declaration as it has a PseudoType. 12900 ObjCPropertyRefExpr *PRE 12901 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12902 if (PRE && !PRE->isImplicitProperty()) { 12903 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12904 if (PD) 12905 LHSType = PD->getType(); 12906 } 12907 12908 if (LHSType.isNull()) 12909 LHSType = LHS->getType(); 12910 12911 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12912 12913 if (LT == Qualifiers::OCL_Weak) { 12914 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12915 getCurFunction()->markSafeWeakUse(LHS); 12916 } 12917 12918 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12919 return; 12920 12921 // FIXME. Check for other life times. 12922 if (LT != Qualifiers::OCL_None) 12923 return; 12924 12925 if (PRE) { 12926 if (PRE->isImplicitProperty()) 12927 return; 12928 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12929 if (!PD) 12930 return; 12931 12932 unsigned Attributes = PD->getPropertyAttributes(); 12933 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12934 // when 'assign' attribute was not explicitly specified 12935 // by user, ignore it and rely on property type itself 12936 // for lifetime info. 12937 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12938 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12939 LHSType->isObjCRetainableType()) 12940 return; 12941 12942 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12943 if (cast->getCastKind() == CK_ARCConsumeObject) { 12944 Diag(Loc, diag::warn_arc_retained_property_assign) 12945 << RHS->getSourceRange(); 12946 return; 12947 } 12948 RHS = cast->getSubExpr(); 12949 } 12950 } 12951 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12952 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12953 return; 12954 } 12955 } 12956 } 12957 12958 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12959 12960 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12961 SourceLocation StmtLoc, 12962 const NullStmt *Body) { 12963 // Do not warn if the body is a macro that expands to nothing, e.g: 12964 // 12965 // #define CALL(x) 12966 // if (condition) 12967 // CALL(0); 12968 if (Body->hasLeadingEmptyMacro()) 12969 return false; 12970 12971 // Get line numbers of statement and body. 12972 bool StmtLineInvalid; 12973 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12974 &StmtLineInvalid); 12975 if (StmtLineInvalid) 12976 return false; 12977 12978 bool BodyLineInvalid; 12979 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12980 &BodyLineInvalid); 12981 if (BodyLineInvalid) 12982 return false; 12983 12984 // Warn if null statement and body are on the same line. 12985 if (StmtLine != BodyLine) 12986 return false; 12987 12988 return true; 12989 } 12990 12991 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12992 const Stmt *Body, 12993 unsigned DiagID) { 12994 // Since this is a syntactic check, don't emit diagnostic for template 12995 // instantiations, this just adds noise. 12996 if (CurrentInstantiationScope) 12997 return; 12998 12999 // The body should be a null statement. 13000 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13001 if (!NBody) 13002 return; 13003 13004 // Do the usual checks. 13005 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13006 return; 13007 13008 Diag(NBody->getSemiLoc(), DiagID); 13009 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13010 } 13011 13012 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13013 const Stmt *PossibleBody) { 13014 assert(!CurrentInstantiationScope); // Ensured by caller 13015 13016 SourceLocation StmtLoc; 13017 const Stmt *Body; 13018 unsigned DiagID; 13019 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13020 StmtLoc = FS->getRParenLoc(); 13021 Body = FS->getBody(); 13022 DiagID = diag::warn_empty_for_body; 13023 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13024 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13025 Body = WS->getBody(); 13026 DiagID = diag::warn_empty_while_body; 13027 } else 13028 return; // Neither `for' nor `while'. 13029 13030 // The body should be a null statement. 13031 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13032 if (!NBody) 13033 return; 13034 13035 // Skip expensive checks if diagnostic is disabled. 13036 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13037 return; 13038 13039 // Do the usual checks. 13040 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13041 return; 13042 13043 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13044 // noise level low, emit diagnostics only if for/while is followed by a 13045 // CompoundStmt, e.g.: 13046 // for (int i = 0; i < n; i++); 13047 // { 13048 // a(i); 13049 // } 13050 // or if for/while is followed by a statement with more indentation 13051 // than for/while itself: 13052 // for (int i = 0; i < n; i++); 13053 // a(i); 13054 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13055 if (!ProbableTypo) { 13056 bool BodyColInvalid; 13057 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13058 PossibleBody->getBeginLoc(), &BodyColInvalid); 13059 if (BodyColInvalid) 13060 return; 13061 13062 bool StmtColInvalid; 13063 unsigned StmtCol = 13064 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13065 if (StmtColInvalid) 13066 return; 13067 13068 if (BodyCol > StmtCol) 13069 ProbableTypo = true; 13070 } 13071 13072 if (ProbableTypo) { 13073 Diag(NBody->getSemiLoc(), DiagID); 13074 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13075 } 13076 } 13077 13078 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13079 13080 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13081 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13082 SourceLocation OpLoc) { 13083 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13084 return; 13085 13086 if (inTemplateInstantiation()) 13087 return; 13088 13089 // Strip parens and casts away. 13090 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13091 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13092 13093 // Check for a call expression 13094 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13095 if (!CE || CE->getNumArgs() != 1) 13096 return; 13097 13098 // Check for a call to std::move 13099 if (!CE->isCallToStdMove()) 13100 return; 13101 13102 // Get argument from std::move 13103 RHSExpr = CE->getArg(0); 13104 13105 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13106 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13107 13108 // Two DeclRefExpr's, check that the decls are the same. 13109 if (LHSDeclRef && RHSDeclRef) { 13110 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13111 return; 13112 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13113 RHSDeclRef->getDecl()->getCanonicalDecl()) 13114 return; 13115 13116 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13117 << LHSExpr->getSourceRange() 13118 << RHSExpr->getSourceRange(); 13119 return; 13120 } 13121 13122 // Member variables require a different approach to check for self moves. 13123 // MemberExpr's are the same if every nested MemberExpr refers to the same 13124 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13125 // the base Expr's are CXXThisExpr's. 13126 const Expr *LHSBase = LHSExpr; 13127 const Expr *RHSBase = RHSExpr; 13128 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13129 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13130 if (!LHSME || !RHSME) 13131 return; 13132 13133 while (LHSME && RHSME) { 13134 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13135 RHSME->getMemberDecl()->getCanonicalDecl()) 13136 return; 13137 13138 LHSBase = LHSME->getBase(); 13139 RHSBase = RHSME->getBase(); 13140 LHSME = dyn_cast<MemberExpr>(LHSBase); 13141 RHSME = dyn_cast<MemberExpr>(RHSBase); 13142 } 13143 13144 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13145 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13146 if (LHSDeclRef && RHSDeclRef) { 13147 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13148 return; 13149 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13150 RHSDeclRef->getDecl()->getCanonicalDecl()) 13151 return; 13152 13153 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13154 << LHSExpr->getSourceRange() 13155 << RHSExpr->getSourceRange(); 13156 return; 13157 } 13158 13159 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13160 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13161 << LHSExpr->getSourceRange() 13162 << RHSExpr->getSourceRange(); 13163 } 13164 13165 //===--- Layout compatibility ----------------------------------------------// 13166 13167 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13168 13169 /// Check if two enumeration types are layout-compatible. 13170 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13171 // C++11 [dcl.enum] p8: 13172 // Two enumeration types are layout-compatible if they have the same 13173 // underlying type. 13174 return ED1->isComplete() && ED2->isComplete() && 13175 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13176 } 13177 13178 /// Check if two fields are layout-compatible. 13179 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13180 FieldDecl *Field2) { 13181 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13182 return false; 13183 13184 if (Field1->isBitField() != Field2->isBitField()) 13185 return false; 13186 13187 if (Field1->isBitField()) { 13188 // Make sure that the bit-fields are the same length. 13189 unsigned Bits1 = Field1->getBitWidthValue(C); 13190 unsigned Bits2 = Field2->getBitWidthValue(C); 13191 13192 if (Bits1 != Bits2) 13193 return false; 13194 } 13195 13196 return true; 13197 } 13198 13199 /// Check if two standard-layout structs are layout-compatible. 13200 /// (C++11 [class.mem] p17) 13201 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13202 RecordDecl *RD2) { 13203 // If both records are C++ classes, check that base classes match. 13204 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13205 // If one of records is a CXXRecordDecl we are in C++ mode, 13206 // thus the other one is a CXXRecordDecl, too. 13207 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13208 // Check number of base classes. 13209 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13210 return false; 13211 13212 // Check the base classes. 13213 for (CXXRecordDecl::base_class_const_iterator 13214 Base1 = D1CXX->bases_begin(), 13215 BaseEnd1 = D1CXX->bases_end(), 13216 Base2 = D2CXX->bases_begin(); 13217 Base1 != BaseEnd1; 13218 ++Base1, ++Base2) { 13219 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13220 return false; 13221 } 13222 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13223 // If only RD2 is a C++ class, it should have zero base classes. 13224 if (D2CXX->getNumBases() > 0) 13225 return false; 13226 } 13227 13228 // Check the fields. 13229 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13230 Field2End = RD2->field_end(), 13231 Field1 = RD1->field_begin(), 13232 Field1End = RD1->field_end(); 13233 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13234 if (!isLayoutCompatible(C, *Field1, *Field2)) 13235 return false; 13236 } 13237 if (Field1 != Field1End || Field2 != Field2End) 13238 return false; 13239 13240 return true; 13241 } 13242 13243 /// Check if two standard-layout unions are layout-compatible. 13244 /// (C++11 [class.mem] p18) 13245 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13246 RecordDecl *RD2) { 13247 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13248 for (auto *Field2 : RD2->fields()) 13249 UnmatchedFields.insert(Field2); 13250 13251 for (auto *Field1 : RD1->fields()) { 13252 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13253 I = UnmatchedFields.begin(), 13254 E = UnmatchedFields.end(); 13255 13256 for ( ; I != E; ++I) { 13257 if (isLayoutCompatible(C, Field1, *I)) { 13258 bool Result = UnmatchedFields.erase(*I); 13259 (void) Result; 13260 assert(Result); 13261 break; 13262 } 13263 } 13264 if (I == E) 13265 return false; 13266 } 13267 13268 return UnmatchedFields.empty(); 13269 } 13270 13271 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13272 RecordDecl *RD2) { 13273 if (RD1->isUnion() != RD2->isUnion()) 13274 return false; 13275 13276 if (RD1->isUnion()) 13277 return isLayoutCompatibleUnion(C, RD1, RD2); 13278 else 13279 return isLayoutCompatibleStruct(C, RD1, RD2); 13280 } 13281 13282 /// Check if two types are layout-compatible in C++11 sense. 13283 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13284 if (T1.isNull() || T2.isNull()) 13285 return false; 13286 13287 // C++11 [basic.types] p11: 13288 // If two types T1 and T2 are the same type, then T1 and T2 are 13289 // layout-compatible types. 13290 if (C.hasSameType(T1, T2)) 13291 return true; 13292 13293 T1 = T1.getCanonicalType().getUnqualifiedType(); 13294 T2 = T2.getCanonicalType().getUnqualifiedType(); 13295 13296 const Type::TypeClass TC1 = T1->getTypeClass(); 13297 const Type::TypeClass TC2 = T2->getTypeClass(); 13298 13299 if (TC1 != TC2) 13300 return false; 13301 13302 if (TC1 == Type::Enum) { 13303 return isLayoutCompatible(C, 13304 cast<EnumType>(T1)->getDecl(), 13305 cast<EnumType>(T2)->getDecl()); 13306 } else if (TC1 == Type::Record) { 13307 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13308 return false; 13309 13310 return isLayoutCompatible(C, 13311 cast<RecordType>(T1)->getDecl(), 13312 cast<RecordType>(T2)->getDecl()); 13313 } 13314 13315 return false; 13316 } 13317 13318 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13319 13320 /// Given a type tag expression find the type tag itself. 13321 /// 13322 /// \param TypeExpr Type tag expression, as it appears in user's code. 13323 /// 13324 /// \param VD Declaration of an identifier that appears in a type tag. 13325 /// 13326 /// \param MagicValue Type tag magic value. 13327 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13328 const ValueDecl **VD, uint64_t *MagicValue) { 13329 while(true) { 13330 if (!TypeExpr) 13331 return false; 13332 13333 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13334 13335 switch (TypeExpr->getStmtClass()) { 13336 case Stmt::UnaryOperatorClass: { 13337 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13338 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13339 TypeExpr = UO->getSubExpr(); 13340 continue; 13341 } 13342 return false; 13343 } 13344 13345 case Stmt::DeclRefExprClass: { 13346 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13347 *VD = DRE->getDecl(); 13348 return true; 13349 } 13350 13351 case Stmt::IntegerLiteralClass: { 13352 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13353 llvm::APInt MagicValueAPInt = IL->getValue(); 13354 if (MagicValueAPInt.getActiveBits() <= 64) { 13355 *MagicValue = MagicValueAPInt.getZExtValue(); 13356 return true; 13357 } else 13358 return false; 13359 } 13360 13361 case Stmt::BinaryConditionalOperatorClass: 13362 case Stmt::ConditionalOperatorClass: { 13363 const AbstractConditionalOperator *ACO = 13364 cast<AbstractConditionalOperator>(TypeExpr); 13365 bool Result; 13366 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13367 if (Result) 13368 TypeExpr = ACO->getTrueExpr(); 13369 else 13370 TypeExpr = ACO->getFalseExpr(); 13371 continue; 13372 } 13373 return false; 13374 } 13375 13376 case Stmt::BinaryOperatorClass: { 13377 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13378 if (BO->getOpcode() == BO_Comma) { 13379 TypeExpr = BO->getRHS(); 13380 continue; 13381 } 13382 return false; 13383 } 13384 13385 default: 13386 return false; 13387 } 13388 } 13389 } 13390 13391 /// Retrieve the C type corresponding to type tag TypeExpr. 13392 /// 13393 /// \param TypeExpr Expression that specifies a type tag. 13394 /// 13395 /// \param MagicValues Registered magic values. 13396 /// 13397 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13398 /// kind. 13399 /// 13400 /// \param TypeInfo Information about the corresponding C type. 13401 /// 13402 /// \returns true if the corresponding C type was found. 13403 static bool GetMatchingCType( 13404 const IdentifierInfo *ArgumentKind, 13405 const Expr *TypeExpr, const ASTContext &Ctx, 13406 const llvm::DenseMap<Sema::TypeTagMagicValue, 13407 Sema::TypeTagData> *MagicValues, 13408 bool &FoundWrongKind, 13409 Sema::TypeTagData &TypeInfo) { 13410 FoundWrongKind = false; 13411 13412 // Variable declaration that has type_tag_for_datatype attribute. 13413 const ValueDecl *VD = nullptr; 13414 13415 uint64_t MagicValue; 13416 13417 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13418 return false; 13419 13420 if (VD) { 13421 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13422 if (I->getArgumentKind() != ArgumentKind) { 13423 FoundWrongKind = true; 13424 return false; 13425 } 13426 TypeInfo.Type = I->getMatchingCType(); 13427 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13428 TypeInfo.MustBeNull = I->getMustBeNull(); 13429 return true; 13430 } 13431 return false; 13432 } 13433 13434 if (!MagicValues) 13435 return false; 13436 13437 llvm::DenseMap<Sema::TypeTagMagicValue, 13438 Sema::TypeTagData>::const_iterator I = 13439 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13440 if (I == MagicValues->end()) 13441 return false; 13442 13443 TypeInfo = I->second; 13444 return true; 13445 } 13446 13447 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13448 uint64_t MagicValue, QualType Type, 13449 bool LayoutCompatible, 13450 bool MustBeNull) { 13451 if (!TypeTagForDatatypeMagicValues) 13452 TypeTagForDatatypeMagicValues.reset( 13453 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13454 13455 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13456 (*TypeTagForDatatypeMagicValues)[Magic] = 13457 TypeTagData(Type, LayoutCompatible, MustBeNull); 13458 } 13459 13460 static bool IsSameCharType(QualType T1, QualType T2) { 13461 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13462 if (!BT1) 13463 return false; 13464 13465 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13466 if (!BT2) 13467 return false; 13468 13469 BuiltinType::Kind T1Kind = BT1->getKind(); 13470 BuiltinType::Kind T2Kind = BT2->getKind(); 13471 13472 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13473 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13474 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13475 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13476 } 13477 13478 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13479 const ArrayRef<const Expr *> ExprArgs, 13480 SourceLocation CallSiteLoc) { 13481 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13482 bool IsPointerAttr = Attr->getIsPointer(); 13483 13484 // Retrieve the argument representing the 'type_tag'. 13485 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13486 if (TypeTagIdxAST >= ExprArgs.size()) { 13487 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13488 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13489 return; 13490 } 13491 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13492 bool FoundWrongKind; 13493 TypeTagData TypeInfo; 13494 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13495 TypeTagForDatatypeMagicValues.get(), 13496 FoundWrongKind, TypeInfo)) { 13497 if (FoundWrongKind) 13498 Diag(TypeTagExpr->getExprLoc(), 13499 diag::warn_type_tag_for_datatype_wrong_kind) 13500 << TypeTagExpr->getSourceRange(); 13501 return; 13502 } 13503 13504 // Retrieve the argument representing the 'arg_idx'. 13505 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13506 if (ArgumentIdxAST >= ExprArgs.size()) { 13507 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13508 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13509 return; 13510 } 13511 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13512 if (IsPointerAttr) { 13513 // Skip implicit cast of pointer to `void *' (as a function argument). 13514 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13515 if (ICE->getType()->isVoidPointerType() && 13516 ICE->getCastKind() == CK_BitCast) 13517 ArgumentExpr = ICE->getSubExpr(); 13518 } 13519 QualType ArgumentType = ArgumentExpr->getType(); 13520 13521 // Passing a `void*' pointer shouldn't trigger a warning. 13522 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13523 return; 13524 13525 if (TypeInfo.MustBeNull) { 13526 // Type tag with matching void type requires a null pointer. 13527 if (!ArgumentExpr->isNullPointerConstant(Context, 13528 Expr::NPC_ValueDependentIsNotNull)) { 13529 Diag(ArgumentExpr->getExprLoc(), 13530 diag::warn_type_safety_null_pointer_required) 13531 << ArgumentKind->getName() 13532 << ArgumentExpr->getSourceRange() 13533 << TypeTagExpr->getSourceRange(); 13534 } 13535 return; 13536 } 13537 13538 QualType RequiredType = TypeInfo.Type; 13539 if (IsPointerAttr) 13540 RequiredType = Context.getPointerType(RequiredType); 13541 13542 bool mismatch = false; 13543 if (!TypeInfo.LayoutCompatible) { 13544 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13545 13546 // C++11 [basic.fundamental] p1: 13547 // Plain char, signed char, and unsigned char are three distinct types. 13548 // 13549 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13550 // char' depending on the current char signedness mode. 13551 if (mismatch) 13552 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13553 RequiredType->getPointeeType())) || 13554 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13555 mismatch = false; 13556 } else 13557 if (IsPointerAttr) 13558 mismatch = !isLayoutCompatible(Context, 13559 ArgumentType->getPointeeType(), 13560 RequiredType->getPointeeType()); 13561 else 13562 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13563 13564 if (mismatch) 13565 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13566 << ArgumentType << ArgumentKind 13567 << TypeInfo.LayoutCompatible << RequiredType 13568 << ArgumentExpr->getSourceRange() 13569 << TypeTagExpr->getSourceRange(); 13570 } 13571 13572 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13573 CharUnits Alignment) { 13574 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13575 } 13576 13577 void Sema::DiagnoseMisalignedMembers() { 13578 for (MisalignedMember &m : MisalignedMembers) { 13579 const NamedDecl *ND = m.RD; 13580 if (ND->getName().empty()) { 13581 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13582 ND = TD; 13583 } 13584 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13585 << m.MD << ND << m.E->getSourceRange(); 13586 } 13587 MisalignedMembers.clear(); 13588 } 13589 13590 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13591 E = E->IgnoreParens(); 13592 if (!T->isPointerType() && !T->isIntegerType()) 13593 return; 13594 if (isa<UnaryOperator>(E) && 13595 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13596 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13597 if (isa<MemberExpr>(Op)) { 13598 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13599 MisalignedMember(Op)); 13600 if (MA != MisalignedMembers.end() && 13601 (T->isIntegerType() || 13602 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13603 Context.getTypeAlignInChars( 13604 T->getPointeeType()) <= MA->Alignment)))) 13605 MisalignedMembers.erase(MA); 13606 } 13607 } 13608 } 13609 13610 void Sema::RefersToMemberWithReducedAlignment( 13611 Expr *E, 13612 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13613 Action) { 13614 const auto *ME = dyn_cast<MemberExpr>(E); 13615 if (!ME) 13616 return; 13617 13618 // No need to check expressions with an __unaligned-qualified type. 13619 if (E->getType().getQualifiers().hasUnaligned()) 13620 return; 13621 13622 // For a chain of MemberExpr like "a.b.c.d" this list 13623 // will keep FieldDecl's like [d, c, b]. 13624 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13625 const MemberExpr *TopME = nullptr; 13626 bool AnyIsPacked = false; 13627 do { 13628 QualType BaseType = ME->getBase()->getType(); 13629 if (ME->isArrow()) 13630 BaseType = BaseType->getPointeeType(); 13631 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13632 if (RD->isInvalidDecl()) 13633 return; 13634 13635 ValueDecl *MD = ME->getMemberDecl(); 13636 auto *FD = dyn_cast<FieldDecl>(MD); 13637 // We do not care about non-data members. 13638 if (!FD || FD->isInvalidDecl()) 13639 return; 13640 13641 AnyIsPacked = 13642 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13643 ReverseMemberChain.push_back(FD); 13644 13645 TopME = ME; 13646 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13647 } while (ME); 13648 assert(TopME && "We did not compute a topmost MemberExpr!"); 13649 13650 // Not the scope of this diagnostic. 13651 if (!AnyIsPacked) 13652 return; 13653 13654 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13655 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13656 // TODO: The innermost base of the member expression may be too complicated. 13657 // For now, just disregard these cases. This is left for future 13658 // improvement. 13659 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13660 return; 13661 13662 // Alignment expected by the whole expression. 13663 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13664 13665 // No need to do anything else with this case. 13666 if (ExpectedAlignment.isOne()) 13667 return; 13668 13669 // Synthesize offset of the whole access. 13670 CharUnits Offset; 13671 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13672 I++) { 13673 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13674 } 13675 13676 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13677 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13678 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13679 13680 // The base expression of the innermost MemberExpr may give 13681 // stronger guarantees than the class containing the member. 13682 if (DRE && !TopME->isArrow()) { 13683 const ValueDecl *VD = DRE->getDecl(); 13684 if (!VD->getType()->isReferenceType()) 13685 CompleteObjectAlignment = 13686 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13687 } 13688 13689 // Check if the synthesized offset fulfills the alignment. 13690 if (Offset % ExpectedAlignment != 0 || 13691 // It may fulfill the offset it but the effective alignment may still be 13692 // lower than the expected expression alignment. 13693 CompleteObjectAlignment < ExpectedAlignment) { 13694 // If this happens, we want to determine a sensible culprit of this. 13695 // Intuitively, watching the chain of member expressions from right to 13696 // left, we start with the required alignment (as required by the field 13697 // type) but some packed attribute in that chain has reduced the alignment. 13698 // It may happen that another packed structure increases it again. But if 13699 // we are here such increase has not been enough. So pointing the first 13700 // FieldDecl that either is packed or else its RecordDecl is, 13701 // seems reasonable. 13702 FieldDecl *FD = nullptr; 13703 CharUnits Alignment; 13704 for (FieldDecl *FDI : ReverseMemberChain) { 13705 if (FDI->hasAttr<PackedAttr>() || 13706 FDI->getParent()->hasAttr<PackedAttr>()) { 13707 FD = FDI; 13708 Alignment = std::min( 13709 Context.getTypeAlignInChars(FD->getType()), 13710 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13711 break; 13712 } 13713 } 13714 assert(FD && "We did not find a packed FieldDecl!"); 13715 Action(E, FD->getParent(), FD, Alignment); 13716 } 13717 } 13718 13719 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13720 using namespace std::placeholders; 13721 13722 RefersToMemberWithReducedAlignment( 13723 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13724 _2, _3, _4)); 13725 } 13726