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 if (BuiltinID == AArch64::BI__getReg) 1753 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1754 1755 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1756 return true; 1757 1758 // For intrinsics which take an immediate value as part of the instruction, 1759 // range check them here. 1760 unsigned i = 0, l = 0, u = 0; 1761 switch (BuiltinID) { 1762 default: return false; 1763 case AArch64::BI__builtin_arm_dmb: 1764 case AArch64::BI__builtin_arm_dsb: 1765 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1766 } 1767 1768 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1769 } 1770 1771 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1772 static const std::map<unsigned, std::vector<StringRef>> ValidCPU = { 1773 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, {"v65"} }, 1774 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, {"v62", "v65"} }, 1775 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, {"v62", "v65"} }, 1776 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, {"v62", "v65"} }, 1777 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {"v60", "v62", "v65"} }, 1778 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {"v60", "v62", "v65"} }, 1779 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {"v60", "v62", "v65"} }, 1780 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {"v60", "v62", "v65"} }, 1781 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {"v60", "v62", "v65"} }, 1782 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {"v60", "v62", "v65"} }, 1783 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {"v60", "v62", "v65"} }, 1784 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {"v60", "v62", "v65"} }, 1785 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {"v60", "v62", "v65"} }, 1786 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {"v60", "v62", "v65"} }, 1787 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {"v60", "v62", "v65"} }, 1788 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {"v60", "v62", "v65"} }, 1789 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, {"v62", "v65"} }, 1790 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, {"v62", "v65"} }, 1791 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, {"v62", "v65"} }, 1792 }; 1793 1794 static const std::map<unsigned, std::vector<StringRef>> ValidHVX = { 1795 { Hexagon::BI__builtin_HEXAGON_V6_extractw, {"v60", "v62", "v65"} }, 1796 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, {"v60", "v62", "v65"} }, 1797 { Hexagon::BI__builtin_HEXAGON_V6_hi, {"v60", "v62", "v65"} }, 1798 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, {"v60", "v62", "v65"} }, 1799 { Hexagon::BI__builtin_HEXAGON_V6_lo, {"v60", "v62", "v65"} }, 1800 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, {"v60", "v62", "v65"} }, 1801 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, {"v62", "v65"} }, 1802 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, {"v62", "v65"} }, 1803 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, {"v62", "v65"} }, 1804 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, {"v62", "v65"} }, 1805 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, {"v60", "v62", "v65"} }, 1806 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, {"v60", "v62", "v65"} }, 1807 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, {"v60", "v62", "v65"} }, 1808 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, {"v60", "v62", "v65"} }, 1809 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, {"v60", "v62", "v65"} }, 1810 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, {"v60", "v62", "v65"} }, 1811 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, {"v60", "v62", "v65"} }, 1812 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, {"v60", "v62", "v65"} }, 1813 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, {"v60", "v62", "v65"} }, 1814 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, {"v60", "v62", "v65"} }, 1815 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, {"v60", "v62", "v65"} }, 1816 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, {"v60", "v62", "v65"} }, 1817 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, {"v60", "v62", "v65"} }, 1818 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, {"v60", "v62", "v65"} }, 1819 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, {"v62", "v65"} }, 1820 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, {"v62", "v65"} }, 1821 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, {"v60", "v62", "v65"} }, 1822 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, {"v60", "v62", "v65"} }, 1823 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, {"v62", "v65"} }, 1824 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, {"v62", "v65"} }, 1825 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, {"v62", "v65"} }, 1826 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, {"v62", "v65"} }, 1827 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, {"v65"} }, 1828 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, {"v65"} }, 1829 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, {"v65"} }, 1830 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, {"v65"} }, 1831 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, {"v60", "v62", "v65"} }, 1832 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, {"v60", "v62", "v65"} }, 1833 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, {"v60", "v62", "v65"} }, 1834 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, {"v60", "v62", "v65"} }, 1835 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, {"v60", "v62", "v65"} }, 1836 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, {"v60", "v62", "v65"} }, 1837 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, {"v60", "v62", "v65"} }, 1838 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, {"v60", "v62", "v65"} }, 1839 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, {"v60", "v62", "v65"} }, 1840 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, {"v60", "v62", "v65"} }, 1841 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, {"v60", "v62", "v65"} }, 1842 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, {"v60", "v62", "v65"} }, 1843 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, {"v60", "v62", "v65"} }, 1844 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, {"v60", "v62", "v65"} }, 1845 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, {"v60", "v62", "v65"} }, 1846 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, {"v60", "v62", "v65"} }, 1847 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, {"v60", "v62", "v65"} }, 1848 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, {"v60", "v62", "v65"} }, 1849 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, {"v60", "v62", "v65"} }, 1850 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, {"v60", "v62", "v65"} }, 1851 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, {"v62", "v65"} }, 1852 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, {"v62", "v65"} }, 1853 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, {"v62", "v65"} }, 1854 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, {"v62", "v65"} }, 1855 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, {"v62", "v65"} }, 1856 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, {"v62", "v65"} }, 1857 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, {"v62", "v65"} }, 1858 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, {"v62", "v65"} }, 1859 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, {"v62", "v65"} }, 1860 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, {"v62", "v65"} }, 1861 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, {"v60", "v62", "v65"} }, 1862 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, {"v60", "v62", "v65"} }, 1863 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, {"v60", "v62", "v65"} }, 1864 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, {"v60", "v62", "v65"} }, 1865 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, {"v60", "v62", "v65"} }, 1866 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, {"v60", "v62", "v65"} }, 1867 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, {"v60", "v62", "v65"} }, 1868 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, {"v60", "v62", "v65"} }, 1869 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, {"v60", "v62", "v65"} }, 1870 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, {"v60", "v62", "v65"} }, 1871 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, {"v62", "v65"} }, 1872 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, {"v62", "v65"} }, 1873 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, {"v60", "v62", "v65"} }, 1874 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, {"v60", "v62", "v65"} }, 1875 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, {"v62", "v65"} }, 1876 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, {"v62", "v65"} }, 1877 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, {"v60", "v62", "v65"} }, 1878 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, {"v60", "v62", "v65"} }, 1879 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, {"v60", "v62", "v65"} }, 1880 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, {"v60", "v62", "v65"} }, 1881 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, {"v62", "v65"} }, 1882 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, {"v62", "v65"} }, 1883 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, {"v60", "v62", "v65"} }, 1884 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, {"v60", "v62", "v65"} }, 1885 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, {"v60", "v62", "v65"} }, 1886 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, {"v60", "v62", "v65"} }, 1887 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, {"v60", "v62", "v65"} }, 1888 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, {"v60", "v62", "v65"} }, 1889 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, {"v62", "v65"} }, 1890 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, {"v62", "v65"} }, 1891 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, {"v62", "v65"} }, 1892 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, {"v62", "v65"} }, 1893 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, {"v62", "v65"} }, 1894 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, {"v62", "v65"} }, 1895 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, {"v60", "v62", "v65"} }, 1896 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, {"v60", "v62", "v65"} }, 1897 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, {"v60", "v62", "v65"} }, 1898 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, {"v60", "v62", "v65"} }, 1899 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, {"v60", "v62", "v65"} }, 1900 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, {"v60", "v62", "v65"} }, 1901 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, {"v60", "v62", "v65"} }, 1902 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, {"v60", "v62", "v65"} }, 1903 { Hexagon::BI__builtin_HEXAGON_V6_valignb, {"v60", "v62", "v65"} }, 1904 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, {"v60", "v62", "v65"} }, 1905 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {"v60", "v62", "v65"} }, 1906 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {"v60", "v62", "v65"} }, 1907 { Hexagon::BI__builtin_HEXAGON_V6_vand, {"v60", "v62", "v65"} }, 1908 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, {"v60", "v62", "v65"} }, 1909 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, {"v62", "v65"} }, 1910 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, {"v62", "v65"} }, 1911 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, {"v62", "v65"} }, 1912 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, {"v62", "v65"} }, 1913 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, {"v60", "v62", "v65"} }, 1914 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, {"v60", "v62", "v65"} }, 1915 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, {"v60", "v62", "v65"} }, 1916 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, {"v60", "v62", "v65"} }, 1917 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, {"v62", "v65"} }, 1918 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, {"v62", "v65"} }, 1919 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, {"v62", "v65"} }, 1920 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, {"v62", "v65"} }, 1921 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, {"v60", "v62", "v65"} }, 1922 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, {"v60", "v62", "v65"} }, 1923 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, {"v60", "v62", "v65"} }, 1924 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, {"v60", "v62", "v65"} }, 1925 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, {"v60", "v62", "v65"} }, 1926 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, {"v60", "v62", "v65"} }, 1927 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, {"v65"} }, 1928 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, {"v65"} }, 1929 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, {"v60", "v62", "v65"} }, 1930 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, {"v60", "v62", "v65"} }, 1931 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, {"v60", "v62", "v65"} }, 1932 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, {"v60", "v62", "v65"} }, 1933 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, {"v60", "v62", "v65"} }, 1934 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, {"v60", "v62", "v65"} }, 1935 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, {"v60", "v62", "v65"} }, 1936 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, {"v60", "v62", "v65"} }, 1937 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, {"v60", "v62", "v65"} }, 1938 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, {"v60", "v62", "v65"} }, 1939 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, {"v65"} }, 1940 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, {"v65"} }, 1941 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, {"v60", "v62", "v65"} }, 1942 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, {"v60", "v62", "v65"} }, 1943 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, {"v62", "v65"} }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, {"v62", "v65"} }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, {"v60", "v62", "v65"} }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, {"v60", "v62", "v65"} }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, {"v60", "v62", "v65"} }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, {"v60", "v62", "v65"} }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, {"v60", "v62", "v65"} }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, {"v60", "v62", "v65"} }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, {"v65"} }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, {"v65"} }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, {"v65"} }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, {"v65"} }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, {"v62", "v65"} }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, {"v62", "v65"} }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, {"v65"} }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, {"v65"} }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, {"v60", "v62", "v65"} }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, {"v60", "v62", "v65"} }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, {"v60", "v62", "v65"} }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, {"v60", "v62", "v65"} }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, {"v60", "v62", "v65"} }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, {"v60", "v62", "v65"} }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, {"v60", "v62", "v65"} }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, {"v60", "v62", "v65"} }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, {"v60", "v62", "v65"} }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, {"v60", "v62", "v65"} }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, {"v62", "v65"} }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, {"v62", "v65"} }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, {"v60", "v62", "v65"} }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, {"v60", "v62", "v65"} }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, {"v60", "v62", "v65"} }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, {"v60", "v62", "v65"} }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vassign, {"v60", "v62", "v65"} }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, {"v60", "v62", "v65"} }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, {"v60", "v62", "v65"} }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, {"v60", "v62", "v65"} }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, {"v65"} }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, {"v65"} }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, {"v65"} }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, {"v65"} }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, {"v60", "v62", "v65"} }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, {"v60", "v62", "v65"} }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, {"v60", "v62", "v65"} }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, {"v60", "v62", "v65"} }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, {"v60", "v62", "v65"} }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, {"v60", "v62", "v65"} }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, {"v60", "v62", "v65"} }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, {"v60", "v62", "v65"} }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, {"v60", "v62", "v65"} }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, {"v60", "v62", "v65"} }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, {"v60", "v62", "v65"} }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, {"v60", "v62", "v65"} }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, {"v65"} }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, {"v65"} }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, {"v65"} }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, {"v65"} }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, {"v60", "v62", "v65"} }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, {"v60", "v62", "v65"} }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, {"v60", "v62", "v65"} }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, {"v60", "v62", "v65"} }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, {"v60", "v62", "v65"} }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, {"v60", "v62", "v65"} }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, {"v60", "v62", "v65"} }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, {"v60", "v62", "v65"} }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, {"v60", "v62", "v65"} }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, {"v60", "v62", "v65"} }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vd0, {"v60", "v62", "v65"} }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, {"v60", "v62", "v65"} }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, {"v65"} }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, {"v65"} }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, {"v60", "v62", "v65"} }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, {"v60", "v62", "v65"} }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, {"v60", "v62", "v65"} }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, {"v60", "v62", "v65"} }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, {"v60", "v62", "v65"} }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, {"v60", "v62", "v65"} }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, {"v60", "v62", "v65"} }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, {"v60", "v62", "v65"} }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, {"v60", "v62", "v65"} }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, {"v60", "v62", "v65"} }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, {"v60", "v62", "v65"} }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, {"v60", "v62", "v65"} }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, {"v60", "v62", "v65"} }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, {"v60", "v62", "v65"} }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, {"v60", "v62", "v65"} }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, {"v60", "v62", "v65"} }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, {"v60", "v62", "v65"} }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, {"v60", "v62", "v65"} }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, {"v60", "v62", "v65"} }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, {"v60", "v62", "v65"} }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, {"v60", "v62", "v65"} }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, {"v60", "v62", "v65"} }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, {"v60", "v62", "v65"} }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, {"v60", "v62", "v65"} }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, {"v60", "v62", "v65"} }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, {"v60", "v62", "v65"} }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, {"v60", "v62", "v65"} }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, {"v60", "v62", "v65"} }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, {"v60", "v62", "v65"} }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, {"v60", "v62", "v65"} }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, {"v60", "v62", "v65"} }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, {"v60", "v62", "v65"} }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, {"v60", "v62", "v65"} }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, {"v60", "v62", "v65"} }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, {"v60", "v62", "v65"} }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, {"v60", "v62", "v65"} }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, {"v60", "v62", "v65"} }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, {"v60", "v62", "v65"} }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, {"v60", "v62", "v65"} }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, {"v60", "v62", "v65"} }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, {"v60", "v62", "v65"} }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, {"v60", "v62", "v65"} }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, {"v60", "v62", "v65"} }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, {"v60", "v62", "v65"} }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, {"v60", "v62", "v65"} }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, {"v60", "v62", "v65"} }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, {"v60", "v62", "v65"} }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, {"v60", "v62", "v65"} }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, {"v60", "v62", "v65"} }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, {"v60", "v62", "v65"} }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_veqb, {"v60", "v62", "v65"} }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, {"v60", "v62", "v65"} }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, {"v60", "v62", "v65"} }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, {"v60", "v62", "v65"} }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, {"v60", "v62", "v65"} }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, {"v60", "v62", "v65"} }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, {"v60", "v62", "v65"} }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, {"v60", "v62", "v65"} }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_veqh, {"v60", "v62", "v65"} }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, {"v60", "v62", "v65"} }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, {"v60", "v62", "v65"} }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, {"v60", "v62", "v65"} }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, {"v60", "v62", "v65"} }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, {"v60", "v62", "v65"} }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, {"v60", "v62", "v65"} }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, {"v60", "v62", "v65"} }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_veqw, {"v60", "v62", "v65"} }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, {"v60", "v62", "v65"} }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, {"v60", "v62", "v65"} }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, {"v60", "v62", "v65"} }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, {"v60", "v62", "v65"} }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, {"v60", "v62", "v65"} }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, {"v60", "v62", "v65"} }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, {"v60", "v62", "v65"} }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, {"v60", "v62", "v65"} }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, {"v60", "v62", "v65"} }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, {"v60", "v62", "v65"} }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, {"v60", "v62", "v65"} }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, {"v60", "v62", "v65"} }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, {"v60", "v62", "v65"} }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, {"v60", "v62", "v65"} }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, {"v60", "v62", "v65"} }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vgth, {"v60", "v62", "v65"} }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, {"v60", "v62", "v65"} }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, {"v60", "v62", "v65"} }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, {"v60", "v62", "v65"} }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, {"v60", "v62", "v65"} }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, {"v60", "v62", "v65"} }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, {"v60", "v62", "v65"} }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, {"v60", "v62", "v65"} }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, {"v60", "v62", "v65"} }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, {"v60", "v62", "v65"} }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, {"v60", "v62", "v65"} }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, {"v60", "v62", "v65"} }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, {"v60", "v62", "v65"} }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, {"v60", "v62", "v65"} }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, {"v60", "v62", "v65"} }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, {"v60", "v62", "v65"} }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, {"v60", "v62", "v65"} }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, {"v60", "v62", "v65"} }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, {"v60", "v62", "v65"} }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, {"v60", "v62", "v65"} }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, {"v60", "v62", "v65"} }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, {"v60", "v62", "v65"} }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, {"v60", "v62", "v65"} }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, {"v60", "v62", "v65"} }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, {"v60", "v62", "v65"} }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, {"v60", "v62", "v65"} }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, {"v60", "v62", "v65"} }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, {"v60", "v62", "v65"} }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, {"v60", "v62", "v65"} }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, {"v60", "v62", "v65"} }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, {"v60", "v62", "v65"} }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, {"v60", "v62", "v65"} }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, {"v60", "v62", "v65"} }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, {"v60", "v62", "v65"} }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, {"v60", "v62", "v65"} }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, {"v60", "v62", "v65"} }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, {"v60", "v62", "v65"} }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, {"v60", "v62", "v65"} }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, {"v60", "v62", "v65"} }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, {"v60", "v62", "v65"} }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, {"v60", "v62", "v65"} }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, {"v60", "v62", "v65"} }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, {"v60", "v62", "v65"} }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, {"v60", "v62", "v65"} }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {"v60", "v62", "v65"} }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {"v60", "v62", "v65"} }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, {"v62", "v65"} }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, {"v62", "v65"} }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, {"v60", "v62", "v65"} }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, {"v60", "v62", "v65"} }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, {"v60", "v62", "v65"} }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, {"v60", "v62", "v65"} }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, {"v60", "v62", "v65"} }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, {"v60", "v62", "v65"} }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, {"v60", "v62", "v65"} }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, {"v60", "v62", "v65"} }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, {"v65"} }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, {"v65"} }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, {"v60", "v62", "v65"} }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, {"v60", "v62", "v65"} }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {"v62", "v65"} }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {"v62", "v65"} }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, {"v62", "v65"} }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, {"v62", "v65"} }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, {"v60", "v62", "v65"} }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, {"v60", "v62", "v65"} }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {"v62", "v65"} }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, {"v62", "v65"} }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, {"v60", "v62", "v65"} }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, {"v60", "v62", "v65"} }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {"v62", "v65"} }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {"v62", "v65"} }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, {"v62", "v65"} }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, {"v62", "v65"} }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, {"v60", "v62", "v65"} }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, {"v60", "v62", "v65"} }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {"v62", "v65"} }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, {"v62", "v65"} }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, {"v62", "v65"} }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, {"v62", "v65"} }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, {"v60", "v62", "v65"} }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, {"v60", "v62", "v65"} }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, {"v60", "v62", "v65"} }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, {"v60", "v62", "v65"} }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, {"v60", "v62", "v65"} }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, {"v60", "v62", "v65"} }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, {"v60", "v62", "v65"} }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, {"v60", "v62", "v65"} }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vminb, {"v62", "v65"} }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, {"v62", "v65"} }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vminh, {"v60", "v62", "v65"} }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, {"v60", "v62", "v65"} }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vminub, {"v60", "v62", "v65"} }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, {"v60", "v62", "v65"} }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, {"v60", "v62", "v65"} }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, {"v60", "v62", "v65"} }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vminw, {"v60", "v62", "v65"} }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, {"v60", "v62", "v65"} }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, {"v60", "v62", "v65"} }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, {"v60", "v62", "v65"} }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, {"v60", "v62", "v65"} }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, {"v60", "v62", "v65"} }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, {"v60", "v62", "v65"} }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, {"v60", "v62", "v65"} }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, {"v65"} }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, {"v65"} }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, {"v65"} }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, {"v65"} }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, {"v60", "v62", "v65"} }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, {"v60", "v62", "v65"} }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, {"v60", "v62", "v65"} }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, {"v60", "v62", "v65"} }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, {"v60", "v62", "v65"} }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, {"v60", "v62", "v65"} }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, {"v65"} }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, {"v65"} }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, {"v62", "v65"} }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, {"v62", "v65"} }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, {"v62", "v65"} }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, {"v62", "v65"} }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, {"v65"} }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, {"v65"} }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, {"v65"} }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, {"v65"} }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, {"v60", "v62", "v65"} }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, {"v60", "v62", "v65"} }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, {"v60", "v62", "v65"} }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, {"v60", "v62", "v65"} }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, {"v60", "v62", "v65"} }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, {"v60", "v62", "v65"} }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, {"v60", "v62", "v65"} }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, {"v60", "v62", "v65"} }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, {"v60", "v62", "v65"} }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, {"v60", "v62", "v65"} }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, {"v60", "v62", "v65"} }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, {"v60", "v62", "v65"} }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, {"v60", "v62", "v65"} }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, {"v60", "v62", "v65"} }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, {"v62", "v65"} }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, {"v62", "v65"} }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, {"v60", "v62", "v65"} }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, {"v60", "v62", "v65"} }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, {"v65"} }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, {"v65"} }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, {"v60", "v62", "v65"} }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, {"v60", "v62", "v65"} }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, {"v60", "v62", "v65"} }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, {"v60", "v62", "v65"} }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, {"v60", "v62", "v65"} }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, {"v60", "v62", "v65"} }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, {"v60", "v62", "v65"} }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, {"v60", "v62", "v65"} }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, {"v60", "v62", "v65"} }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, {"v60", "v62", "v65"} }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, {"v60", "v62", "v65"} }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, {"v60", "v62", "v65"} }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, {"v60", "v62", "v65"} }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, {"v60", "v62", "v65"} }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, {"v60", "v62", "v65"} }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, {"v60", "v62", "v65"} }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, {"v60", "v62", "v65"} }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, {"v60", "v62", "v65"} }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, {"v60", "v62", "v65"} }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, {"v60", "v62", "v65"} }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, {"v60", "v62", "v65"} }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, {"v60", "v62", "v65"} }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, {"v60", "v62", "v65"} }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, {"v60", "v62", "v65"} }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, {"v60", "v62", "v65"} }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, {"v60", "v62", "v65"} }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, {"v60", "v62", "v65"} }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, {"v60", "v62", "v65"} }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, {"v60", "v62", "v65"} }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, {"v60", "v62", "v65"} }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, {"v60", "v62", "v65"} }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, {"v60", "v62", "v65"} }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, {"v60", "v62", "v65"} }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, {"v60", "v62", "v65"} }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, {"v60", "v62", "v65"} }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, {"v60", "v62", "v65"} }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, {"v60", "v62", "v65"} }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, {"v60", "v62", "v65"} }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, {"v60", "v62", "v65"} }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, {"v60", "v62", "v65"} }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, {"v60", "v62", "v65"} }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, {"v60", "v62", "v65"} }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, {"v62", "v65"} }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, {"v62", "v65"} }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, {"v62", "v65"} }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, {"v62", "v65"} }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, {"v60", "v62", "v65"} }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, {"v60", "v62", "v65"} }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, {"v62", "v65"} }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, {"v62", "v65"} }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, {"v60", "v62", "v65"} }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, {"v60", "v62", "v65"} }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, {"v60", "v62", "v65"} }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, {"v60", "v62", "v65"} }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, {"v60", "v62", "v65"} }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, {"v60", "v62", "v65"} }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, {"v60", "v62", "v65"} }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, {"v60", "v62", "v65"} }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, {"v60", "v62", "v65"} }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, {"v60", "v62", "v65"} }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, {"v60", "v62", "v65"} }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, {"v60", "v62", "v65"} }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, {"v60", "v62", "v65"} }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, {"v60", "v62", "v65"} }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, {"v60", "v62", "v65"} }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, {"v60", "v62", "v65"} }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, {"v60", "v62", "v65"} }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, {"v60", "v62", "v65"} }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, {"v65"} }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, {"v65"} }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, {"v65"} }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, {"v65"} }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, {"v60", "v62", "v65"} }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, {"v60", "v62", "v65"} }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, {"v60", "v62", "v65"} }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, {"v60", "v62", "v65"} }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vmux, {"v60", "v62", "v65"} }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, {"v60", "v62", "v65"} }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, {"v65"} }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, {"v65"} }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, {"v60", "v62", "v65"} }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, {"v60", "v62", "v65"} }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, {"v60", "v62", "v65"} }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, {"v60", "v62", "v65"} }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, {"v60", "v62", "v65"} }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, {"v60", "v62", "v65"} }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, {"v60", "v62", "v65"} }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, {"v60", "v62", "v65"} }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, {"v60", "v62", "v65"} }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, {"v60", "v62", "v65"} }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vnot, {"v60", "v62", "v65"} }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, {"v60", "v62", "v65"} }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vor, {"v60", "v62", "v65"} }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, {"v60", "v62", "v65"} }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, {"v60", "v62", "v65"} }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, {"v60", "v62", "v65"} }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, {"v60", "v62", "v65"} }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, {"v60", "v62", "v65"} }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, {"v60", "v62", "v65"} }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, {"v60", "v62", "v65"} }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, {"v60", "v62", "v65"} }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, {"v60", "v62", "v65"} }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, {"v60", "v62", "v65"} }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, {"v60", "v62", "v65"} }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, {"v60", "v62", "v65"} }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, {"v60", "v62", "v65"} }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, {"v60", "v62", "v65"} }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, {"v60", "v62", "v65"} }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, {"v60", "v62", "v65"} }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, {"v60", "v62", "v65"} }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, {"v60", "v62", "v65"} }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, {"v60", "v62", "v65"} }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, {"v65"} }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, {"v65"} }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, {"v65"} }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, {"v65"} }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, {"v65"} }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, {"v65"} }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, {"v60", "v62", "v65"} }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, {"v60", "v62", "v65"} }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, {"v65"} }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, {"v65"} }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, {"v65"} }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, {"v65"} }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, {"v60", "v62", "v65"} }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, {"v60", "v62", "v65"} }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, {"v60", "v62", "v65"} }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, {"v60", "v62", "v65"} }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {"v60", "v62", "v65"} }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {"v60", "v62", "v65"} }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {"v60", "v62", "v65"} }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, {"v60", "v62", "v65"} }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, {"v60", "v62", "v65"} }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, {"v60", "v62", "v65"} }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, {"v60", "v62", "v65"} }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, {"v60", "v62", "v65"} }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, {"v60", "v62", "v65"} }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, {"v60", "v62", "v65"} }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, {"v60", "v62", "v65"} }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, {"v60", "v62", "v65"} }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, {"v60", "v62", "v65"} }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, {"v60", "v62", "v65"} }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, {"v60", "v62", "v65"} }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, {"v60", "v62", "v65"} }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {"v60", "v62", "v65"} }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {"v60", "v62", "v65"} }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {"v60", "v62", "v65"} }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, {"v60", "v62", "v65"} }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, {"v65"} }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, {"v65"} }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, {"v65"} }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, {"v65"} }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, {"v60", "v62", "v65"} }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, {"v60", "v62", "v65"} }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, {"v60", "v62", "v65"} }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, {"v60", "v62", "v65"} }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vror, {"v60", "v62", "v65"} }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, {"v60", "v62", "v65"} }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, {"v60", "v62", "v65"} }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, {"v60", "v62", "v65"} }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, {"v60", "v62", "v65"} }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, {"v60", "v62", "v65"} }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, {"v62", "v65"} }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, {"v62", "v65"} }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, {"v62", "v65"} }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, {"v62", "v65"} }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, {"v60", "v62", "v65"} }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, {"v60", "v62", "v65"} }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, {"v60", "v62", "v65"} }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, {"v60", "v62", "v65"} }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {"v60", "v62", "v65"} }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {"v60", "v62", "v65"} }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {"v60", "v62", "v65"} }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, {"v60", "v62", "v65"} }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, {"v60", "v62", "v65"} }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, {"v60", "v62", "v65"} }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, {"v62", "v65"} }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, {"v62", "v65"} }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, {"v60", "v62", "v65"} }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, {"v60", "v62", "v65"} }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vsb, {"v60", "v62", "v65"} }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, {"v60", "v62", "v65"} }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vsh, {"v60", "v62", "v65"} }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, {"v60", "v62", "v65"} }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, {"v60", "v62", "v65"} }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, {"v60", "v62", "v65"} }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, {"v60", "v62", "v65"} }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, {"v60", "v62", "v65"} }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, {"v60", "v62", "v65"} }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, {"v60", "v62", "v65"} }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, {"v60", "v62", "v65"} }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, {"v60", "v62", "v65"} }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, {"v60", "v62", "v65"} }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, {"v60", "v62", "v65"} }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, {"v60", "v62", "v65"} }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, {"v60", "v62", "v65"} }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, {"v60", "v62", "v65"} }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, {"v60", "v62", "v65"} }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, {"v60", "v62", "v65"} }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, {"v60", "v62", "v65"} }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, {"v60", "v62", "v65"} }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, {"v60", "v62", "v65"} }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, {"v60", "v62", "v65"} }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, {"v60", "v62", "v65"} }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, {"v60", "v62", "v65"} }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, {"v60", "v62", "v65"} }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, {"v62", "v65"} }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, {"v62", "v65"} }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, {"v62", "v65"} }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, {"v62", "v65"} }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, {"v62", "v65"} }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, {"v62", "v65"} }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, {"v60", "v62", "v65"} }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, {"v60", "v62", "v65"} }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, {"v60", "v62", "v65"} }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, {"v60", "v62", "v65"} }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, {"v60", "v62", "v65"} }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, {"v60", "v62", "v65"} }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, {"v60", "v62", "v65"} }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, {"v60", "v62", "v65"} }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, {"v60", "v62", "v65"} }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, {"v60", "v62", "v65"} }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, {"v60", "v62", "v65"} }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, {"v60", "v62", "v65"} }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, {"v60", "v62", "v65"} }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, {"v60", "v62", "v65"} }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, {"v60", "v62", "v65"} }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, {"v60", "v62", "v65"} }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, {"v62", "v65"} }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, {"v62", "v65"} }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, {"v60", "v62", "v65"} }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, {"v60", "v62", "v65"} }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, {"v60", "v62", "v65"} }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, {"v60", "v62", "v65"} }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, {"v60", "v62", "v65"} }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, {"v60", "v62", "v65"} }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, {"v62", "v65"} }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, {"v62", "v65"} }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, {"v62", "v65"} }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, {"v62", "v65"} }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, {"v60", "v62", "v65"} }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, {"v60", "v62", "v65"} }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, {"v60", "v62", "v65"} }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, {"v60", "v62", "v65"} }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, {"v60", "v62", "v65"} }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, {"v60", "v62", "v65"} }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, {"v60", "v62", "v65"} }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, {"v60", "v62", "v65"} }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vswap, {"v60", "v62", "v65"} }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, {"v60", "v62", "v65"} }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, {"v60", "v62", "v65"} }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, {"v60", "v62", "v65"} }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, {"v60", "v62", "v65"} }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, {"v60", "v62", "v65"} }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, {"v60", "v62", "v65"} }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, {"v60", "v62", "v65"} }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, {"v60", "v62", "v65"} }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, {"v60", "v62", "v65"} }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, {"v60", "v62", "v65"} }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, {"v60", "v62", "v65"} }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, {"v60", "v62", "v65"} }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, {"v60", "v62", "v65"} }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, {"v60", "v62", "v65"} }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, {"v60", "v62", "v65"} }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, {"v60", "v62", "v65"} }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, {"v60", "v62", "v65"} }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, {"v60", "v62", "v65"} }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, {"v60", "v62", "v65"} }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, {"v60", "v62", "v65"} }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, {"v60", "v62", "v65"} }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, {"v60", "v62", "v65"} }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, {"v60", "v62", "v65"} }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, {"v60", "v62", "v65"} }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, {"v60", "v62", "v65"} }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vxor, {"v60", "v62", "v65"} }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, {"v60", "v62", "v65"} }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vzb, {"v60", "v62", "v65"} }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, {"v60", "v62", "v65"} }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vzh, {"v60", "v62", "v65"} }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, {"v60", "v62", "v65"} }, 2519 }; 2520 2521 const TargetInfo &TI = Context.getTargetInfo(); 2522 2523 auto FC = ValidCPU.find(BuiltinID); 2524 if (FC != ValidCPU.end()) { 2525 const TargetOptions &Opts = TI.getTargetOpts(); 2526 StringRef CPU = Opts.CPU; 2527 if (!CPU.empty()) { 2528 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2529 CPU.consume_front("hexagon"); 2530 if (llvm::none_of(FC->second, [CPU](StringRef S) { return S == CPU; })) 2531 return Diag(TheCall->getBeginLoc(), 2532 diag::err_hexagon_builtin_unsupported_cpu); 2533 } 2534 } 2535 2536 auto FH = ValidHVX.find(BuiltinID); 2537 if (FH != ValidHVX.end()) { 2538 if (!TI.hasFeature("hvx")) 2539 return Diag(TheCall->getBeginLoc(), 2540 diag::err_hexagon_builtin_requires_hvx); 2541 2542 bool IsValid = llvm::any_of(FH->second, 2543 [&TI] (StringRef V) { 2544 std::string F = "hvx" + V.str(); 2545 return TI.hasFeature(F); 2546 }); 2547 if (!IsValid) 2548 return Diag(TheCall->getBeginLoc(), 2549 diag::err_hexagon_builtin_unsupported_hvx); 2550 } 2551 2552 return false; 2553 } 2554 2555 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2556 struct ArgInfo { 2557 ArgInfo(unsigned O, bool S, unsigned W, unsigned A) 2558 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {} 2559 unsigned OpNum = 0; 2560 bool IsSigned = false; 2561 unsigned BitWidth = 0; 2562 unsigned Align = 0; 2563 }; 2564 2565 static const std::map<unsigned, std::vector<ArgInfo>> Infos = { 2566 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2567 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2568 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2569 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2570 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2571 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2572 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2573 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2574 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2575 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2576 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2577 2578 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2579 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2580 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2581 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2582 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2583 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2584 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2585 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2588 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2589 2590 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2593 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2596 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2597 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2598 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2599 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2600 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2601 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2602 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2603 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2604 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2605 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2606 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2607 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2608 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2609 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2610 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2611 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2612 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2613 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2615 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2616 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2617 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2618 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2619 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2620 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2621 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2622 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2624 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2625 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2642 {{ 1, false, 6, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2648 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2649 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2650 {{ 1, false, 5, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2657 { 2, false, 5, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2659 { 2, false, 6, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2661 { 3, false, 5, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2663 { 3, false, 6, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2680 {{ 2, false, 4, 0 }, 2681 { 3, false, 5, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2683 {{ 2, false, 4, 0 }, 2684 { 3, false, 5, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2686 {{ 2, false, 4, 0 }, 2687 { 3, false, 5, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2689 {{ 2, false, 4, 0 }, 2690 { 3, false, 5, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2702 { 2, false, 5, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2704 { 2, false, 6, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2714 {{ 1, false, 4, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2717 {{ 1, false, 4, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2738 {{ 3, false, 1, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2743 {{ 3, false, 1, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2748 {{ 3, false, 1, 0 }} }, 2749 }; 2750 2751 auto F = Infos.find(BuiltinID); 2752 if (F == Infos.end()) 2753 return false; 2754 2755 bool Error = false; 2756 2757 for (const ArgInfo &A : F->second) { 2758 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0; 2759 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1; 2760 if (!A.Align) { 2761 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2762 } else { 2763 unsigned M = 1 << A.Align; 2764 Min *= M; 2765 Max *= M; 2766 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2767 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2768 } 2769 } 2770 return Error; 2771 } 2772 2773 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2774 CallExpr *TheCall) { 2775 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2776 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2777 } 2778 2779 2780 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2781 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2782 // ordering for DSP is unspecified. MSA is ordered by the data format used 2783 // by the underlying instruction i.e., df/m, df/n and then by size. 2784 // 2785 // FIXME: The size tests here should instead be tablegen'd along with the 2786 // definitions from include/clang/Basic/BuiltinsMips.def. 2787 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2788 // be too. 2789 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2790 unsigned i = 0, l = 0, u = 0, m = 0; 2791 switch (BuiltinID) { 2792 default: return false; 2793 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2794 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2795 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2796 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2797 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2798 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2799 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2800 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the 2801 // df/m field. 2802 // These intrinsics take an unsigned 3 bit immediate. 2803 case Mips::BI__builtin_msa_bclri_b: 2804 case Mips::BI__builtin_msa_bnegi_b: 2805 case Mips::BI__builtin_msa_bseti_b: 2806 case Mips::BI__builtin_msa_sat_s_b: 2807 case Mips::BI__builtin_msa_sat_u_b: 2808 case Mips::BI__builtin_msa_slli_b: 2809 case Mips::BI__builtin_msa_srai_b: 2810 case Mips::BI__builtin_msa_srari_b: 2811 case Mips::BI__builtin_msa_srli_b: 2812 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2813 case Mips::BI__builtin_msa_binsli_b: 2814 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2815 // These intrinsics take an unsigned 4 bit immediate. 2816 case Mips::BI__builtin_msa_bclri_h: 2817 case Mips::BI__builtin_msa_bnegi_h: 2818 case Mips::BI__builtin_msa_bseti_h: 2819 case Mips::BI__builtin_msa_sat_s_h: 2820 case Mips::BI__builtin_msa_sat_u_h: 2821 case Mips::BI__builtin_msa_slli_h: 2822 case Mips::BI__builtin_msa_srai_h: 2823 case Mips::BI__builtin_msa_srari_h: 2824 case Mips::BI__builtin_msa_srli_h: 2825 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2826 case Mips::BI__builtin_msa_binsli_h: 2827 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2828 // These intrinsics take an unsigned 5 bit immediate. 2829 // The first block of intrinsics actually have an unsigned 5 bit field, 2830 // not a df/n field. 2831 case Mips::BI__builtin_msa_clei_u_b: 2832 case Mips::BI__builtin_msa_clei_u_h: 2833 case Mips::BI__builtin_msa_clei_u_w: 2834 case Mips::BI__builtin_msa_clei_u_d: 2835 case Mips::BI__builtin_msa_clti_u_b: 2836 case Mips::BI__builtin_msa_clti_u_h: 2837 case Mips::BI__builtin_msa_clti_u_w: 2838 case Mips::BI__builtin_msa_clti_u_d: 2839 case Mips::BI__builtin_msa_maxi_u_b: 2840 case Mips::BI__builtin_msa_maxi_u_h: 2841 case Mips::BI__builtin_msa_maxi_u_w: 2842 case Mips::BI__builtin_msa_maxi_u_d: 2843 case Mips::BI__builtin_msa_mini_u_b: 2844 case Mips::BI__builtin_msa_mini_u_h: 2845 case Mips::BI__builtin_msa_mini_u_w: 2846 case Mips::BI__builtin_msa_mini_u_d: 2847 case Mips::BI__builtin_msa_addvi_b: 2848 case Mips::BI__builtin_msa_addvi_h: 2849 case Mips::BI__builtin_msa_addvi_w: 2850 case Mips::BI__builtin_msa_addvi_d: 2851 case Mips::BI__builtin_msa_bclri_w: 2852 case Mips::BI__builtin_msa_bnegi_w: 2853 case Mips::BI__builtin_msa_bseti_w: 2854 case Mips::BI__builtin_msa_sat_s_w: 2855 case Mips::BI__builtin_msa_sat_u_w: 2856 case Mips::BI__builtin_msa_slli_w: 2857 case Mips::BI__builtin_msa_srai_w: 2858 case Mips::BI__builtin_msa_srari_w: 2859 case Mips::BI__builtin_msa_srli_w: 2860 case Mips::BI__builtin_msa_srlri_w: 2861 case Mips::BI__builtin_msa_subvi_b: 2862 case Mips::BI__builtin_msa_subvi_h: 2863 case Mips::BI__builtin_msa_subvi_w: 2864 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2865 case Mips::BI__builtin_msa_binsli_w: 2866 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2867 // These intrinsics take an unsigned 6 bit immediate. 2868 case Mips::BI__builtin_msa_bclri_d: 2869 case Mips::BI__builtin_msa_bnegi_d: 2870 case Mips::BI__builtin_msa_bseti_d: 2871 case Mips::BI__builtin_msa_sat_s_d: 2872 case Mips::BI__builtin_msa_sat_u_d: 2873 case Mips::BI__builtin_msa_slli_d: 2874 case Mips::BI__builtin_msa_srai_d: 2875 case Mips::BI__builtin_msa_srari_d: 2876 case Mips::BI__builtin_msa_srli_d: 2877 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2878 case Mips::BI__builtin_msa_binsli_d: 2879 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2880 // These intrinsics take a signed 5 bit immediate. 2881 case Mips::BI__builtin_msa_ceqi_b: 2882 case Mips::BI__builtin_msa_ceqi_h: 2883 case Mips::BI__builtin_msa_ceqi_w: 2884 case Mips::BI__builtin_msa_ceqi_d: 2885 case Mips::BI__builtin_msa_clti_s_b: 2886 case Mips::BI__builtin_msa_clti_s_h: 2887 case Mips::BI__builtin_msa_clti_s_w: 2888 case Mips::BI__builtin_msa_clti_s_d: 2889 case Mips::BI__builtin_msa_clei_s_b: 2890 case Mips::BI__builtin_msa_clei_s_h: 2891 case Mips::BI__builtin_msa_clei_s_w: 2892 case Mips::BI__builtin_msa_clei_s_d: 2893 case Mips::BI__builtin_msa_maxi_s_b: 2894 case Mips::BI__builtin_msa_maxi_s_h: 2895 case Mips::BI__builtin_msa_maxi_s_w: 2896 case Mips::BI__builtin_msa_maxi_s_d: 2897 case Mips::BI__builtin_msa_mini_s_b: 2898 case Mips::BI__builtin_msa_mini_s_h: 2899 case Mips::BI__builtin_msa_mini_s_w: 2900 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2901 // These intrinsics take an unsigned 8 bit immediate. 2902 case Mips::BI__builtin_msa_andi_b: 2903 case Mips::BI__builtin_msa_nori_b: 2904 case Mips::BI__builtin_msa_ori_b: 2905 case Mips::BI__builtin_msa_shf_b: 2906 case Mips::BI__builtin_msa_shf_h: 2907 case Mips::BI__builtin_msa_shf_w: 2908 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2909 case Mips::BI__builtin_msa_bseli_b: 2910 case Mips::BI__builtin_msa_bmnzi_b: 2911 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2912 // df/n format 2913 // These intrinsics take an unsigned 4 bit immediate. 2914 case Mips::BI__builtin_msa_copy_s_b: 2915 case Mips::BI__builtin_msa_copy_u_b: 2916 case Mips::BI__builtin_msa_insve_b: 2917 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2918 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2919 // These intrinsics take an unsigned 3 bit immediate. 2920 case Mips::BI__builtin_msa_copy_s_h: 2921 case Mips::BI__builtin_msa_copy_u_h: 2922 case Mips::BI__builtin_msa_insve_h: 2923 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2924 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2925 // These intrinsics take an unsigned 2 bit immediate. 2926 case Mips::BI__builtin_msa_copy_s_w: 2927 case Mips::BI__builtin_msa_copy_u_w: 2928 case Mips::BI__builtin_msa_insve_w: 2929 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2930 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2931 // These intrinsics take an unsigned 1 bit immediate. 2932 case Mips::BI__builtin_msa_copy_s_d: 2933 case Mips::BI__builtin_msa_copy_u_d: 2934 case Mips::BI__builtin_msa_insve_d: 2935 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2936 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2937 // Memory offsets and immediate loads. 2938 // These intrinsics take a signed 10 bit immediate. 2939 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2940 case Mips::BI__builtin_msa_ldi_h: 2941 case Mips::BI__builtin_msa_ldi_w: 2942 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2943 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break; 2944 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break; 2945 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break; 2946 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break; 2947 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break; 2948 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break; 2949 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break; 2950 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break; 2951 } 2952 2953 if (!m) 2954 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2955 2956 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2957 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2958 } 2959 2960 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2961 unsigned i = 0, l = 0, u = 0; 2962 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2963 BuiltinID == PPC::BI__builtin_divdeu || 2964 BuiltinID == PPC::BI__builtin_bpermd; 2965 bool IsTarget64Bit = Context.getTargetInfo() 2966 .getTypeWidth(Context 2967 .getTargetInfo() 2968 .getIntPtrType()) == 64; 2969 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2970 BuiltinID == PPC::BI__builtin_divweu || 2971 BuiltinID == PPC::BI__builtin_divde || 2972 BuiltinID == PPC::BI__builtin_divdeu; 2973 2974 if (Is64BitBltin && !IsTarget64Bit) 2975 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2976 << TheCall->getSourceRange(); 2977 2978 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2979 (BuiltinID == PPC::BI__builtin_bpermd && 2980 !Context.getTargetInfo().hasFeature("bpermd"))) 2981 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2982 << TheCall->getSourceRange(); 2983 2984 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 2985 if (!Context.getTargetInfo().hasFeature("vsx")) 2986 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2987 << TheCall->getSourceRange(); 2988 return false; 2989 }; 2990 2991 switch (BuiltinID) { 2992 default: return false; 2993 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2994 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2995 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2996 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2997 case PPC::BI__builtin_tbegin: 2998 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2999 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3000 case PPC::BI__builtin_tabortwc: 3001 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3002 case PPC::BI__builtin_tabortwci: 3003 case PPC::BI__builtin_tabortdci: 3004 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3005 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3006 case PPC::BI__builtin_vsx_xxpermdi: 3007 case PPC::BI__builtin_vsx_xxsldwi: 3008 return SemaBuiltinVSX(TheCall); 3009 case PPC::BI__builtin_unpack_vector_int128: 3010 return SemaVSXCheck(TheCall) || 3011 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3012 case PPC::BI__builtin_pack_vector_int128: 3013 return SemaVSXCheck(TheCall); 3014 } 3015 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3016 } 3017 3018 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3019 CallExpr *TheCall) { 3020 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3021 Expr *Arg = TheCall->getArg(0); 3022 llvm::APSInt AbortCode(32); 3023 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3024 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3025 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3026 << Arg->getSourceRange(); 3027 } 3028 3029 // For intrinsics which take an immediate value as part of the instruction, 3030 // range check them here. 3031 unsigned i = 0, l = 0, u = 0; 3032 switch (BuiltinID) { 3033 default: return false; 3034 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3035 case SystemZ::BI__builtin_s390_verimb: 3036 case SystemZ::BI__builtin_s390_verimh: 3037 case SystemZ::BI__builtin_s390_verimf: 3038 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3039 case SystemZ::BI__builtin_s390_vfaeb: 3040 case SystemZ::BI__builtin_s390_vfaeh: 3041 case SystemZ::BI__builtin_s390_vfaef: 3042 case SystemZ::BI__builtin_s390_vfaebs: 3043 case SystemZ::BI__builtin_s390_vfaehs: 3044 case SystemZ::BI__builtin_s390_vfaefs: 3045 case SystemZ::BI__builtin_s390_vfaezb: 3046 case SystemZ::BI__builtin_s390_vfaezh: 3047 case SystemZ::BI__builtin_s390_vfaezf: 3048 case SystemZ::BI__builtin_s390_vfaezbs: 3049 case SystemZ::BI__builtin_s390_vfaezhs: 3050 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3051 case SystemZ::BI__builtin_s390_vfisb: 3052 case SystemZ::BI__builtin_s390_vfidb: 3053 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3054 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3055 case SystemZ::BI__builtin_s390_vftcisb: 3056 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3057 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3058 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3059 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3060 case SystemZ::BI__builtin_s390_vstrcb: 3061 case SystemZ::BI__builtin_s390_vstrch: 3062 case SystemZ::BI__builtin_s390_vstrcf: 3063 case SystemZ::BI__builtin_s390_vstrczb: 3064 case SystemZ::BI__builtin_s390_vstrczh: 3065 case SystemZ::BI__builtin_s390_vstrczf: 3066 case SystemZ::BI__builtin_s390_vstrcbs: 3067 case SystemZ::BI__builtin_s390_vstrchs: 3068 case SystemZ::BI__builtin_s390_vstrcfs: 3069 case SystemZ::BI__builtin_s390_vstrczbs: 3070 case SystemZ::BI__builtin_s390_vstrczhs: 3071 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3072 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3073 case SystemZ::BI__builtin_s390_vfminsb: 3074 case SystemZ::BI__builtin_s390_vfmaxsb: 3075 case SystemZ::BI__builtin_s390_vfmindb: 3076 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3077 } 3078 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3079 } 3080 3081 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3082 /// This checks that the target supports __builtin_cpu_supports and 3083 /// that the string argument is constant and valid. 3084 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3085 Expr *Arg = TheCall->getArg(0); 3086 3087 // Check if the argument is a string literal. 3088 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3089 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3090 << Arg->getSourceRange(); 3091 3092 // Check the contents of the string. 3093 StringRef Feature = 3094 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3095 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3096 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3097 << Arg->getSourceRange(); 3098 return false; 3099 } 3100 3101 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3102 /// This checks that the target supports __builtin_cpu_is and 3103 /// that the string argument is constant and valid. 3104 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3105 Expr *Arg = TheCall->getArg(0); 3106 3107 // Check if the argument is a string literal. 3108 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3109 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3110 << Arg->getSourceRange(); 3111 3112 // Check the contents of the string. 3113 StringRef Feature = 3114 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3115 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3116 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3117 << Arg->getSourceRange(); 3118 return false; 3119 } 3120 3121 // Check if the rounding mode is legal. 3122 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3123 // Indicates if this instruction has rounding control or just SAE. 3124 bool HasRC = false; 3125 3126 unsigned ArgNum = 0; 3127 switch (BuiltinID) { 3128 default: 3129 return false; 3130 case X86::BI__builtin_ia32_vcvttsd2si32: 3131 case X86::BI__builtin_ia32_vcvttsd2si64: 3132 case X86::BI__builtin_ia32_vcvttsd2usi32: 3133 case X86::BI__builtin_ia32_vcvttsd2usi64: 3134 case X86::BI__builtin_ia32_vcvttss2si32: 3135 case X86::BI__builtin_ia32_vcvttss2si64: 3136 case X86::BI__builtin_ia32_vcvttss2usi32: 3137 case X86::BI__builtin_ia32_vcvttss2usi64: 3138 ArgNum = 1; 3139 break; 3140 case X86::BI__builtin_ia32_maxpd512: 3141 case X86::BI__builtin_ia32_maxps512: 3142 case X86::BI__builtin_ia32_minpd512: 3143 case X86::BI__builtin_ia32_minps512: 3144 ArgNum = 2; 3145 break; 3146 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3147 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3148 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3149 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3150 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3151 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3152 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3153 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3154 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3155 case X86::BI__builtin_ia32_exp2pd_mask: 3156 case X86::BI__builtin_ia32_exp2ps_mask: 3157 case X86::BI__builtin_ia32_getexppd512_mask: 3158 case X86::BI__builtin_ia32_getexpps512_mask: 3159 case X86::BI__builtin_ia32_rcp28pd_mask: 3160 case X86::BI__builtin_ia32_rcp28ps_mask: 3161 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3162 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3163 case X86::BI__builtin_ia32_vcomisd: 3164 case X86::BI__builtin_ia32_vcomiss: 3165 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3166 ArgNum = 3; 3167 break; 3168 case X86::BI__builtin_ia32_cmppd512_mask: 3169 case X86::BI__builtin_ia32_cmpps512_mask: 3170 case X86::BI__builtin_ia32_cmpsd_mask: 3171 case X86::BI__builtin_ia32_cmpss_mask: 3172 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3173 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3174 case X86::BI__builtin_ia32_getexpss128_round_mask: 3175 case X86::BI__builtin_ia32_maxsd_round_mask: 3176 case X86::BI__builtin_ia32_maxss_round_mask: 3177 case X86::BI__builtin_ia32_minsd_round_mask: 3178 case X86::BI__builtin_ia32_minss_round_mask: 3179 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3180 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3181 case X86::BI__builtin_ia32_reducepd512_mask: 3182 case X86::BI__builtin_ia32_reduceps512_mask: 3183 case X86::BI__builtin_ia32_rndscalepd_mask: 3184 case X86::BI__builtin_ia32_rndscaleps_mask: 3185 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3186 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3187 ArgNum = 4; 3188 break; 3189 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3190 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3191 case X86::BI__builtin_ia32_fixupimmps512_mask: 3192 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3193 case X86::BI__builtin_ia32_fixupimmsd_mask: 3194 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3195 case X86::BI__builtin_ia32_fixupimmss_mask: 3196 case X86::BI__builtin_ia32_fixupimmss_maskz: 3197 case X86::BI__builtin_ia32_rangepd512_mask: 3198 case X86::BI__builtin_ia32_rangeps512_mask: 3199 case X86::BI__builtin_ia32_rangesd128_round_mask: 3200 case X86::BI__builtin_ia32_rangess128_round_mask: 3201 case X86::BI__builtin_ia32_reducesd_mask: 3202 case X86::BI__builtin_ia32_reducess_mask: 3203 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3204 case X86::BI__builtin_ia32_rndscaless_round_mask: 3205 ArgNum = 5; 3206 break; 3207 case X86::BI__builtin_ia32_vcvtsd2si64: 3208 case X86::BI__builtin_ia32_vcvtsd2si32: 3209 case X86::BI__builtin_ia32_vcvtsd2usi32: 3210 case X86::BI__builtin_ia32_vcvtsd2usi64: 3211 case X86::BI__builtin_ia32_vcvtss2si32: 3212 case X86::BI__builtin_ia32_vcvtss2si64: 3213 case X86::BI__builtin_ia32_vcvtss2usi32: 3214 case X86::BI__builtin_ia32_vcvtss2usi64: 3215 case X86::BI__builtin_ia32_sqrtpd512: 3216 case X86::BI__builtin_ia32_sqrtps512: 3217 ArgNum = 1; 3218 HasRC = true; 3219 break; 3220 case X86::BI__builtin_ia32_addpd512: 3221 case X86::BI__builtin_ia32_addps512: 3222 case X86::BI__builtin_ia32_divpd512: 3223 case X86::BI__builtin_ia32_divps512: 3224 case X86::BI__builtin_ia32_mulpd512: 3225 case X86::BI__builtin_ia32_mulps512: 3226 case X86::BI__builtin_ia32_subpd512: 3227 case X86::BI__builtin_ia32_subps512: 3228 case X86::BI__builtin_ia32_cvtsi2sd64: 3229 case X86::BI__builtin_ia32_cvtsi2ss32: 3230 case X86::BI__builtin_ia32_cvtsi2ss64: 3231 case X86::BI__builtin_ia32_cvtusi2sd64: 3232 case X86::BI__builtin_ia32_cvtusi2ss32: 3233 case X86::BI__builtin_ia32_cvtusi2ss64: 3234 ArgNum = 2; 3235 HasRC = true; 3236 break; 3237 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3238 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3239 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3240 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3241 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3242 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3243 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3244 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3245 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3246 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3247 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3248 ArgNum = 3; 3249 HasRC = true; 3250 break; 3251 case X86::BI__builtin_ia32_addss_round_mask: 3252 case X86::BI__builtin_ia32_addsd_round_mask: 3253 case X86::BI__builtin_ia32_divss_round_mask: 3254 case X86::BI__builtin_ia32_divsd_round_mask: 3255 case X86::BI__builtin_ia32_mulss_round_mask: 3256 case X86::BI__builtin_ia32_mulsd_round_mask: 3257 case X86::BI__builtin_ia32_subss_round_mask: 3258 case X86::BI__builtin_ia32_subsd_round_mask: 3259 case X86::BI__builtin_ia32_scalefpd512_mask: 3260 case X86::BI__builtin_ia32_scalefps512_mask: 3261 case X86::BI__builtin_ia32_scalefsd_round_mask: 3262 case X86::BI__builtin_ia32_scalefss_round_mask: 3263 case X86::BI__builtin_ia32_getmantpd512_mask: 3264 case X86::BI__builtin_ia32_getmantps512_mask: 3265 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3266 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3267 case X86::BI__builtin_ia32_sqrtss_round_mask: 3268 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3269 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3270 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3271 case X86::BI__builtin_ia32_vfmaddss3_mask: 3272 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3273 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3274 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3275 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3276 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3277 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3278 case X86::BI__builtin_ia32_vfmaddps512_mask: 3279 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3280 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3281 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3282 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3283 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3284 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3285 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3286 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3287 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3288 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3289 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3290 ArgNum = 4; 3291 HasRC = true; 3292 break; 3293 case X86::BI__builtin_ia32_getmantsd_round_mask: 3294 case X86::BI__builtin_ia32_getmantss_round_mask: 3295 ArgNum = 5; 3296 HasRC = true; 3297 break; 3298 } 3299 3300 llvm::APSInt Result; 3301 3302 // We can't check the value of a dependent argument. 3303 Expr *Arg = TheCall->getArg(ArgNum); 3304 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3305 return false; 3306 3307 // Check constant-ness first. 3308 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3309 return true; 3310 3311 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3312 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3313 // combined with ROUND_NO_EXC. 3314 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3315 Result == 8/*ROUND_NO_EXC*/ || 3316 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3317 return false; 3318 3319 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3320 << Arg->getSourceRange(); 3321 } 3322 3323 // Check if the gather/scatter scale is legal. 3324 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3325 CallExpr *TheCall) { 3326 unsigned ArgNum = 0; 3327 switch (BuiltinID) { 3328 default: 3329 return false; 3330 case X86::BI__builtin_ia32_gatherpfdpd: 3331 case X86::BI__builtin_ia32_gatherpfdps: 3332 case X86::BI__builtin_ia32_gatherpfqpd: 3333 case X86::BI__builtin_ia32_gatherpfqps: 3334 case X86::BI__builtin_ia32_scatterpfdpd: 3335 case X86::BI__builtin_ia32_scatterpfdps: 3336 case X86::BI__builtin_ia32_scatterpfqpd: 3337 case X86::BI__builtin_ia32_scatterpfqps: 3338 ArgNum = 3; 3339 break; 3340 case X86::BI__builtin_ia32_gatherd_pd: 3341 case X86::BI__builtin_ia32_gatherd_pd256: 3342 case X86::BI__builtin_ia32_gatherq_pd: 3343 case X86::BI__builtin_ia32_gatherq_pd256: 3344 case X86::BI__builtin_ia32_gatherd_ps: 3345 case X86::BI__builtin_ia32_gatherd_ps256: 3346 case X86::BI__builtin_ia32_gatherq_ps: 3347 case X86::BI__builtin_ia32_gatherq_ps256: 3348 case X86::BI__builtin_ia32_gatherd_q: 3349 case X86::BI__builtin_ia32_gatherd_q256: 3350 case X86::BI__builtin_ia32_gatherq_q: 3351 case X86::BI__builtin_ia32_gatherq_q256: 3352 case X86::BI__builtin_ia32_gatherd_d: 3353 case X86::BI__builtin_ia32_gatherd_d256: 3354 case X86::BI__builtin_ia32_gatherq_d: 3355 case X86::BI__builtin_ia32_gatherq_d256: 3356 case X86::BI__builtin_ia32_gather3div2df: 3357 case X86::BI__builtin_ia32_gather3div2di: 3358 case X86::BI__builtin_ia32_gather3div4df: 3359 case X86::BI__builtin_ia32_gather3div4di: 3360 case X86::BI__builtin_ia32_gather3div4sf: 3361 case X86::BI__builtin_ia32_gather3div4si: 3362 case X86::BI__builtin_ia32_gather3div8sf: 3363 case X86::BI__builtin_ia32_gather3div8si: 3364 case X86::BI__builtin_ia32_gather3siv2df: 3365 case X86::BI__builtin_ia32_gather3siv2di: 3366 case X86::BI__builtin_ia32_gather3siv4df: 3367 case X86::BI__builtin_ia32_gather3siv4di: 3368 case X86::BI__builtin_ia32_gather3siv4sf: 3369 case X86::BI__builtin_ia32_gather3siv4si: 3370 case X86::BI__builtin_ia32_gather3siv8sf: 3371 case X86::BI__builtin_ia32_gather3siv8si: 3372 case X86::BI__builtin_ia32_gathersiv8df: 3373 case X86::BI__builtin_ia32_gathersiv16sf: 3374 case X86::BI__builtin_ia32_gatherdiv8df: 3375 case X86::BI__builtin_ia32_gatherdiv16sf: 3376 case X86::BI__builtin_ia32_gathersiv8di: 3377 case X86::BI__builtin_ia32_gathersiv16si: 3378 case X86::BI__builtin_ia32_gatherdiv8di: 3379 case X86::BI__builtin_ia32_gatherdiv16si: 3380 case X86::BI__builtin_ia32_scatterdiv2df: 3381 case X86::BI__builtin_ia32_scatterdiv2di: 3382 case X86::BI__builtin_ia32_scatterdiv4df: 3383 case X86::BI__builtin_ia32_scatterdiv4di: 3384 case X86::BI__builtin_ia32_scatterdiv4sf: 3385 case X86::BI__builtin_ia32_scatterdiv4si: 3386 case X86::BI__builtin_ia32_scatterdiv8sf: 3387 case X86::BI__builtin_ia32_scatterdiv8si: 3388 case X86::BI__builtin_ia32_scattersiv2df: 3389 case X86::BI__builtin_ia32_scattersiv2di: 3390 case X86::BI__builtin_ia32_scattersiv4df: 3391 case X86::BI__builtin_ia32_scattersiv4di: 3392 case X86::BI__builtin_ia32_scattersiv4sf: 3393 case X86::BI__builtin_ia32_scattersiv4si: 3394 case X86::BI__builtin_ia32_scattersiv8sf: 3395 case X86::BI__builtin_ia32_scattersiv8si: 3396 case X86::BI__builtin_ia32_scattersiv8df: 3397 case X86::BI__builtin_ia32_scattersiv16sf: 3398 case X86::BI__builtin_ia32_scatterdiv8df: 3399 case X86::BI__builtin_ia32_scatterdiv16sf: 3400 case X86::BI__builtin_ia32_scattersiv8di: 3401 case X86::BI__builtin_ia32_scattersiv16si: 3402 case X86::BI__builtin_ia32_scatterdiv8di: 3403 case X86::BI__builtin_ia32_scatterdiv16si: 3404 ArgNum = 4; 3405 break; 3406 } 3407 3408 llvm::APSInt Result; 3409 3410 // We can't check the value of a dependent argument. 3411 Expr *Arg = TheCall->getArg(ArgNum); 3412 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3413 return false; 3414 3415 // Check constant-ness first. 3416 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3417 return true; 3418 3419 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3420 return false; 3421 3422 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3423 << Arg->getSourceRange(); 3424 } 3425 3426 static bool isX86_32Builtin(unsigned BuiltinID) { 3427 // These builtins only work on x86-32 targets. 3428 switch (BuiltinID) { 3429 case X86::BI__builtin_ia32_readeflags_u32: 3430 case X86::BI__builtin_ia32_writeeflags_u32: 3431 return true; 3432 } 3433 3434 return false; 3435 } 3436 3437 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3438 if (BuiltinID == X86::BI__builtin_cpu_supports) 3439 return SemaBuiltinCpuSupports(*this, TheCall); 3440 3441 if (BuiltinID == X86::BI__builtin_cpu_is) 3442 return SemaBuiltinCpuIs(*this, TheCall); 3443 3444 // Check for 32-bit only builtins on a 64-bit target. 3445 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3446 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3447 return Diag(TheCall->getCallee()->getBeginLoc(), 3448 diag::err_32_bit_builtin_64_bit_tgt); 3449 3450 // If the intrinsic has rounding or SAE make sure its valid. 3451 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3452 return true; 3453 3454 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3455 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3456 return true; 3457 3458 // For intrinsics which take an immediate value as part of the instruction, 3459 // range check them here. 3460 int i = 0, l = 0, u = 0; 3461 switch (BuiltinID) { 3462 default: 3463 return false; 3464 case X86::BI__builtin_ia32_vec_ext_v2si: 3465 case X86::BI__builtin_ia32_vec_ext_v2di: 3466 case X86::BI__builtin_ia32_vextractf128_pd256: 3467 case X86::BI__builtin_ia32_vextractf128_ps256: 3468 case X86::BI__builtin_ia32_vextractf128_si256: 3469 case X86::BI__builtin_ia32_extract128i256: 3470 case X86::BI__builtin_ia32_extractf64x4_mask: 3471 case X86::BI__builtin_ia32_extracti64x4_mask: 3472 case X86::BI__builtin_ia32_extractf32x8_mask: 3473 case X86::BI__builtin_ia32_extracti32x8_mask: 3474 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3475 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3476 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3477 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3478 i = 1; l = 0; u = 1; 3479 break; 3480 case X86::BI__builtin_ia32_vec_set_v2di: 3481 case X86::BI__builtin_ia32_vinsertf128_pd256: 3482 case X86::BI__builtin_ia32_vinsertf128_ps256: 3483 case X86::BI__builtin_ia32_vinsertf128_si256: 3484 case X86::BI__builtin_ia32_insert128i256: 3485 case X86::BI__builtin_ia32_insertf32x8: 3486 case X86::BI__builtin_ia32_inserti32x8: 3487 case X86::BI__builtin_ia32_insertf64x4: 3488 case X86::BI__builtin_ia32_inserti64x4: 3489 case X86::BI__builtin_ia32_insertf64x2_256: 3490 case X86::BI__builtin_ia32_inserti64x2_256: 3491 case X86::BI__builtin_ia32_insertf32x4_256: 3492 case X86::BI__builtin_ia32_inserti32x4_256: 3493 i = 2; l = 0; u = 1; 3494 break; 3495 case X86::BI__builtin_ia32_vpermilpd: 3496 case X86::BI__builtin_ia32_vec_ext_v4hi: 3497 case X86::BI__builtin_ia32_vec_ext_v4si: 3498 case X86::BI__builtin_ia32_vec_ext_v4sf: 3499 case X86::BI__builtin_ia32_vec_ext_v4di: 3500 case X86::BI__builtin_ia32_extractf32x4_mask: 3501 case X86::BI__builtin_ia32_extracti32x4_mask: 3502 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3503 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3504 i = 1; l = 0; u = 3; 3505 break; 3506 case X86::BI_mm_prefetch: 3507 case X86::BI__builtin_ia32_vec_ext_v8hi: 3508 case X86::BI__builtin_ia32_vec_ext_v8si: 3509 i = 1; l = 0; u = 7; 3510 break; 3511 case X86::BI__builtin_ia32_sha1rnds4: 3512 case X86::BI__builtin_ia32_blendpd: 3513 case X86::BI__builtin_ia32_shufpd: 3514 case X86::BI__builtin_ia32_vec_set_v4hi: 3515 case X86::BI__builtin_ia32_vec_set_v4si: 3516 case X86::BI__builtin_ia32_vec_set_v4di: 3517 case X86::BI__builtin_ia32_shuf_f32x4_256: 3518 case X86::BI__builtin_ia32_shuf_f64x2_256: 3519 case X86::BI__builtin_ia32_shuf_i32x4_256: 3520 case X86::BI__builtin_ia32_shuf_i64x2_256: 3521 case X86::BI__builtin_ia32_insertf64x2_512: 3522 case X86::BI__builtin_ia32_inserti64x2_512: 3523 case X86::BI__builtin_ia32_insertf32x4: 3524 case X86::BI__builtin_ia32_inserti32x4: 3525 i = 2; l = 0; u = 3; 3526 break; 3527 case X86::BI__builtin_ia32_vpermil2pd: 3528 case X86::BI__builtin_ia32_vpermil2pd256: 3529 case X86::BI__builtin_ia32_vpermil2ps: 3530 case X86::BI__builtin_ia32_vpermil2ps256: 3531 i = 3; l = 0; u = 3; 3532 break; 3533 case X86::BI__builtin_ia32_cmpb128_mask: 3534 case X86::BI__builtin_ia32_cmpw128_mask: 3535 case X86::BI__builtin_ia32_cmpd128_mask: 3536 case X86::BI__builtin_ia32_cmpq128_mask: 3537 case X86::BI__builtin_ia32_cmpb256_mask: 3538 case X86::BI__builtin_ia32_cmpw256_mask: 3539 case X86::BI__builtin_ia32_cmpd256_mask: 3540 case X86::BI__builtin_ia32_cmpq256_mask: 3541 case X86::BI__builtin_ia32_cmpb512_mask: 3542 case X86::BI__builtin_ia32_cmpw512_mask: 3543 case X86::BI__builtin_ia32_cmpd512_mask: 3544 case X86::BI__builtin_ia32_cmpq512_mask: 3545 case X86::BI__builtin_ia32_ucmpb128_mask: 3546 case X86::BI__builtin_ia32_ucmpw128_mask: 3547 case X86::BI__builtin_ia32_ucmpd128_mask: 3548 case X86::BI__builtin_ia32_ucmpq128_mask: 3549 case X86::BI__builtin_ia32_ucmpb256_mask: 3550 case X86::BI__builtin_ia32_ucmpw256_mask: 3551 case X86::BI__builtin_ia32_ucmpd256_mask: 3552 case X86::BI__builtin_ia32_ucmpq256_mask: 3553 case X86::BI__builtin_ia32_ucmpb512_mask: 3554 case X86::BI__builtin_ia32_ucmpw512_mask: 3555 case X86::BI__builtin_ia32_ucmpd512_mask: 3556 case X86::BI__builtin_ia32_ucmpq512_mask: 3557 case X86::BI__builtin_ia32_vpcomub: 3558 case X86::BI__builtin_ia32_vpcomuw: 3559 case X86::BI__builtin_ia32_vpcomud: 3560 case X86::BI__builtin_ia32_vpcomuq: 3561 case X86::BI__builtin_ia32_vpcomb: 3562 case X86::BI__builtin_ia32_vpcomw: 3563 case X86::BI__builtin_ia32_vpcomd: 3564 case X86::BI__builtin_ia32_vpcomq: 3565 case X86::BI__builtin_ia32_vec_set_v8hi: 3566 case X86::BI__builtin_ia32_vec_set_v8si: 3567 i = 2; l = 0; u = 7; 3568 break; 3569 case X86::BI__builtin_ia32_vpermilpd256: 3570 case X86::BI__builtin_ia32_roundps: 3571 case X86::BI__builtin_ia32_roundpd: 3572 case X86::BI__builtin_ia32_roundps256: 3573 case X86::BI__builtin_ia32_roundpd256: 3574 case X86::BI__builtin_ia32_getmantpd128_mask: 3575 case X86::BI__builtin_ia32_getmantpd256_mask: 3576 case X86::BI__builtin_ia32_getmantps128_mask: 3577 case X86::BI__builtin_ia32_getmantps256_mask: 3578 case X86::BI__builtin_ia32_getmantpd512_mask: 3579 case X86::BI__builtin_ia32_getmantps512_mask: 3580 case X86::BI__builtin_ia32_vec_ext_v16qi: 3581 case X86::BI__builtin_ia32_vec_ext_v16hi: 3582 i = 1; l = 0; u = 15; 3583 break; 3584 case X86::BI__builtin_ia32_pblendd128: 3585 case X86::BI__builtin_ia32_blendps: 3586 case X86::BI__builtin_ia32_blendpd256: 3587 case X86::BI__builtin_ia32_shufpd256: 3588 case X86::BI__builtin_ia32_roundss: 3589 case X86::BI__builtin_ia32_roundsd: 3590 case X86::BI__builtin_ia32_rangepd128_mask: 3591 case X86::BI__builtin_ia32_rangepd256_mask: 3592 case X86::BI__builtin_ia32_rangepd512_mask: 3593 case X86::BI__builtin_ia32_rangeps128_mask: 3594 case X86::BI__builtin_ia32_rangeps256_mask: 3595 case X86::BI__builtin_ia32_rangeps512_mask: 3596 case X86::BI__builtin_ia32_getmantsd_round_mask: 3597 case X86::BI__builtin_ia32_getmantss_round_mask: 3598 case X86::BI__builtin_ia32_vec_set_v16qi: 3599 case X86::BI__builtin_ia32_vec_set_v16hi: 3600 i = 2; l = 0; u = 15; 3601 break; 3602 case X86::BI__builtin_ia32_vec_ext_v32qi: 3603 i = 1; l = 0; u = 31; 3604 break; 3605 case X86::BI__builtin_ia32_cmpps: 3606 case X86::BI__builtin_ia32_cmpss: 3607 case X86::BI__builtin_ia32_cmppd: 3608 case X86::BI__builtin_ia32_cmpsd: 3609 case X86::BI__builtin_ia32_cmpps256: 3610 case X86::BI__builtin_ia32_cmppd256: 3611 case X86::BI__builtin_ia32_cmpps128_mask: 3612 case X86::BI__builtin_ia32_cmppd128_mask: 3613 case X86::BI__builtin_ia32_cmpps256_mask: 3614 case X86::BI__builtin_ia32_cmppd256_mask: 3615 case X86::BI__builtin_ia32_cmpps512_mask: 3616 case X86::BI__builtin_ia32_cmppd512_mask: 3617 case X86::BI__builtin_ia32_cmpsd_mask: 3618 case X86::BI__builtin_ia32_cmpss_mask: 3619 case X86::BI__builtin_ia32_vec_set_v32qi: 3620 i = 2; l = 0; u = 31; 3621 break; 3622 case X86::BI__builtin_ia32_permdf256: 3623 case X86::BI__builtin_ia32_permdi256: 3624 case X86::BI__builtin_ia32_permdf512: 3625 case X86::BI__builtin_ia32_permdi512: 3626 case X86::BI__builtin_ia32_vpermilps: 3627 case X86::BI__builtin_ia32_vpermilps256: 3628 case X86::BI__builtin_ia32_vpermilpd512: 3629 case X86::BI__builtin_ia32_vpermilps512: 3630 case X86::BI__builtin_ia32_pshufd: 3631 case X86::BI__builtin_ia32_pshufd256: 3632 case X86::BI__builtin_ia32_pshufd512: 3633 case X86::BI__builtin_ia32_pshufhw: 3634 case X86::BI__builtin_ia32_pshufhw256: 3635 case X86::BI__builtin_ia32_pshufhw512: 3636 case X86::BI__builtin_ia32_pshuflw: 3637 case X86::BI__builtin_ia32_pshuflw256: 3638 case X86::BI__builtin_ia32_pshuflw512: 3639 case X86::BI__builtin_ia32_vcvtps2ph: 3640 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3641 case X86::BI__builtin_ia32_vcvtps2ph256: 3642 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3643 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3644 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3645 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3646 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3647 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3648 case X86::BI__builtin_ia32_rndscaleps_mask: 3649 case X86::BI__builtin_ia32_rndscalepd_mask: 3650 case X86::BI__builtin_ia32_reducepd128_mask: 3651 case X86::BI__builtin_ia32_reducepd256_mask: 3652 case X86::BI__builtin_ia32_reducepd512_mask: 3653 case X86::BI__builtin_ia32_reduceps128_mask: 3654 case X86::BI__builtin_ia32_reduceps256_mask: 3655 case X86::BI__builtin_ia32_reduceps512_mask: 3656 case X86::BI__builtin_ia32_prold512: 3657 case X86::BI__builtin_ia32_prolq512: 3658 case X86::BI__builtin_ia32_prold128: 3659 case X86::BI__builtin_ia32_prold256: 3660 case X86::BI__builtin_ia32_prolq128: 3661 case X86::BI__builtin_ia32_prolq256: 3662 case X86::BI__builtin_ia32_prord512: 3663 case X86::BI__builtin_ia32_prorq512: 3664 case X86::BI__builtin_ia32_prord128: 3665 case X86::BI__builtin_ia32_prord256: 3666 case X86::BI__builtin_ia32_prorq128: 3667 case X86::BI__builtin_ia32_prorq256: 3668 case X86::BI__builtin_ia32_fpclasspd128_mask: 3669 case X86::BI__builtin_ia32_fpclasspd256_mask: 3670 case X86::BI__builtin_ia32_fpclassps128_mask: 3671 case X86::BI__builtin_ia32_fpclassps256_mask: 3672 case X86::BI__builtin_ia32_fpclassps512_mask: 3673 case X86::BI__builtin_ia32_fpclasspd512_mask: 3674 case X86::BI__builtin_ia32_fpclasssd_mask: 3675 case X86::BI__builtin_ia32_fpclassss_mask: 3676 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3677 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3678 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3679 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3680 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3681 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3682 case X86::BI__builtin_ia32_kshiftliqi: 3683 case X86::BI__builtin_ia32_kshiftlihi: 3684 case X86::BI__builtin_ia32_kshiftlisi: 3685 case X86::BI__builtin_ia32_kshiftlidi: 3686 case X86::BI__builtin_ia32_kshiftriqi: 3687 case X86::BI__builtin_ia32_kshiftrihi: 3688 case X86::BI__builtin_ia32_kshiftrisi: 3689 case X86::BI__builtin_ia32_kshiftridi: 3690 i = 1; l = 0; u = 255; 3691 break; 3692 case X86::BI__builtin_ia32_vperm2f128_pd256: 3693 case X86::BI__builtin_ia32_vperm2f128_ps256: 3694 case X86::BI__builtin_ia32_vperm2f128_si256: 3695 case X86::BI__builtin_ia32_permti256: 3696 case X86::BI__builtin_ia32_pblendw128: 3697 case X86::BI__builtin_ia32_pblendw256: 3698 case X86::BI__builtin_ia32_blendps256: 3699 case X86::BI__builtin_ia32_pblendd256: 3700 case X86::BI__builtin_ia32_palignr128: 3701 case X86::BI__builtin_ia32_palignr256: 3702 case X86::BI__builtin_ia32_palignr512: 3703 case X86::BI__builtin_ia32_alignq512: 3704 case X86::BI__builtin_ia32_alignd512: 3705 case X86::BI__builtin_ia32_alignd128: 3706 case X86::BI__builtin_ia32_alignd256: 3707 case X86::BI__builtin_ia32_alignq128: 3708 case X86::BI__builtin_ia32_alignq256: 3709 case X86::BI__builtin_ia32_vcomisd: 3710 case X86::BI__builtin_ia32_vcomiss: 3711 case X86::BI__builtin_ia32_shuf_f32x4: 3712 case X86::BI__builtin_ia32_shuf_f64x2: 3713 case X86::BI__builtin_ia32_shuf_i32x4: 3714 case X86::BI__builtin_ia32_shuf_i64x2: 3715 case X86::BI__builtin_ia32_shufpd512: 3716 case X86::BI__builtin_ia32_shufps: 3717 case X86::BI__builtin_ia32_shufps256: 3718 case X86::BI__builtin_ia32_shufps512: 3719 case X86::BI__builtin_ia32_dbpsadbw128: 3720 case X86::BI__builtin_ia32_dbpsadbw256: 3721 case X86::BI__builtin_ia32_dbpsadbw512: 3722 case X86::BI__builtin_ia32_vpshldd128: 3723 case X86::BI__builtin_ia32_vpshldd256: 3724 case X86::BI__builtin_ia32_vpshldd512: 3725 case X86::BI__builtin_ia32_vpshldq128: 3726 case X86::BI__builtin_ia32_vpshldq256: 3727 case X86::BI__builtin_ia32_vpshldq512: 3728 case X86::BI__builtin_ia32_vpshldw128: 3729 case X86::BI__builtin_ia32_vpshldw256: 3730 case X86::BI__builtin_ia32_vpshldw512: 3731 case X86::BI__builtin_ia32_vpshrdd128: 3732 case X86::BI__builtin_ia32_vpshrdd256: 3733 case X86::BI__builtin_ia32_vpshrdd512: 3734 case X86::BI__builtin_ia32_vpshrdq128: 3735 case X86::BI__builtin_ia32_vpshrdq256: 3736 case X86::BI__builtin_ia32_vpshrdq512: 3737 case X86::BI__builtin_ia32_vpshrdw128: 3738 case X86::BI__builtin_ia32_vpshrdw256: 3739 case X86::BI__builtin_ia32_vpshrdw512: 3740 i = 2; l = 0; u = 255; 3741 break; 3742 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3743 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3744 case X86::BI__builtin_ia32_fixupimmps512_mask: 3745 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3746 case X86::BI__builtin_ia32_fixupimmsd_mask: 3747 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3748 case X86::BI__builtin_ia32_fixupimmss_mask: 3749 case X86::BI__builtin_ia32_fixupimmss_maskz: 3750 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3751 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3752 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3753 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3754 case X86::BI__builtin_ia32_fixupimmps128_mask: 3755 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3756 case X86::BI__builtin_ia32_fixupimmps256_mask: 3757 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3758 case X86::BI__builtin_ia32_pternlogd512_mask: 3759 case X86::BI__builtin_ia32_pternlogd512_maskz: 3760 case X86::BI__builtin_ia32_pternlogq512_mask: 3761 case X86::BI__builtin_ia32_pternlogq512_maskz: 3762 case X86::BI__builtin_ia32_pternlogd128_mask: 3763 case X86::BI__builtin_ia32_pternlogd128_maskz: 3764 case X86::BI__builtin_ia32_pternlogd256_mask: 3765 case X86::BI__builtin_ia32_pternlogd256_maskz: 3766 case X86::BI__builtin_ia32_pternlogq128_mask: 3767 case X86::BI__builtin_ia32_pternlogq128_maskz: 3768 case X86::BI__builtin_ia32_pternlogq256_mask: 3769 case X86::BI__builtin_ia32_pternlogq256_maskz: 3770 i = 3; l = 0; u = 255; 3771 break; 3772 case X86::BI__builtin_ia32_gatherpfdpd: 3773 case X86::BI__builtin_ia32_gatherpfdps: 3774 case X86::BI__builtin_ia32_gatherpfqpd: 3775 case X86::BI__builtin_ia32_gatherpfqps: 3776 case X86::BI__builtin_ia32_scatterpfdpd: 3777 case X86::BI__builtin_ia32_scatterpfdps: 3778 case X86::BI__builtin_ia32_scatterpfqpd: 3779 case X86::BI__builtin_ia32_scatterpfqps: 3780 i = 4; l = 2; u = 3; 3781 break; 3782 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3783 case X86::BI__builtin_ia32_rndscaless_round_mask: 3784 i = 4; l = 0; u = 255; 3785 break; 3786 } 3787 3788 // Note that we don't force a hard error on the range check here, allowing 3789 // template-generated or macro-generated dead code to potentially have out-of- 3790 // range values. These need to code generate, but don't need to necessarily 3791 // make any sense. We use a warning that defaults to an error. 3792 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3793 } 3794 3795 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3796 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3797 /// Returns true when the format fits the function and the FormatStringInfo has 3798 /// been populated. 3799 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3800 FormatStringInfo *FSI) { 3801 FSI->HasVAListArg = Format->getFirstArg() == 0; 3802 FSI->FormatIdx = Format->getFormatIdx() - 1; 3803 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3804 3805 // The way the format attribute works in GCC, the implicit this argument 3806 // of member functions is counted. However, it doesn't appear in our own 3807 // lists, so decrement format_idx in that case. 3808 if (IsCXXMember) { 3809 if(FSI->FormatIdx == 0) 3810 return false; 3811 --FSI->FormatIdx; 3812 if (FSI->FirstDataArg != 0) 3813 --FSI->FirstDataArg; 3814 } 3815 return true; 3816 } 3817 3818 /// Checks if a the given expression evaluates to null. 3819 /// 3820 /// Returns true if the value evaluates to null. 3821 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3822 // If the expression has non-null type, it doesn't evaluate to null. 3823 if (auto nullability 3824 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3825 if (*nullability == NullabilityKind::NonNull) 3826 return false; 3827 } 3828 3829 // As a special case, transparent unions initialized with zero are 3830 // considered null for the purposes of the nonnull attribute. 3831 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3832 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3833 if (const CompoundLiteralExpr *CLE = 3834 dyn_cast<CompoundLiteralExpr>(Expr)) 3835 if (const InitListExpr *ILE = 3836 dyn_cast<InitListExpr>(CLE->getInitializer())) 3837 Expr = ILE->getInit(0); 3838 } 3839 3840 bool Result; 3841 return (!Expr->isValueDependent() && 3842 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3843 !Result); 3844 } 3845 3846 static void CheckNonNullArgument(Sema &S, 3847 const Expr *ArgExpr, 3848 SourceLocation CallSiteLoc) { 3849 if (CheckNonNullExpr(S, ArgExpr)) 3850 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3851 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 3852 } 3853 3854 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3855 FormatStringInfo FSI; 3856 if ((GetFormatStringType(Format) == FST_NSString) && 3857 getFormatStringInfo(Format, false, &FSI)) { 3858 Idx = FSI.FormatIdx; 3859 return true; 3860 } 3861 return false; 3862 } 3863 3864 /// Diagnose use of %s directive in an NSString which is being passed 3865 /// as formatting string to formatting method. 3866 static void 3867 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3868 const NamedDecl *FDecl, 3869 Expr **Args, 3870 unsigned NumArgs) { 3871 unsigned Idx = 0; 3872 bool Format = false; 3873 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3874 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3875 Idx = 2; 3876 Format = true; 3877 } 3878 else 3879 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3880 if (S.GetFormatNSStringIdx(I, Idx)) { 3881 Format = true; 3882 break; 3883 } 3884 } 3885 if (!Format || NumArgs <= Idx) 3886 return; 3887 const Expr *FormatExpr = Args[Idx]; 3888 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3889 FormatExpr = CSCE->getSubExpr(); 3890 const StringLiteral *FormatString; 3891 if (const ObjCStringLiteral *OSL = 3892 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3893 FormatString = OSL->getString(); 3894 else 3895 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3896 if (!FormatString) 3897 return; 3898 if (S.FormatStringHasSArg(FormatString)) { 3899 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3900 << "%s" << 1 << 1; 3901 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3902 << FDecl->getDeclName(); 3903 } 3904 } 3905 3906 /// Determine whether the given type has a non-null nullability annotation. 3907 static bool isNonNullType(ASTContext &ctx, QualType type) { 3908 if (auto nullability = type->getNullability(ctx)) 3909 return *nullability == NullabilityKind::NonNull; 3910 3911 return false; 3912 } 3913 3914 static void CheckNonNullArguments(Sema &S, 3915 const NamedDecl *FDecl, 3916 const FunctionProtoType *Proto, 3917 ArrayRef<const Expr *> Args, 3918 SourceLocation CallSiteLoc) { 3919 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3920 3921 // Check the attributes attached to the method/function itself. 3922 llvm::SmallBitVector NonNullArgs; 3923 if (FDecl) { 3924 // Handle the nonnull attribute on the function/method declaration itself. 3925 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3926 if (!NonNull->args_size()) { 3927 // Easy case: all pointer arguments are nonnull. 3928 for (const auto *Arg : Args) 3929 if (S.isValidPointerAttrType(Arg->getType())) 3930 CheckNonNullArgument(S, Arg, CallSiteLoc); 3931 return; 3932 } 3933 3934 for (const ParamIdx &Idx : NonNull->args()) { 3935 unsigned IdxAST = Idx.getASTIndex(); 3936 if (IdxAST >= Args.size()) 3937 continue; 3938 if (NonNullArgs.empty()) 3939 NonNullArgs.resize(Args.size()); 3940 NonNullArgs.set(IdxAST); 3941 } 3942 } 3943 } 3944 3945 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3946 // Handle the nonnull attribute on the parameters of the 3947 // function/method. 3948 ArrayRef<ParmVarDecl*> parms; 3949 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3950 parms = FD->parameters(); 3951 else 3952 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3953 3954 unsigned ParamIndex = 0; 3955 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3956 I != E; ++I, ++ParamIndex) { 3957 const ParmVarDecl *PVD = *I; 3958 if (PVD->hasAttr<NonNullAttr>() || 3959 isNonNullType(S.Context, PVD->getType())) { 3960 if (NonNullArgs.empty()) 3961 NonNullArgs.resize(Args.size()); 3962 3963 NonNullArgs.set(ParamIndex); 3964 } 3965 } 3966 } else { 3967 // If we have a non-function, non-method declaration but no 3968 // function prototype, try to dig out the function prototype. 3969 if (!Proto) { 3970 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3971 QualType type = VD->getType().getNonReferenceType(); 3972 if (auto pointerType = type->getAs<PointerType>()) 3973 type = pointerType->getPointeeType(); 3974 else if (auto blockType = type->getAs<BlockPointerType>()) 3975 type = blockType->getPointeeType(); 3976 // FIXME: data member pointers? 3977 3978 // Dig out the function prototype, if there is one. 3979 Proto = type->getAs<FunctionProtoType>(); 3980 } 3981 } 3982 3983 // Fill in non-null argument information from the nullability 3984 // information on the parameter types (if we have them). 3985 if (Proto) { 3986 unsigned Index = 0; 3987 for (auto paramType : Proto->getParamTypes()) { 3988 if (isNonNullType(S.Context, paramType)) { 3989 if (NonNullArgs.empty()) 3990 NonNullArgs.resize(Args.size()); 3991 3992 NonNullArgs.set(Index); 3993 } 3994 3995 ++Index; 3996 } 3997 } 3998 } 3999 4000 // Check for non-null arguments. 4001 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4002 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4003 if (NonNullArgs[ArgIndex]) 4004 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4005 } 4006 } 4007 4008 /// Handles the checks for format strings, non-POD arguments to vararg 4009 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4010 /// attributes. 4011 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4012 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4013 bool IsMemberFunction, SourceLocation Loc, 4014 SourceRange Range, VariadicCallType CallType) { 4015 // FIXME: We should check as much as we can in the template definition. 4016 if (CurContext->isDependentContext()) 4017 return; 4018 4019 // Printf and scanf checking. 4020 llvm::SmallBitVector CheckedVarArgs; 4021 if (FDecl) { 4022 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4023 // Only create vector if there are format attributes. 4024 CheckedVarArgs.resize(Args.size()); 4025 4026 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4027 CheckedVarArgs); 4028 } 4029 } 4030 4031 // Refuse POD arguments that weren't caught by the format string 4032 // checks above. 4033 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4034 if (CallType != VariadicDoesNotApply && 4035 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4036 unsigned NumParams = Proto ? Proto->getNumParams() 4037 : FDecl && isa<FunctionDecl>(FDecl) 4038 ? cast<FunctionDecl>(FDecl)->getNumParams() 4039 : FDecl && isa<ObjCMethodDecl>(FDecl) 4040 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4041 : 0; 4042 4043 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4044 // Args[ArgIdx] can be null in malformed code. 4045 if (const Expr *Arg = Args[ArgIdx]) { 4046 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4047 checkVariadicArgument(Arg, CallType); 4048 } 4049 } 4050 } 4051 4052 if (FDecl || Proto) { 4053 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4054 4055 // Type safety checking. 4056 if (FDecl) { 4057 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4058 CheckArgumentWithTypeTag(I, Args, Loc); 4059 } 4060 } 4061 4062 if (FD) 4063 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4064 } 4065 4066 /// CheckConstructorCall - Check a constructor call for correctness and safety 4067 /// properties not enforced by the C type system. 4068 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4069 ArrayRef<const Expr *> Args, 4070 const FunctionProtoType *Proto, 4071 SourceLocation Loc) { 4072 VariadicCallType CallType = 4073 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4074 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4075 Loc, SourceRange(), CallType); 4076 } 4077 4078 /// CheckFunctionCall - Check a direct function call for various correctness 4079 /// and safety properties not strictly enforced by the C type system. 4080 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4081 const FunctionProtoType *Proto) { 4082 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4083 isa<CXXMethodDecl>(FDecl); 4084 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4085 IsMemberOperatorCall; 4086 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4087 TheCall->getCallee()); 4088 Expr** Args = TheCall->getArgs(); 4089 unsigned NumArgs = TheCall->getNumArgs(); 4090 4091 Expr *ImplicitThis = nullptr; 4092 if (IsMemberOperatorCall) { 4093 // If this is a call to a member operator, hide the first argument 4094 // from checkCall. 4095 // FIXME: Our choice of AST representation here is less than ideal. 4096 ImplicitThis = Args[0]; 4097 ++Args; 4098 --NumArgs; 4099 } else if (IsMemberFunction) 4100 ImplicitThis = 4101 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4102 4103 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4104 IsMemberFunction, TheCall->getRParenLoc(), 4105 TheCall->getCallee()->getSourceRange(), CallType); 4106 4107 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4108 // None of the checks below are needed for functions that don't have 4109 // simple names (e.g., C++ conversion functions). 4110 if (!FnInfo) 4111 return false; 4112 4113 CheckAbsoluteValueFunction(TheCall, FDecl); 4114 CheckMaxUnsignedZero(TheCall, FDecl); 4115 4116 if (getLangOpts().ObjC1) 4117 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4118 4119 unsigned CMId = FDecl->getMemoryFunctionKind(); 4120 if (CMId == 0) 4121 return false; 4122 4123 // Handle memory setting and copying functions. 4124 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4125 CheckStrlcpycatArguments(TheCall, FnInfo); 4126 else if (CMId == Builtin::BIstrncat) 4127 CheckStrncatArguments(TheCall, FnInfo); 4128 else 4129 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4130 4131 return false; 4132 } 4133 4134 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4135 ArrayRef<const Expr *> Args) { 4136 VariadicCallType CallType = 4137 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4138 4139 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4140 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4141 CallType); 4142 4143 return false; 4144 } 4145 4146 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4147 const FunctionProtoType *Proto) { 4148 QualType Ty; 4149 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4150 Ty = V->getType().getNonReferenceType(); 4151 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4152 Ty = F->getType().getNonReferenceType(); 4153 else 4154 return false; 4155 4156 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4157 !Ty->isFunctionProtoType()) 4158 return false; 4159 4160 VariadicCallType CallType; 4161 if (!Proto || !Proto->isVariadic()) { 4162 CallType = VariadicDoesNotApply; 4163 } else if (Ty->isBlockPointerType()) { 4164 CallType = VariadicBlock; 4165 } else { // Ty->isFunctionPointerType() 4166 CallType = VariadicFunction; 4167 } 4168 4169 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4170 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4171 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4172 TheCall->getCallee()->getSourceRange(), CallType); 4173 4174 return false; 4175 } 4176 4177 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4178 /// such as function pointers returned from functions. 4179 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4180 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4181 TheCall->getCallee()); 4182 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4183 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4184 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4185 TheCall->getCallee()->getSourceRange(), CallType); 4186 4187 return false; 4188 } 4189 4190 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4191 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4192 return false; 4193 4194 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4195 switch (Op) { 4196 case AtomicExpr::AO__c11_atomic_init: 4197 case AtomicExpr::AO__opencl_atomic_init: 4198 llvm_unreachable("There is no ordering argument for an init"); 4199 4200 case AtomicExpr::AO__c11_atomic_load: 4201 case AtomicExpr::AO__opencl_atomic_load: 4202 case AtomicExpr::AO__atomic_load_n: 4203 case AtomicExpr::AO__atomic_load: 4204 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4205 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4206 4207 case AtomicExpr::AO__c11_atomic_store: 4208 case AtomicExpr::AO__opencl_atomic_store: 4209 case AtomicExpr::AO__atomic_store: 4210 case AtomicExpr::AO__atomic_store_n: 4211 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4212 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4213 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4214 4215 default: 4216 return true; 4217 } 4218 } 4219 4220 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4221 AtomicExpr::AtomicOp Op) { 4222 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4223 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4224 4225 // All the non-OpenCL operations take one of the following forms. 4226 // The OpenCL operations take the __c11 forms with one extra argument for 4227 // synchronization scope. 4228 enum { 4229 // C __c11_atomic_init(A *, C) 4230 Init, 4231 4232 // C __c11_atomic_load(A *, int) 4233 Load, 4234 4235 // void __atomic_load(A *, CP, int) 4236 LoadCopy, 4237 4238 // void __atomic_store(A *, CP, int) 4239 Copy, 4240 4241 // C __c11_atomic_add(A *, M, int) 4242 Arithmetic, 4243 4244 // C __atomic_exchange_n(A *, CP, int) 4245 Xchg, 4246 4247 // void __atomic_exchange(A *, C *, CP, int) 4248 GNUXchg, 4249 4250 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4251 C11CmpXchg, 4252 4253 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4254 GNUCmpXchg 4255 } Form = Init; 4256 4257 const unsigned NumForm = GNUCmpXchg + 1; 4258 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4259 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4260 // where: 4261 // C is an appropriate type, 4262 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4263 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4264 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4265 // the int parameters are for orderings. 4266 4267 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4268 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4269 "need to update code for modified forms"); 4270 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4271 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4272 AtomicExpr::AO__atomic_load, 4273 "need to update code for modified C11 atomics"); 4274 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4275 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4276 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4277 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4278 IsOpenCL; 4279 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4280 Op == AtomicExpr::AO__atomic_store_n || 4281 Op == AtomicExpr::AO__atomic_exchange_n || 4282 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4283 bool IsAddSub = false; 4284 bool IsMinMax = false; 4285 4286 switch (Op) { 4287 case AtomicExpr::AO__c11_atomic_init: 4288 case AtomicExpr::AO__opencl_atomic_init: 4289 Form = Init; 4290 break; 4291 4292 case AtomicExpr::AO__c11_atomic_load: 4293 case AtomicExpr::AO__opencl_atomic_load: 4294 case AtomicExpr::AO__atomic_load_n: 4295 Form = Load; 4296 break; 4297 4298 case AtomicExpr::AO__atomic_load: 4299 Form = LoadCopy; 4300 break; 4301 4302 case AtomicExpr::AO__c11_atomic_store: 4303 case AtomicExpr::AO__opencl_atomic_store: 4304 case AtomicExpr::AO__atomic_store: 4305 case AtomicExpr::AO__atomic_store_n: 4306 Form = Copy; 4307 break; 4308 4309 case AtomicExpr::AO__c11_atomic_fetch_add: 4310 case AtomicExpr::AO__c11_atomic_fetch_sub: 4311 case AtomicExpr::AO__opencl_atomic_fetch_add: 4312 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4313 case AtomicExpr::AO__opencl_atomic_fetch_min: 4314 case AtomicExpr::AO__opencl_atomic_fetch_max: 4315 case AtomicExpr::AO__atomic_fetch_add: 4316 case AtomicExpr::AO__atomic_fetch_sub: 4317 case AtomicExpr::AO__atomic_add_fetch: 4318 case AtomicExpr::AO__atomic_sub_fetch: 4319 IsAddSub = true; 4320 LLVM_FALLTHROUGH; 4321 case AtomicExpr::AO__c11_atomic_fetch_and: 4322 case AtomicExpr::AO__c11_atomic_fetch_or: 4323 case AtomicExpr::AO__c11_atomic_fetch_xor: 4324 case AtomicExpr::AO__opencl_atomic_fetch_and: 4325 case AtomicExpr::AO__opencl_atomic_fetch_or: 4326 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4327 case AtomicExpr::AO__atomic_fetch_and: 4328 case AtomicExpr::AO__atomic_fetch_or: 4329 case AtomicExpr::AO__atomic_fetch_xor: 4330 case AtomicExpr::AO__atomic_fetch_nand: 4331 case AtomicExpr::AO__atomic_and_fetch: 4332 case AtomicExpr::AO__atomic_or_fetch: 4333 case AtomicExpr::AO__atomic_xor_fetch: 4334 case AtomicExpr::AO__atomic_nand_fetch: 4335 Form = Arithmetic; 4336 break; 4337 4338 case AtomicExpr::AO__atomic_fetch_min: 4339 case AtomicExpr::AO__atomic_fetch_max: 4340 IsMinMax = true; 4341 Form = Arithmetic; 4342 break; 4343 4344 case AtomicExpr::AO__c11_atomic_exchange: 4345 case AtomicExpr::AO__opencl_atomic_exchange: 4346 case AtomicExpr::AO__atomic_exchange_n: 4347 Form = Xchg; 4348 break; 4349 4350 case AtomicExpr::AO__atomic_exchange: 4351 Form = GNUXchg; 4352 break; 4353 4354 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4355 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4356 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4357 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4358 Form = C11CmpXchg; 4359 break; 4360 4361 case AtomicExpr::AO__atomic_compare_exchange: 4362 case AtomicExpr::AO__atomic_compare_exchange_n: 4363 Form = GNUCmpXchg; 4364 break; 4365 } 4366 4367 unsigned AdjustedNumArgs = NumArgs[Form]; 4368 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4369 ++AdjustedNumArgs; 4370 // Check we have the right number of arguments. 4371 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4372 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4373 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4374 << TheCall->getCallee()->getSourceRange(); 4375 return ExprError(); 4376 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4377 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4378 diag::err_typecheck_call_too_many_args) 4379 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4380 << TheCall->getCallee()->getSourceRange(); 4381 return ExprError(); 4382 } 4383 4384 // Inspect the first argument of the atomic operation. 4385 Expr *Ptr = TheCall->getArg(0); 4386 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4387 if (ConvertedPtr.isInvalid()) 4388 return ExprError(); 4389 4390 Ptr = ConvertedPtr.get(); 4391 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4392 if (!pointerType) { 4393 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4394 << Ptr->getType() << Ptr->getSourceRange(); 4395 return ExprError(); 4396 } 4397 4398 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4399 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4400 QualType ValType = AtomTy; // 'C' 4401 if (IsC11) { 4402 if (!AtomTy->isAtomicType()) { 4403 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4404 << Ptr->getType() << Ptr->getSourceRange(); 4405 return ExprError(); 4406 } 4407 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4408 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4409 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4410 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4411 << Ptr->getSourceRange(); 4412 return ExprError(); 4413 } 4414 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4415 } else if (Form != Load && Form != LoadCopy) { 4416 if (ValType.isConstQualified()) { 4417 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4418 << Ptr->getType() << Ptr->getSourceRange(); 4419 return ExprError(); 4420 } 4421 } 4422 4423 // For an arithmetic operation, the implied arithmetic must be well-formed. 4424 if (Form == Arithmetic) { 4425 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4426 if (IsAddSub && !ValType->isIntegerType() 4427 && !ValType->isPointerType()) { 4428 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4429 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4430 return ExprError(); 4431 } 4432 if (IsMinMax) { 4433 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4434 if (!BT || (BT->getKind() != BuiltinType::Int && 4435 BT->getKind() != BuiltinType::UInt)) { 4436 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4437 return ExprError(); 4438 } 4439 } 4440 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4441 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4442 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4443 return ExprError(); 4444 } 4445 if (IsC11 && ValType->isPointerType() && 4446 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4447 diag::err_incomplete_type)) { 4448 return ExprError(); 4449 } 4450 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4451 // For __atomic_*_n operations, the value type must be a scalar integral or 4452 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4453 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4454 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4455 return ExprError(); 4456 } 4457 4458 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4459 !AtomTy->isScalarType()) { 4460 // For GNU atomics, require a trivially-copyable type. This is not part of 4461 // the GNU atomics specification, but we enforce it for sanity. 4462 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4463 << Ptr->getType() << Ptr->getSourceRange(); 4464 return ExprError(); 4465 } 4466 4467 switch (ValType.getObjCLifetime()) { 4468 case Qualifiers::OCL_None: 4469 case Qualifiers::OCL_ExplicitNone: 4470 // okay 4471 break; 4472 4473 case Qualifiers::OCL_Weak: 4474 case Qualifiers::OCL_Strong: 4475 case Qualifiers::OCL_Autoreleasing: 4476 // FIXME: Can this happen? By this point, ValType should be known 4477 // to be trivially copyable. 4478 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4479 << ValType << Ptr->getSourceRange(); 4480 return ExprError(); 4481 } 4482 4483 // All atomic operations have an overload which takes a pointer to a volatile 4484 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4485 // into the result or the other operands. Similarly atomic_load takes a 4486 // pointer to a const 'A'. 4487 ValType.removeLocalVolatile(); 4488 ValType.removeLocalConst(); 4489 QualType ResultType = ValType; 4490 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4491 Form == Init) 4492 ResultType = Context.VoidTy; 4493 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4494 ResultType = Context.BoolTy; 4495 4496 // The type of a parameter passed 'by value'. In the GNU atomics, such 4497 // arguments are actually passed as pointers. 4498 QualType ByValType = ValType; // 'CP' 4499 bool IsPassedByAddress = false; 4500 if (!IsC11 && !IsN) { 4501 ByValType = Ptr->getType(); 4502 IsPassedByAddress = true; 4503 } 4504 4505 // The first argument's non-CV pointer type is used to deduce the type of 4506 // subsequent arguments, except for: 4507 // - weak flag (always converted to bool) 4508 // - memory order (always converted to int) 4509 // - scope (always converted to int) 4510 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4511 QualType Ty; 4512 if (i < NumVals[Form] + 1) { 4513 switch (i) { 4514 case 0: 4515 // The first argument is always a pointer. It has a fixed type. 4516 // It is always dereferenced, a nullptr is undefined. 4517 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4518 // Nothing else to do: we already know all we want about this pointer. 4519 continue; 4520 case 1: 4521 // The second argument is the non-atomic operand. For arithmetic, this 4522 // is always passed by value, and for a compare_exchange it is always 4523 // passed by address. For the rest, GNU uses by-address and C11 uses 4524 // by-value. 4525 assert(Form != Load); 4526 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4527 Ty = ValType; 4528 else if (Form == Copy || Form == Xchg) { 4529 if (IsPassedByAddress) 4530 // The value pointer is always dereferenced, a nullptr is undefined. 4531 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4532 Ty = ByValType; 4533 } else if (Form == Arithmetic) 4534 Ty = Context.getPointerDiffType(); 4535 else { 4536 Expr *ValArg = TheCall->getArg(i); 4537 // The value pointer is always dereferenced, a nullptr is undefined. 4538 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4539 LangAS AS = LangAS::Default; 4540 // Keep address space of non-atomic pointer type. 4541 if (const PointerType *PtrTy = 4542 ValArg->getType()->getAs<PointerType>()) { 4543 AS = PtrTy->getPointeeType().getAddressSpace(); 4544 } 4545 Ty = Context.getPointerType( 4546 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4547 } 4548 break; 4549 case 2: 4550 // The third argument to compare_exchange / GNU exchange is the desired 4551 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4552 if (IsPassedByAddress) 4553 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4554 Ty = ByValType; 4555 break; 4556 case 3: 4557 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4558 Ty = Context.BoolTy; 4559 break; 4560 } 4561 } else { 4562 // The order(s) and scope are always converted to int. 4563 Ty = Context.IntTy; 4564 } 4565 4566 InitializedEntity Entity = 4567 InitializedEntity::InitializeParameter(Context, Ty, false); 4568 ExprResult Arg = TheCall->getArg(i); 4569 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4570 if (Arg.isInvalid()) 4571 return true; 4572 TheCall->setArg(i, Arg.get()); 4573 } 4574 4575 // Permute the arguments into a 'consistent' order. 4576 SmallVector<Expr*, 5> SubExprs; 4577 SubExprs.push_back(Ptr); 4578 switch (Form) { 4579 case Init: 4580 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4581 SubExprs.push_back(TheCall->getArg(1)); // Val1 4582 break; 4583 case Load: 4584 SubExprs.push_back(TheCall->getArg(1)); // Order 4585 break; 4586 case LoadCopy: 4587 case Copy: 4588 case Arithmetic: 4589 case Xchg: 4590 SubExprs.push_back(TheCall->getArg(2)); // Order 4591 SubExprs.push_back(TheCall->getArg(1)); // Val1 4592 break; 4593 case GNUXchg: 4594 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4595 SubExprs.push_back(TheCall->getArg(3)); // Order 4596 SubExprs.push_back(TheCall->getArg(1)); // Val1 4597 SubExprs.push_back(TheCall->getArg(2)); // Val2 4598 break; 4599 case C11CmpXchg: 4600 SubExprs.push_back(TheCall->getArg(3)); // Order 4601 SubExprs.push_back(TheCall->getArg(1)); // Val1 4602 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4603 SubExprs.push_back(TheCall->getArg(2)); // Val2 4604 break; 4605 case GNUCmpXchg: 4606 SubExprs.push_back(TheCall->getArg(4)); // Order 4607 SubExprs.push_back(TheCall->getArg(1)); // Val1 4608 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4609 SubExprs.push_back(TheCall->getArg(2)); // Val2 4610 SubExprs.push_back(TheCall->getArg(3)); // Weak 4611 break; 4612 } 4613 4614 if (SubExprs.size() >= 2 && Form != Init) { 4615 llvm::APSInt Result(32); 4616 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4617 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4618 Diag(SubExprs[1]->getBeginLoc(), 4619 diag::warn_atomic_op_has_invalid_memory_order) 4620 << SubExprs[1]->getSourceRange(); 4621 } 4622 4623 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4624 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4625 llvm::APSInt Result(32); 4626 if (Scope->isIntegerConstantExpr(Result, Context) && 4627 !ScopeModel->isValid(Result.getZExtValue())) { 4628 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4629 << Scope->getSourceRange(); 4630 } 4631 SubExprs.push_back(Scope); 4632 } 4633 4634 AtomicExpr *AE = 4635 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4636 ResultType, Op, TheCall->getRParenLoc()); 4637 4638 if ((Op == AtomicExpr::AO__c11_atomic_load || 4639 Op == AtomicExpr::AO__c11_atomic_store || 4640 Op == AtomicExpr::AO__opencl_atomic_load || 4641 Op == AtomicExpr::AO__opencl_atomic_store ) && 4642 Context.AtomicUsesUnsupportedLibcall(AE)) 4643 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4644 << ((Op == AtomicExpr::AO__c11_atomic_load || 4645 Op == AtomicExpr::AO__opencl_atomic_load) 4646 ? 0 4647 : 1); 4648 4649 return AE; 4650 } 4651 4652 /// checkBuiltinArgument - Given a call to a builtin function, perform 4653 /// normal type-checking on the given argument, updating the call in 4654 /// place. This is useful when a builtin function requires custom 4655 /// type-checking for some of its arguments but not necessarily all of 4656 /// them. 4657 /// 4658 /// Returns true on error. 4659 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4660 FunctionDecl *Fn = E->getDirectCallee(); 4661 assert(Fn && "builtin call without direct callee!"); 4662 4663 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4664 InitializedEntity Entity = 4665 InitializedEntity::InitializeParameter(S.Context, Param); 4666 4667 ExprResult Arg = E->getArg(0); 4668 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4669 if (Arg.isInvalid()) 4670 return true; 4671 4672 E->setArg(ArgIndex, Arg.get()); 4673 return false; 4674 } 4675 4676 /// We have a call to a function like __sync_fetch_and_add, which is an 4677 /// overloaded function based on the pointer type of its first argument. 4678 /// The main ActOnCallExpr routines have already promoted the types of 4679 /// arguments because all of these calls are prototyped as void(...). 4680 /// 4681 /// This function goes through and does final semantic checking for these 4682 /// builtins, as well as generating any warnings. 4683 ExprResult 4684 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4685 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4686 Expr *Callee = TheCall->getCallee(); 4687 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4688 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4689 4690 // Ensure that we have at least one argument to do type inference from. 4691 if (TheCall->getNumArgs() < 1) { 4692 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4693 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4694 return ExprError(); 4695 } 4696 4697 // Inspect the first argument of the atomic builtin. This should always be 4698 // a pointer type, whose element is an integral scalar or pointer type. 4699 // Because it is a pointer type, we don't have to worry about any implicit 4700 // casts here. 4701 // FIXME: We don't allow floating point scalars as input. 4702 Expr *FirstArg = TheCall->getArg(0); 4703 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4704 if (FirstArgResult.isInvalid()) 4705 return ExprError(); 4706 FirstArg = FirstArgResult.get(); 4707 TheCall->setArg(0, FirstArg); 4708 4709 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4710 if (!pointerType) { 4711 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4712 << FirstArg->getType() << FirstArg->getSourceRange(); 4713 return ExprError(); 4714 } 4715 4716 QualType ValType = pointerType->getPointeeType(); 4717 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4718 !ValType->isBlockPointerType()) { 4719 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4720 << FirstArg->getType() << FirstArg->getSourceRange(); 4721 return ExprError(); 4722 } 4723 4724 if (ValType.isConstQualified()) { 4725 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4726 << FirstArg->getType() << FirstArg->getSourceRange(); 4727 return ExprError(); 4728 } 4729 4730 switch (ValType.getObjCLifetime()) { 4731 case Qualifiers::OCL_None: 4732 case Qualifiers::OCL_ExplicitNone: 4733 // okay 4734 break; 4735 4736 case Qualifiers::OCL_Weak: 4737 case Qualifiers::OCL_Strong: 4738 case Qualifiers::OCL_Autoreleasing: 4739 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4740 << ValType << FirstArg->getSourceRange(); 4741 return ExprError(); 4742 } 4743 4744 // Strip any qualifiers off ValType. 4745 ValType = ValType.getUnqualifiedType(); 4746 4747 // The majority of builtins return a value, but a few have special return 4748 // types, so allow them to override appropriately below. 4749 QualType ResultType = ValType; 4750 4751 // We need to figure out which concrete builtin this maps onto. For example, 4752 // __sync_fetch_and_add with a 2 byte object turns into 4753 // __sync_fetch_and_add_2. 4754 #define BUILTIN_ROW(x) \ 4755 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4756 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4757 4758 static const unsigned BuiltinIndices[][5] = { 4759 BUILTIN_ROW(__sync_fetch_and_add), 4760 BUILTIN_ROW(__sync_fetch_and_sub), 4761 BUILTIN_ROW(__sync_fetch_and_or), 4762 BUILTIN_ROW(__sync_fetch_and_and), 4763 BUILTIN_ROW(__sync_fetch_and_xor), 4764 BUILTIN_ROW(__sync_fetch_and_nand), 4765 4766 BUILTIN_ROW(__sync_add_and_fetch), 4767 BUILTIN_ROW(__sync_sub_and_fetch), 4768 BUILTIN_ROW(__sync_and_and_fetch), 4769 BUILTIN_ROW(__sync_or_and_fetch), 4770 BUILTIN_ROW(__sync_xor_and_fetch), 4771 BUILTIN_ROW(__sync_nand_and_fetch), 4772 4773 BUILTIN_ROW(__sync_val_compare_and_swap), 4774 BUILTIN_ROW(__sync_bool_compare_and_swap), 4775 BUILTIN_ROW(__sync_lock_test_and_set), 4776 BUILTIN_ROW(__sync_lock_release), 4777 BUILTIN_ROW(__sync_swap) 4778 }; 4779 #undef BUILTIN_ROW 4780 4781 // Determine the index of the size. 4782 unsigned SizeIndex; 4783 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4784 case 1: SizeIndex = 0; break; 4785 case 2: SizeIndex = 1; break; 4786 case 4: SizeIndex = 2; break; 4787 case 8: SizeIndex = 3; break; 4788 case 16: SizeIndex = 4; break; 4789 default: 4790 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4791 << FirstArg->getType() << FirstArg->getSourceRange(); 4792 return ExprError(); 4793 } 4794 4795 // Each of these builtins has one pointer argument, followed by some number of 4796 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4797 // that we ignore. Find out which row of BuiltinIndices to read from as well 4798 // as the number of fixed args. 4799 unsigned BuiltinID = FDecl->getBuiltinID(); 4800 unsigned BuiltinIndex, NumFixed = 1; 4801 bool WarnAboutSemanticsChange = false; 4802 switch (BuiltinID) { 4803 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4804 case Builtin::BI__sync_fetch_and_add: 4805 case Builtin::BI__sync_fetch_and_add_1: 4806 case Builtin::BI__sync_fetch_and_add_2: 4807 case Builtin::BI__sync_fetch_and_add_4: 4808 case Builtin::BI__sync_fetch_and_add_8: 4809 case Builtin::BI__sync_fetch_and_add_16: 4810 BuiltinIndex = 0; 4811 break; 4812 4813 case Builtin::BI__sync_fetch_and_sub: 4814 case Builtin::BI__sync_fetch_and_sub_1: 4815 case Builtin::BI__sync_fetch_and_sub_2: 4816 case Builtin::BI__sync_fetch_and_sub_4: 4817 case Builtin::BI__sync_fetch_and_sub_8: 4818 case Builtin::BI__sync_fetch_and_sub_16: 4819 BuiltinIndex = 1; 4820 break; 4821 4822 case Builtin::BI__sync_fetch_and_or: 4823 case Builtin::BI__sync_fetch_and_or_1: 4824 case Builtin::BI__sync_fetch_and_or_2: 4825 case Builtin::BI__sync_fetch_and_or_4: 4826 case Builtin::BI__sync_fetch_and_or_8: 4827 case Builtin::BI__sync_fetch_and_or_16: 4828 BuiltinIndex = 2; 4829 break; 4830 4831 case Builtin::BI__sync_fetch_and_and: 4832 case Builtin::BI__sync_fetch_and_and_1: 4833 case Builtin::BI__sync_fetch_and_and_2: 4834 case Builtin::BI__sync_fetch_and_and_4: 4835 case Builtin::BI__sync_fetch_and_and_8: 4836 case Builtin::BI__sync_fetch_and_and_16: 4837 BuiltinIndex = 3; 4838 break; 4839 4840 case Builtin::BI__sync_fetch_and_xor: 4841 case Builtin::BI__sync_fetch_and_xor_1: 4842 case Builtin::BI__sync_fetch_and_xor_2: 4843 case Builtin::BI__sync_fetch_and_xor_4: 4844 case Builtin::BI__sync_fetch_and_xor_8: 4845 case Builtin::BI__sync_fetch_and_xor_16: 4846 BuiltinIndex = 4; 4847 break; 4848 4849 case Builtin::BI__sync_fetch_and_nand: 4850 case Builtin::BI__sync_fetch_and_nand_1: 4851 case Builtin::BI__sync_fetch_and_nand_2: 4852 case Builtin::BI__sync_fetch_and_nand_4: 4853 case Builtin::BI__sync_fetch_and_nand_8: 4854 case Builtin::BI__sync_fetch_and_nand_16: 4855 BuiltinIndex = 5; 4856 WarnAboutSemanticsChange = true; 4857 break; 4858 4859 case Builtin::BI__sync_add_and_fetch: 4860 case Builtin::BI__sync_add_and_fetch_1: 4861 case Builtin::BI__sync_add_and_fetch_2: 4862 case Builtin::BI__sync_add_and_fetch_4: 4863 case Builtin::BI__sync_add_and_fetch_8: 4864 case Builtin::BI__sync_add_and_fetch_16: 4865 BuiltinIndex = 6; 4866 break; 4867 4868 case Builtin::BI__sync_sub_and_fetch: 4869 case Builtin::BI__sync_sub_and_fetch_1: 4870 case Builtin::BI__sync_sub_and_fetch_2: 4871 case Builtin::BI__sync_sub_and_fetch_4: 4872 case Builtin::BI__sync_sub_and_fetch_8: 4873 case Builtin::BI__sync_sub_and_fetch_16: 4874 BuiltinIndex = 7; 4875 break; 4876 4877 case Builtin::BI__sync_and_and_fetch: 4878 case Builtin::BI__sync_and_and_fetch_1: 4879 case Builtin::BI__sync_and_and_fetch_2: 4880 case Builtin::BI__sync_and_and_fetch_4: 4881 case Builtin::BI__sync_and_and_fetch_8: 4882 case Builtin::BI__sync_and_and_fetch_16: 4883 BuiltinIndex = 8; 4884 break; 4885 4886 case Builtin::BI__sync_or_and_fetch: 4887 case Builtin::BI__sync_or_and_fetch_1: 4888 case Builtin::BI__sync_or_and_fetch_2: 4889 case Builtin::BI__sync_or_and_fetch_4: 4890 case Builtin::BI__sync_or_and_fetch_8: 4891 case Builtin::BI__sync_or_and_fetch_16: 4892 BuiltinIndex = 9; 4893 break; 4894 4895 case Builtin::BI__sync_xor_and_fetch: 4896 case Builtin::BI__sync_xor_and_fetch_1: 4897 case Builtin::BI__sync_xor_and_fetch_2: 4898 case Builtin::BI__sync_xor_and_fetch_4: 4899 case Builtin::BI__sync_xor_and_fetch_8: 4900 case Builtin::BI__sync_xor_and_fetch_16: 4901 BuiltinIndex = 10; 4902 break; 4903 4904 case Builtin::BI__sync_nand_and_fetch: 4905 case Builtin::BI__sync_nand_and_fetch_1: 4906 case Builtin::BI__sync_nand_and_fetch_2: 4907 case Builtin::BI__sync_nand_and_fetch_4: 4908 case Builtin::BI__sync_nand_and_fetch_8: 4909 case Builtin::BI__sync_nand_and_fetch_16: 4910 BuiltinIndex = 11; 4911 WarnAboutSemanticsChange = true; 4912 break; 4913 4914 case Builtin::BI__sync_val_compare_and_swap: 4915 case Builtin::BI__sync_val_compare_and_swap_1: 4916 case Builtin::BI__sync_val_compare_and_swap_2: 4917 case Builtin::BI__sync_val_compare_and_swap_4: 4918 case Builtin::BI__sync_val_compare_and_swap_8: 4919 case Builtin::BI__sync_val_compare_and_swap_16: 4920 BuiltinIndex = 12; 4921 NumFixed = 2; 4922 break; 4923 4924 case Builtin::BI__sync_bool_compare_and_swap: 4925 case Builtin::BI__sync_bool_compare_and_swap_1: 4926 case Builtin::BI__sync_bool_compare_and_swap_2: 4927 case Builtin::BI__sync_bool_compare_and_swap_4: 4928 case Builtin::BI__sync_bool_compare_and_swap_8: 4929 case Builtin::BI__sync_bool_compare_and_swap_16: 4930 BuiltinIndex = 13; 4931 NumFixed = 2; 4932 ResultType = Context.BoolTy; 4933 break; 4934 4935 case Builtin::BI__sync_lock_test_and_set: 4936 case Builtin::BI__sync_lock_test_and_set_1: 4937 case Builtin::BI__sync_lock_test_and_set_2: 4938 case Builtin::BI__sync_lock_test_and_set_4: 4939 case Builtin::BI__sync_lock_test_and_set_8: 4940 case Builtin::BI__sync_lock_test_and_set_16: 4941 BuiltinIndex = 14; 4942 break; 4943 4944 case Builtin::BI__sync_lock_release: 4945 case Builtin::BI__sync_lock_release_1: 4946 case Builtin::BI__sync_lock_release_2: 4947 case Builtin::BI__sync_lock_release_4: 4948 case Builtin::BI__sync_lock_release_8: 4949 case Builtin::BI__sync_lock_release_16: 4950 BuiltinIndex = 15; 4951 NumFixed = 0; 4952 ResultType = Context.VoidTy; 4953 break; 4954 4955 case Builtin::BI__sync_swap: 4956 case Builtin::BI__sync_swap_1: 4957 case Builtin::BI__sync_swap_2: 4958 case Builtin::BI__sync_swap_4: 4959 case Builtin::BI__sync_swap_8: 4960 case Builtin::BI__sync_swap_16: 4961 BuiltinIndex = 16; 4962 break; 4963 } 4964 4965 // Now that we know how many fixed arguments we expect, first check that we 4966 // have at least that many. 4967 if (TheCall->getNumArgs() < 1+NumFixed) { 4968 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4969 << 0 << 1 + NumFixed << TheCall->getNumArgs() 4970 << Callee->getSourceRange(); 4971 return ExprError(); 4972 } 4973 4974 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 4975 << Callee->getSourceRange(); 4976 4977 if (WarnAboutSemanticsChange) { 4978 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4979 << Callee->getSourceRange(); 4980 } 4981 4982 // Get the decl for the concrete builtin from this, we can tell what the 4983 // concrete integer type we should convert to is. 4984 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4985 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4986 FunctionDecl *NewBuiltinDecl; 4987 if (NewBuiltinID == BuiltinID) 4988 NewBuiltinDecl = FDecl; 4989 else { 4990 // Perform builtin lookup to avoid redeclaring it. 4991 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4992 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 4993 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4994 assert(Res.getFoundDecl()); 4995 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4996 if (!NewBuiltinDecl) 4997 return ExprError(); 4998 } 4999 5000 // The first argument --- the pointer --- has a fixed type; we 5001 // deduce the types of the rest of the arguments accordingly. Walk 5002 // the remaining arguments, converting them to the deduced value type. 5003 for (unsigned i = 0; i != NumFixed; ++i) { 5004 ExprResult Arg = TheCall->getArg(i+1); 5005 5006 // GCC does an implicit conversion to the pointer or integer ValType. This 5007 // can fail in some cases (1i -> int**), check for this error case now. 5008 // Initialize the argument. 5009 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5010 ValType, /*consume*/ false); 5011 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5012 if (Arg.isInvalid()) 5013 return ExprError(); 5014 5015 // Okay, we have something that *can* be converted to the right type. Check 5016 // to see if there is a potentially weird extension going on here. This can 5017 // happen when you do an atomic operation on something like an char* and 5018 // pass in 42. The 42 gets converted to char. This is even more strange 5019 // for things like 45.123 -> char, etc. 5020 // FIXME: Do this check. 5021 TheCall->setArg(i+1, Arg.get()); 5022 } 5023 5024 ASTContext& Context = this->getASTContext(); 5025 5026 // Create a new DeclRefExpr to refer to the new decl. 5027 DeclRefExpr* NewDRE = DeclRefExpr::Create( 5028 Context, 5029 DRE->getQualifierLoc(), 5030 SourceLocation(), 5031 NewBuiltinDecl, 5032 /*enclosing*/ false, 5033 DRE->getLocation(), 5034 Context.BuiltinFnTy, 5035 DRE->getValueKind()); 5036 5037 // Set the callee in the CallExpr. 5038 // FIXME: This loses syntactic information. 5039 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5040 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5041 CK_BuiltinFnToFnPtr); 5042 TheCall->setCallee(PromotedCall.get()); 5043 5044 // Change the result type of the call to match the original value type. This 5045 // is arbitrary, but the codegen for these builtins ins design to handle it 5046 // gracefully. 5047 TheCall->setType(ResultType); 5048 5049 return TheCallResult; 5050 } 5051 5052 /// SemaBuiltinNontemporalOverloaded - We have a call to 5053 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5054 /// overloaded function based on the pointer type of its last argument. 5055 /// 5056 /// This function goes through and does final semantic checking for these 5057 /// builtins. 5058 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5059 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5060 DeclRefExpr *DRE = 5061 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5062 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5063 unsigned BuiltinID = FDecl->getBuiltinID(); 5064 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5065 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5066 "Unexpected nontemporal load/store builtin!"); 5067 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5068 unsigned numArgs = isStore ? 2 : 1; 5069 5070 // Ensure that we have the proper number of arguments. 5071 if (checkArgCount(*this, TheCall, numArgs)) 5072 return ExprError(); 5073 5074 // Inspect the last argument of the nontemporal builtin. This should always 5075 // be a pointer type, from which we imply the type of the memory access. 5076 // Because it is a pointer type, we don't have to worry about any implicit 5077 // casts here. 5078 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5079 ExprResult PointerArgResult = 5080 DefaultFunctionArrayLvalueConversion(PointerArg); 5081 5082 if (PointerArgResult.isInvalid()) 5083 return ExprError(); 5084 PointerArg = PointerArgResult.get(); 5085 TheCall->setArg(numArgs - 1, PointerArg); 5086 5087 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5088 if (!pointerType) { 5089 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5090 << PointerArg->getType() << PointerArg->getSourceRange(); 5091 return ExprError(); 5092 } 5093 5094 QualType ValType = pointerType->getPointeeType(); 5095 5096 // Strip any qualifiers off ValType. 5097 ValType = ValType.getUnqualifiedType(); 5098 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5099 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5100 !ValType->isVectorType()) { 5101 Diag(DRE->getBeginLoc(), 5102 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5103 << PointerArg->getType() << PointerArg->getSourceRange(); 5104 return ExprError(); 5105 } 5106 5107 if (!isStore) { 5108 TheCall->setType(ValType); 5109 return TheCallResult; 5110 } 5111 5112 ExprResult ValArg = TheCall->getArg(0); 5113 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5114 Context, ValType, /*consume*/ false); 5115 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5116 if (ValArg.isInvalid()) 5117 return ExprError(); 5118 5119 TheCall->setArg(0, ValArg.get()); 5120 TheCall->setType(Context.VoidTy); 5121 return TheCallResult; 5122 } 5123 5124 /// CheckObjCString - Checks that the argument to the builtin 5125 /// CFString constructor is correct 5126 /// Note: It might also make sense to do the UTF-16 conversion here (would 5127 /// simplify the backend). 5128 bool Sema::CheckObjCString(Expr *Arg) { 5129 Arg = Arg->IgnoreParenCasts(); 5130 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5131 5132 if (!Literal || !Literal->isAscii()) { 5133 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5134 << Arg->getSourceRange(); 5135 return true; 5136 } 5137 5138 if (Literal->containsNonAsciiOrNull()) { 5139 StringRef String = Literal->getString(); 5140 unsigned NumBytes = String.size(); 5141 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5142 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5143 llvm::UTF16 *ToPtr = &ToBuf[0]; 5144 5145 llvm::ConversionResult Result = 5146 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5147 ToPtr + NumBytes, llvm::strictConversion); 5148 // Check for conversion failure. 5149 if (Result != llvm::conversionOK) 5150 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5151 << Arg->getSourceRange(); 5152 } 5153 return false; 5154 } 5155 5156 /// CheckObjCString - Checks that the format string argument to the os_log() 5157 /// and os_trace() functions is correct, and converts it to const char *. 5158 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5159 Arg = Arg->IgnoreParenCasts(); 5160 auto *Literal = dyn_cast<StringLiteral>(Arg); 5161 if (!Literal) { 5162 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5163 Literal = ObjcLiteral->getString(); 5164 } 5165 } 5166 5167 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5168 return ExprError( 5169 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5170 << Arg->getSourceRange()); 5171 } 5172 5173 ExprResult Result(Literal); 5174 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5175 InitializedEntity Entity = 5176 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5177 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5178 return Result; 5179 } 5180 5181 /// Check that the user is calling the appropriate va_start builtin for the 5182 /// target and calling convention. 5183 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5184 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5185 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5186 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5187 bool IsWindows = TT.isOSWindows(); 5188 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5189 if (IsX64 || IsAArch64) { 5190 CallingConv CC = CC_C; 5191 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5192 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5193 if (IsMSVAStart) { 5194 // Don't allow this in System V ABI functions. 5195 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5196 return S.Diag(Fn->getBeginLoc(), 5197 diag::err_ms_va_start_used_in_sysv_function); 5198 } else { 5199 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5200 // On x64 Windows, don't allow this in System V ABI functions. 5201 // (Yes, that means there's no corresponding way to support variadic 5202 // System V ABI functions on Windows.) 5203 if ((IsWindows && CC == CC_X86_64SysV) || 5204 (!IsWindows && CC == CC_Win64)) 5205 return S.Diag(Fn->getBeginLoc(), 5206 diag::err_va_start_used_in_wrong_abi_function) 5207 << !IsWindows; 5208 } 5209 return false; 5210 } 5211 5212 if (IsMSVAStart) 5213 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5214 return false; 5215 } 5216 5217 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5218 ParmVarDecl **LastParam = nullptr) { 5219 // Determine whether the current function, block, or obj-c method is variadic 5220 // and get its parameter list. 5221 bool IsVariadic = false; 5222 ArrayRef<ParmVarDecl *> Params; 5223 DeclContext *Caller = S.CurContext; 5224 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5225 IsVariadic = Block->isVariadic(); 5226 Params = Block->parameters(); 5227 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5228 IsVariadic = FD->isVariadic(); 5229 Params = FD->parameters(); 5230 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5231 IsVariadic = MD->isVariadic(); 5232 // FIXME: This isn't correct for methods (results in bogus warning). 5233 Params = MD->parameters(); 5234 } else if (isa<CapturedDecl>(Caller)) { 5235 // We don't support va_start in a CapturedDecl. 5236 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5237 return true; 5238 } else { 5239 // This must be some other declcontext that parses exprs. 5240 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5241 return true; 5242 } 5243 5244 if (!IsVariadic) { 5245 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5246 return true; 5247 } 5248 5249 if (LastParam) 5250 *LastParam = Params.empty() ? nullptr : Params.back(); 5251 5252 return false; 5253 } 5254 5255 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5256 /// for validity. Emit an error and return true on failure; return false 5257 /// on success. 5258 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5259 Expr *Fn = TheCall->getCallee(); 5260 5261 if (checkVAStartABI(*this, BuiltinID, Fn)) 5262 return true; 5263 5264 if (TheCall->getNumArgs() > 2) { 5265 Diag(TheCall->getArg(2)->getBeginLoc(), 5266 diag::err_typecheck_call_too_many_args) 5267 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5268 << Fn->getSourceRange() 5269 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5270 (*(TheCall->arg_end() - 1))->getEndLoc()); 5271 return true; 5272 } 5273 5274 if (TheCall->getNumArgs() < 2) { 5275 return Diag(TheCall->getEndLoc(), 5276 diag::err_typecheck_call_too_few_args_at_least) 5277 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5278 } 5279 5280 // Type-check the first argument normally. 5281 if (checkBuiltinArgument(*this, TheCall, 0)) 5282 return true; 5283 5284 // Check that the current function is variadic, and get its last parameter. 5285 ParmVarDecl *LastParam; 5286 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5287 return true; 5288 5289 // Verify that the second argument to the builtin is the last argument of the 5290 // current function or method. 5291 bool SecondArgIsLastNamedArgument = false; 5292 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5293 5294 // These are valid if SecondArgIsLastNamedArgument is false after the next 5295 // block. 5296 QualType Type; 5297 SourceLocation ParamLoc; 5298 bool IsCRegister = false; 5299 5300 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5301 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5302 SecondArgIsLastNamedArgument = PV == LastParam; 5303 5304 Type = PV->getType(); 5305 ParamLoc = PV->getLocation(); 5306 IsCRegister = 5307 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5308 } 5309 } 5310 5311 if (!SecondArgIsLastNamedArgument) 5312 Diag(TheCall->getArg(1)->getBeginLoc(), 5313 diag::warn_second_arg_of_va_start_not_last_named_param); 5314 else if (IsCRegister || Type->isReferenceType() || 5315 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5316 // Promotable integers are UB, but enumerations need a bit of 5317 // extra checking to see what their promotable type actually is. 5318 if (!Type->isPromotableIntegerType()) 5319 return false; 5320 if (!Type->isEnumeralType()) 5321 return true; 5322 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5323 return !(ED && 5324 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5325 }()) { 5326 unsigned Reason = 0; 5327 if (Type->isReferenceType()) Reason = 1; 5328 else if (IsCRegister) Reason = 2; 5329 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5330 Diag(ParamLoc, diag::note_parameter_type) << Type; 5331 } 5332 5333 TheCall->setType(Context.VoidTy); 5334 return false; 5335 } 5336 5337 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5338 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5339 // const char *named_addr); 5340 5341 Expr *Func = Call->getCallee(); 5342 5343 if (Call->getNumArgs() < 3) 5344 return Diag(Call->getEndLoc(), 5345 diag::err_typecheck_call_too_few_args_at_least) 5346 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5347 5348 // Type-check the first argument normally. 5349 if (checkBuiltinArgument(*this, Call, 0)) 5350 return true; 5351 5352 // Check that the current function is variadic. 5353 if (checkVAStartIsInVariadicFunction(*this, Func)) 5354 return true; 5355 5356 // __va_start on Windows does not validate the parameter qualifiers 5357 5358 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5359 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5360 5361 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5362 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5363 5364 const QualType &ConstCharPtrTy = 5365 Context.getPointerType(Context.CharTy.withConst()); 5366 if (!Arg1Ty->isPointerType() || 5367 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5368 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5369 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5370 << 0 /* qualifier difference */ 5371 << 3 /* parameter mismatch */ 5372 << 2 << Arg1->getType() << ConstCharPtrTy; 5373 5374 const QualType SizeTy = Context.getSizeType(); 5375 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5376 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5377 << Arg2->getType() << SizeTy << 1 /* different class */ 5378 << 0 /* qualifier difference */ 5379 << 3 /* parameter mismatch */ 5380 << 3 << Arg2->getType() << SizeTy; 5381 5382 return false; 5383 } 5384 5385 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5386 /// friends. This is declared to take (...), so we have to check everything. 5387 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5388 if (TheCall->getNumArgs() < 2) 5389 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5390 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5391 if (TheCall->getNumArgs() > 2) 5392 return Diag(TheCall->getArg(2)->getBeginLoc(), 5393 diag::err_typecheck_call_too_many_args) 5394 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5395 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5396 (*(TheCall->arg_end() - 1))->getEndLoc()); 5397 5398 ExprResult OrigArg0 = TheCall->getArg(0); 5399 ExprResult OrigArg1 = TheCall->getArg(1); 5400 5401 // Do standard promotions between the two arguments, returning their common 5402 // type. 5403 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5404 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5405 return true; 5406 5407 // Make sure any conversions are pushed back into the call; this is 5408 // type safe since unordered compare builtins are declared as "_Bool 5409 // foo(...)". 5410 TheCall->setArg(0, OrigArg0.get()); 5411 TheCall->setArg(1, OrigArg1.get()); 5412 5413 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5414 return false; 5415 5416 // If the common type isn't a real floating type, then the arguments were 5417 // invalid for this operation. 5418 if (Res.isNull() || !Res->isRealFloatingType()) 5419 return Diag(OrigArg0.get()->getBeginLoc(), 5420 diag::err_typecheck_call_invalid_ordered_compare) 5421 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5422 << SourceRange(OrigArg0.get()->getBeginLoc(), 5423 OrigArg1.get()->getEndLoc()); 5424 5425 return false; 5426 } 5427 5428 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5429 /// __builtin_isnan and friends. This is declared to take (...), so we have 5430 /// to check everything. We expect the last argument to be a floating point 5431 /// value. 5432 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5433 if (TheCall->getNumArgs() < NumArgs) 5434 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5435 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5436 if (TheCall->getNumArgs() > NumArgs) 5437 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5438 diag::err_typecheck_call_too_many_args) 5439 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5440 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5441 (*(TheCall->arg_end() - 1))->getEndLoc()); 5442 5443 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5444 5445 if (OrigArg->isTypeDependent()) 5446 return false; 5447 5448 // This operation requires a non-_Complex floating-point number. 5449 if (!OrigArg->getType()->isRealFloatingType()) 5450 return Diag(OrigArg->getBeginLoc(), 5451 diag::err_typecheck_call_invalid_unary_fp) 5452 << OrigArg->getType() << OrigArg->getSourceRange(); 5453 5454 // If this is an implicit conversion from float -> float, double, or 5455 // long double, remove it. 5456 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5457 // Only remove standard FloatCasts, leaving other casts inplace 5458 if (Cast->getCastKind() == CK_FloatingCast) { 5459 Expr *CastArg = Cast->getSubExpr(); 5460 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5461 assert( 5462 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5463 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5464 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5465 "promotion from float to either float, double, or long double is " 5466 "the only expected cast here"); 5467 Cast->setSubExpr(nullptr); 5468 TheCall->setArg(NumArgs-1, CastArg); 5469 } 5470 } 5471 } 5472 5473 return false; 5474 } 5475 5476 // Customized Sema Checking for VSX builtins that have the following signature: 5477 // vector [...] builtinName(vector [...], vector [...], const int); 5478 // Which takes the same type of vectors (any legal vector type) for the first 5479 // two arguments and takes compile time constant for the third argument. 5480 // Example builtins are : 5481 // vector double vec_xxpermdi(vector double, vector double, int); 5482 // vector short vec_xxsldwi(vector short, vector short, int); 5483 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5484 unsigned ExpectedNumArgs = 3; 5485 if (TheCall->getNumArgs() < ExpectedNumArgs) 5486 return Diag(TheCall->getEndLoc(), 5487 diag::err_typecheck_call_too_few_args_at_least) 5488 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5489 << TheCall->getSourceRange(); 5490 5491 if (TheCall->getNumArgs() > ExpectedNumArgs) 5492 return Diag(TheCall->getEndLoc(), 5493 diag::err_typecheck_call_too_many_args_at_most) 5494 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5495 << TheCall->getSourceRange(); 5496 5497 // Check the third argument is a compile time constant 5498 llvm::APSInt Value; 5499 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5500 return Diag(TheCall->getBeginLoc(), 5501 diag::err_vsx_builtin_nonconstant_argument) 5502 << 3 /* argument index */ << TheCall->getDirectCallee() 5503 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5504 TheCall->getArg(2)->getEndLoc()); 5505 5506 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5507 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5508 5509 // Check the type of argument 1 and argument 2 are vectors. 5510 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5511 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5512 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5513 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5514 << TheCall->getDirectCallee() 5515 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5516 TheCall->getArg(1)->getEndLoc()); 5517 } 5518 5519 // Check the first two arguments are the same type. 5520 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5521 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5522 << TheCall->getDirectCallee() 5523 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5524 TheCall->getArg(1)->getEndLoc()); 5525 } 5526 5527 // When default clang type checking is turned off and the customized type 5528 // checking is used, the returning type of the function must be explicitly 5529 // set. Otherwise it is _Bool by default. 5530 TheCall->setType(Arg1Ty); 5531 5532 return false; 5533 } 5534 5535 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5536 // This is declared to take (...), so we have to check everything. 5537 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5538 if (TheCall->getNumArgs() < 2) 5539 return ExprError(Diag(TheCall->getEndLoc(), 5540 diag::err_typecheck_call_too_few_args_at_least) 5541 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5542 << TheCall->getSourceRange()); 5543 5544 // Determine which of the following types of shufflevector we're checking: 5545 // 1) unary, vector mask: (lhs, mask) 5546 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5547 QualType resType = TheCall->getArg(0)->getType(); 5548 unsigned numElements = 0; 5549 5550 if (!TheCall->getArg(0)->isTypeDependent() && 5551 !TheCall->getArg(1)->isTypeDependent()) { 5552 QualType LHSType = TheCall->getArg(0)->getType(); 5553 QualType RHSType = TheCall->getArg(1)->getType(); 5554 5555 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5556 return ExprError( 5557 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5558 << TheCall->getDirectCallee() 5559 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5560 TheCall->getArg(1)->getEndLoc())); 5561 5562 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5563 unsigned numResElements = TheCall->getNumArgs() - 2; 5564 5565 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5566 // with mask. If so, verify that RHS is an integer vector type with the 5567 // same number of elts as lhs. 5568 if (TheCall->getNumArgs() == 2) { 5569 if (!RHSType->hasIntegerRepresentation() || 5570 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5571 return ExprError(Diag(TheCall->getBeginLoc(), 5572 diag::err_vec_builtin_incompatible_vector) 5573 << TheCall->getDirectCallee() 5574 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5575 TheCall->getArg(1)->getEndLoc())); 5576 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5577 return ExprError(Diag(TheCall->getBeginLoc(), 5578 diag::err_vec_builtin_incompatible_vector) 5579 << TheCall->getDirectCallee() 5580 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5581 TheCall->getArg(1)->getEndLoc())); 5582 } else if (numElements != numResElements) { 5583 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5584 resType = Context.getVectorType(eltType, numResElements, 5585 VectorType::GenericVector); 5586 } 5587 } 5588 5589 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5590 if (TheCall->getArg(i)->isTypeDependent() || 5591 TheCall->getArg(i)->isValueDependent()) 5592 continue; 5593 5594 llvm::APSInt Result(32); 5595 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5596 return ExprError(Diag(TheCall->getBeginLoc(), 5597 diag::err_shufflevector_nonconstant_argument) 5598 << TheCall->getArg(i)->getSourceRange()); 5599 5600 // Allow -1 which will be translated to undef in the IR. 5601 if (Result.isSigned() && Result.isAllOnesValue()) 5602 continue; 5603 5604 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5605 return ExprError(Diag(TheCall->getBeginLoc(), 5606 diag::err_shufflevector_argument_too_large) 5607 << TheCall->getArg(i)->getSourceRange()); 5608 } 5609 5610 SmallVector<Expr*, 32> exprs; 5611 5612 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5613 exprs.push_back(TheCall->getArg(i)); 5614 TheCall->setArg(i, nullptr); 5615 } 5616 5617 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5618 TheCall->getCallee()->getBeginLoc(), 5619 TheCall->getRParenLoc()); 5620 } 5621 5622 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5623 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5624 SourceLocation BuiltinLoc, 5625 SourceLocation RParenLoc) { 5626 ExprValueKind VK = VK_RValue; 5627 ExprObjectKind OK = OK_Ordinary; 5628 QualType DstTy = TInfo->getType(); 5629 QualType SrcTy = E->getType(); 5630 5631 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5632 return ExprError(Diag(BuiltinLoc, 5633 diag::err_convertvector_non_vector) 5634 << E->getSourceRange()); 5635 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5636 return ExprError(Diag(BuiltinLoc, 5637 diag::err_convertvector_non_vector_type)); 5638 5639 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5640 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5641 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5642 if (SrcElts != DstElts) 5643 return ExprError(Diag(BuiltinLoc, 5644 diag::err_convertvector_incompatible_vector) 5645 << E->getSourceRange()); 5646 } 5647 5648 return new (Context) 5649 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5650 } 5651 5652 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5653 // This is declared to take (const void*, ...) and can take two 5654 // optional constant int args. 5655 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5656 unsigned NumArgs = TheCall->getNumArgs(); 5657 5658 if (NumArgs > 3) 5659 return Diag(TheCall->getEndLoc(), 5660 diag::err_typecheck_call_too_many_args_at_most) 5661 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5662 5663 // Argument 0 is checked for us and the remaining arguments must be 5664 // constant integers. 5665 for (unsigned i = 1; i != NumArgs; ++i) 5666 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5667 return true; 5668 5669 return false; 5670 } 5671 5672 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5673 // __assume does not evaluate its arguments, and should warn if its argument 5674 // has side effects. 5675 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5676 Expr *Arg = TheCall->getArg(0); 5677 if (Arg->isInstantiationDependent()) return false; 5678 5679 if (Arg->HasSideEffects(Context)) 5680 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5681 << Arg->getSourceRange() 5682 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5683 5684 return false; 5685 } 5686 5687 /// Handle __builtin_alloca_with_align. This is declared 5688 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5689 /// than 8. 5690 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5691 // The alignment must be a constant integer. 5692 Expr *Arg = TheCall->getArg(1); 5693 5694 // We can't check the value of a dependent argument. 5695 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5696 if (const auto *UE = 5697 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5698 if (UE->getKind() == UETT_AlignOf) 5699 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5700 << Arg->getSourceRange(); 5701 5702 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5703 5704 if (!Result.isPowerOf2()) 5705 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5706 << Arg->getSourceRange(); 5707 5708 if (Result < Context.getCharWidth()) 5709 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5710 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5711 5712 if (Result > std::numeric_limits<int32_t>::max()) 5713 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5714 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5715 } 5716 5717 return false; 5718 } 5719 5720 /// Handle __builtin_assume_aligned. This is declared 5721 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5722 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5723 unsigned NumArgs = TheCall->getNumArgs(); 5724 5725 if (NumArgs > 3) 5726 return Diag(TheCall->getEndLoc(), 5727 diag::err_typecheck_call_too_many_args_at_most) 5728 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5729 5730 // The alignment must be a constant integer. 5731 Expr *Arg = TheCall->getArg(1); 5732 5733 // We can't check the value of a dependent argument. 5734 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5735 llvm::APSInt Result; 5736 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5737 return true; 5738 5739 if (!Result.isPowerOf2()) 5740 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5741 << Arg->getSourceRange(); 5742 } 5743 5744 if (NumArgs > 2) { 5745 ExprResult Arg(TheCall->getArg(2)); 5746 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5747 Context.getSizeType(), false); 5748 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5749 if (Arg.isInvalid()) return true; 5750 TheCall->setArg(2, Arg.get()); 5751 } 5752 5753 return false; 5754 } 5755 5756 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5757 unsigned BuiltinID = 5758 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5759 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5760 5761 unsigned NumArgs = TheCall->getNumArgs(); 5762 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5763 if (NumArgs < NumRequiredArgs) { 5764 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5765 << 0 /* function call */ << NumRequiredArgs << NumArgs 5766 << TheCall->getSourceRange(); 5767 } 5768 if (NumArgs >= NumRequiredArgs + 0x100) { 5769 return Diag(TheCall->getEndLoc(), 5770 diag::err_typecheck_call_too_many_args_at_most) 5771 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5772 << TheCall->getSourceRange(); 5773 } 5774 unsigned i = 0; 5775 5776 // For formatting call, check buffer arg. 5777 if (!IsSizeCall) { 5778 ExprResult Arg(TheCall->getArg(i)); 5779 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5780 Context, Context.VoidPtrTy, false); 5781 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5782 if (Arg.isInvalid()) 5783 return true; 5784 TheCall->setArg(i, Arg.get()); 5785 i++; 5786 } 5787 5788 // Check string literal arg. 5789 unsigned FormatIdx = i; 5790 { 5791 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5792 if (Arg.isInvalid()) 5793 return true; 5794 TheCall->setArg(i, Arg.get()); 5795 i++; 5796 } 5797 5798 // Make sure variadic args are scalar. 5799 unsigned FirstDataArg = i; 5800 while (i < NumArgs) { 5801 ExprResult Arg = DefaultVariadicArgumentPromotion( 5802 TheCall->getArg(i), VariadicFunction, nullptr); 5803 if (Arg.isInvalid()) 5804 return true; 5805 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5806 if (ArgSize.getQuantity() >= 0x100) { 5807 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5808 << i << (int)ArgSize.getQuantity() << 0xff 5809 << TheCall->getSourceRange(); 5810 } 5811 TheCall->setArg(i, Arg.get()); 5812 i++; 5813 } 5814 5815 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5816 // call to avoid duplicate diagnostics. 5817 if (!IsSizeCall) { 5818 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5819 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5820 bool Success = CheckFormatArguments( 5821 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5822 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5823 CheckedVarArgs); 5824 if (!Success) 5825 return true; 5826 } 5827 5828 if (IsSizeCall) { 5829 TheCall->setType(Context.getSizeType()); 5830 } else { 5831 TheCall->setType(Context.VoidPtrTy); 5832 } 5833 return false; 5834 } 5835 5836 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5837 /// TheCall is a constant expression. 5838 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5839 llvm::APSInt &Result) { 5840 Expr *Arg = TheCall->getArg(ArgNum); 5841 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5842 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5843 5844 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5845 5846 if (!Arg->isIntegerConstantExpr(Result, Context)) 5847 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5848 << FDecl->getDeclName() << Arg->getSourceRange(); 5849 5850 return false; 5851 } 5852 5853 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5854 /// TheCall is a constant expression in the range [Low, High]. 5855 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5856 int Low, int High, bool RangeIsError) { 5857 llvm::APSInt Result; 5858 5859 // We can't check the value of a dependent argument. 5860 Expr *Arg = TheCall->getArg(ArgNum); 5861 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5862 return false; 5863 5864 // Check constant-ness first. 5865 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5866 return true; 5867 5868 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5869 if (RangeIsError) 5870 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5871 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5872 else 5873 // Defer the warning until we know if the code will be emitted so that 5874 // dead code can ignore this. 5875 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5876 PDiag(diag::warn_argument_invalid_range) 5877 << Result.toString(10) << Low << High 5878 << Arg->getSourceRange()); 5879 } 5880 5881 return false; 5882 } 5883 5884 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5885 /// TheCall is a constant expression is a multiple of Num.. 5886 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5887 unsigned Num) { 5888 llvm::APSInt Result; 5889 5890 // We can't check the value of a dependent argument. 5891 Expr *Arg = TheCall->getArg(ArgNum); 5892 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5893 return false; 5894 5895 // Check constant-ness first. 5896 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5897 return true; 5898 5899 if (Result.getSExtValue() % Num != 0) 5900 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5901 << Num << Arg->getSourceRange(); 5902 5903 return false; 5904 } 5905 5906 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 5907 /// TheCall is an ARM/AArch64 special register string literal. 5908 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 5909 int ArgNum, unsigned ExpectedFieldNum, 5910 bool AllowName) { 5911 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 5912 BuiltinID == ARM::BI__builtin_arm_wsr64 || 5913 BuiltinID == ARM::BI__builtin_arm_rsr || 5914 BuiltinID == ARM::BI__builtin_arm_rsrp || 5915 BuiltinID == ARM::BI__builtin_arm_wsr || 5916 BuiltinID == ARM::BI__builtin_arm_wsrp; 5917 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 5918 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 5919 BuiltinID == AArch64::BI__builtin_arm_rsr || 5920 BuiltinID == AArch64::BI__builtin_arm_rsrp || 5921 BuiltinID == AArch64::BI__builtin_arm_wsr || 5922 BuiltinID == AArch64::BI__builtin_arm_wsrp; 5923 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 5924 5925 // We can't check the value of a dependent argument. 5926 Expr *Arg = TheCall->getArg(ArgNum); 5927 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5928 return false; 5929 5930 // Check if the argument is a string literal. 5931 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 5932 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 5933 << Arg->getSourceRange(); 5934 5935 // Check the type of special register given. 5936 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 5937 SmallVector<StringRef, 6> Fields; 5938 Reg.split(Fields, ":"); 5939 5940 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 5941 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5942 << Arg->getSourceRange(); 5943 5944 // If the string is the name of a register then we cannot check that it is 5945 // valid here but if the string is of one the forms described in ACLE then we 5946 // can check that the supplied fields are integers and within the valid 5947 // ranges. 5948 if (Fields.size() > 1) { 5949 bool FiveFields = Fields.size() == 5; 5950 5951 bool ValidString = true; 5952 if (IsARMBuiltin) { 5953 ValidString &= Fields[0].startswith_lower("cp") || 5954 Fields[0].startswith_lower("p"); 5955 if (ValidString) 5956 Fields[0] = 5957 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 5958 5959 ValidString &= Fields[2].startswith_lower("c"); 5960 if (ValidString) 5961 Fields[2] = Fields[2].drop_front(1); 5962 5963 if (FiveFields) { 5964 ValidString &= Fields[3].startswith_lower("c"); 5965 if (ValidString) 5966 Fields[3] = Fields[3].drop_front(1); 5967 } 5968 } 5969 5970 SmallVector<int, 5> Ranges; 5971 if (FiveFields) 5972 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 5973 else 5974 Ranges.append({15, 7, 15}); 5975 5976 for (unsigned i=0; i<Fields.size(); ++i) { 5977 int IntField; 5978 ValidString &= !Fields[i].getAsInteger(10, IntField); 5979 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 5980 } 5981 5982 if (!ValidString) 5983 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 5984 << Arg->getSourceRange(); 5985 } else if (IsAArch64Builtin && Fields.size() == 1) { 5986 // If the register name is one of those that appear in the condition below 5987 // and the special register builtin being used is one of the write builtins, 5988 // then we require that the argument provided for writing to the register 5989 // is an integer constant expression. This is because it will be lowered to 5990 // an MSR (immediate) instruction, so we need to know the immediate at 5991 // compile time. 5992 if (TheCall->getNumArgs() != 2) 5993 return false; 5994 5995 std::string RegLower = Reg.lower(); 5996 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 5997 RegLower != "pan" && RegLower != "uao") 5998 return false; 5999 6000 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6001 } 6002 6003 return false; 6004 } 6005 6006 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6007 /// This checks that the target supports __builtin_longjmp and 6008 /// that val is a constant 1. 6009 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6010 if (!Context.getTargetInfo().hasSjLjLowering()) 6011 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6012 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6013 6014 Expr *Arg = TheCall->getArg(1); 6015 llvm::APSInt Result; 6016 6017 // TODO: This is less than ideal. Overload this to take a value. 6018 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6019 return true; 6020 6021 if (Result != 1) 6022 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6023 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6024 6025 return false; 6026 } 6027 6028 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6029 /// This checks that the target supports __builtin_setjmp. 6030 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6031 if (!Context.getTargetInfo().hasSjLjLowering()) 6032 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6033 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6034 return false; 6035 } 6036 6037 namespace { 6038 6039 class UncoveredArgHandler { 6040 enum { Unknown = -1, AllCovered = -2 }; 6041 6042 signed FirstUncoveredArg = Unknown; 6043 SmallVector<const Expr *, 4> DiagnosticExprs; 6044 6045 public: 6046 UncoveredArgHandler() = default; 6047 6048 bool hasUncoveredArg() const { 6049 return (FirstUncoveredArg >= 0); 6050 } 6051 6052 unsigned getUncoveredArg() const { 6053 assert(hasUncoveredArg() && "no uncovered argument"); 6054 return FirstUncoveredArg; 6055 } 6056 6057 void setAllCovered() { 6058 // A string has been found with all arguments covered, so clear out 6059 // the diagnostics. 6060 DiagnosticExprs.clear(); 6061 FirstUncoveredArg = AllCovered; 6062 } 6063 6064 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6065 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6066 6067 // Don't update if a previous string covers all arguments. 6068 if (FirstUncoveredArg == AllCovered) 6069 return; 6070 6071 // UncoveredArgHandler tracks the highest uncovered argument index 6072 // and with it all the strings that match this index. 6073 if (NewFirstUncoveredArg == FirstUncoveredArg) 6074 DiagnosticExprs.push_back(StrExpr); 6075 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6076 DiagnosticExprs.clear(); 6077 DiagnosticExprs.push_back(StrExpr); 6078 FirstUncoveredArg = NewFirstUncoveredArg; 6079 } 6080 } 6081 6082 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6083 }; 6084 6085 enum StringLiteralCheckType { 6086 SLCT_NotALiteral, 6087 SLCT_UncheckedLiteral, 6088 SLCT_CheckedLiteral 6089 }; 6090 6091 } // namespace 6092 6093 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6094 BinaryOperatorKind BinOpKind, 6095 bool AddendIsRight) { 6096 unsigned BitWidth = Offset.getBitWidth(); 6097 unsigned AddendBitWidth = Addend.getBitWidth(); 6098 // There might be negative interim results. 6099 if (Addend.isUnsigned()) { 6100 Addend = Addend.zext(++AddendBitWidth); 6101 Addend.setIsSigned(true); 6102 } 6103 // Adjust the bit width of the APSInts. 6104 if (AddendBitWidth > BitWidth) { 6105 Offset = Offset.sext(AddendBitWidth); 6106 BitWidth = AddendBitWidth; 6107 } else if (BitWidth > AddendBitWidth) { 6108 Addend = Addend.sext(BitWidth); 6109 } 6110 6111 bool Ov = false; 6112 llvm::APSInt ResOffset = Offset; 6113 if (BinOpKind == BO_Add) 6114 ResOffset = Offset.sadd_ov(Addend, Ov); 6115 else { 6116 assert(AddendIsRight && BinOpKind == BO_Sub && 6117 "operator must be add or sub with addend on the right"); 6118 ResOffset = Offset.ssub_ov(Addend, Ov); 6119 } 6120 6121 // We add an offset to a pointer here so we should support an offset as big as 6122 // possible. 6123 if (Ov) { 6124 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6125 "index (intermediate) result too big"); 6126 Offset = Offset.sext(2 * BitWidth); 6127 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6128 return; 6129 } 6130 6131 Offset = ResOffset; 6132 } 6133 6134 namespace { 6135 6136 // This is a wrapper class around StringLiteral to support offsetted string 6137 // literals as format strings. It takes the offset into account when returning 6138 // the string and its length or the source locations to display notes correctly. 6139 class FormatStringLiteral { 6140 const StringLiteral *FExpr; 6141 int64_t Offset; 6142 6143 public: 6144 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6145 : FExpr(fexpr), Offset(Offset) {} 6146 6147 StringRef getString() const { 6148 return FExpr->getString().drop_front(Offset); 6149 } 6150 6151 unsigned getByteLength() const { 6152 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6153 } 6154 6155 unsigned getLength() const { return FExpr->getLength() - Offset; } 6156 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6157 6158 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6159 6160 QualType getType() const { return FExpr->getType(); } 6161 6162 bool isAscii() const { return FExpr->isAscii(); } 6163 bool isWide() const { return FExpr->isWide(); } 6164 bool isUTF8() const { return FExpr->isUTF8(); } 6165 bool isUTF16() const { return FExpr->isUTF16(); } 6166 bool isUTF32() const { return FExpr->isUTF32(); } 6167 bool isPascal() const { return FExpr->isPascal(); } 6168 6169 SourceLocation getLocationOfByte( 6170 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6171 const TargetInfo &Target, unsigned *StartToken = nullptr, 6172 unsigned *StartTokenByteOffset = nullptr) const { 6173 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6174 StartToken, StartTokenByteOffset); 6175 } 6176 6177 SourceLocation getBeginLoc() const LLVM_READONLY { 6178 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6179 } 6180 6181 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6182 }; 6183 6184 } // namespace 6185 6186 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6187 const Expr *OrigFormatExpr, 6188 ArrayRef<const Expr *> Args, 6189 bool HasVAListArg, unsigned format_idx, 6190 unsigned firstDataArg, 6191 Sema::FormatStringType Type, 6192 bool inFunctionCall, 6193 Sema::VariadicCallType CallType, 6194 llvm::SmallBitVector &CheckedVarArgs, 6195 UncoveredArgHandler &UncoveredArg); 6196 6197 // Determine if an expression is a string literal or constant string. 6198 // If this function returns false on the arguments to a function expecting a 6199 // format string, we will usually need to emit a warning. 6200 // True string literals are then checked by CheckFormatString. 6201 static StringLiteralCheckType 6202 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6203 bool HasVAListArg, unsigned format_idx, 6204 unsigned firstDataArg, Sema::FormatStringType Type, 6205 Sema::VariadicCallType CallType, bool InFunctionCall, 6206 llvm::SmallBitVector &CheckedVarArgs, 6207 UncoveredArgHandler &UncoveredArg, 6208 llvm::APSInt Offset) { 6209 tryAgain: 6210 assert(Offset.isSigned() && "invalid offset"); 6211 6212 if (E->isTypeDependent() || E->isValueDependent()) 6213 return SLCT_NotALiteral; 6214 6215 E = E->IgnoreParenCasts(); 6216 6217 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6218 // Technically -Wformat-nonliteral does not warn about this case. 6219 // The behavior of printf and friends in this case is implementation 6220 // dependent. Ideally if the format string cannot be null then 6221 // it should have a 'nonnull' attribute in the function prototype. 6222 return SLCT_UncheckedLiteral; 6223 6224 switch (E->getStmtClass()) { 6225 case Stmt::BinaryConditionalOperatorClass: 6226 case Stmt::ConditionalOperatorClass: { 6227 // The expression is a literal if both sub-expressions were, and it was 6228 // completely checked only if both sub-expressions were checked. 6229 const AbstractConditionalOperator *C = 6230 cast<AbstractConditionalOperator>(E); 6231 6232 // Determine whether it is necessary to check both sub-expressions, for 6233 // example, because the condition expression is a constant that can be 6234 // evaluated at compile time. 6235 bool CheckLeft = true, CheckRight = true; 6236 6237 bool Cond; 6238 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6239 if (Cond) 6240 CheckRight = false; 6241 else 6242 CheckLeft = false; 6243 } 6244 6245 // We need to maintain the offsets for the right and the left hand side 6246 // separately to check if every possible indexed expression is a valid 6247 // string literal. They might have different offsets for different string 6248 // literals in the end. 6249 StringLiteralCheckType Left; 6250 if (!CheckLeft) 6251 Left = SLCT_UncheckedLiteral; 6252 else { 6253 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6254 HasVAListArg, format_idx, firstDataArg, 6255 Type, CallType, InFunctionCall, 6256 CheckedVarArgs, UncoveredArg, Offset); 6257 if (Left == SLCT_NotALiteral || !CheckRight) { 6258 return Left; 6259 } 6260 } 6261 6262 StringLiteralCheckType Right = 6263 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6264 HasVAListArg, format_idx, firstDataArg, 6265 Type, CallType, InFunctionCall, CheckedVarArgs, 6266 UncoveredArg, Offset); 6267 6268 return (CheckLeft && Left < Right) ? Left : Right; 6269 } 6270 6271 case Stmt::ImplicitCastExprClass: 6272 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6273 goto tryAgain; 6274 6275 case Stmt::OpaqueValueExprClass: 6276 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6277 E = src; 6278 goto tryAgain; 6279 } 6280 return SLCT_NotALiteral; 6281 6282 case Stmt::PredefinedExprClass: 6283 // While __func__, etc., are technically not string literals, they 6284 // cannot contain format specifiers and thus are not a security 6285 // liability. 6286 return SLCT_UncheckedLiteral; 6287 6288 case Stmt::DeclRefExprClass: { 6289 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6290 6291 // As an exception, do not flag errors for variables binding to 6292 // const string literals. 6293 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6294 bool isConstant = false; 6295 QualType T = DR->getType(); 6296 6297 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6298 isConstant = AT->getElementType().isConstant(S.Context); 6299 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6300 isConstant = T.isConstant(S.Context) && 6301 PT->getPointeeType().isConstant(S.Context); 6302 } else if (T->isObjCObjectPointerType()) { 6303 // In ObjC, there is usually no "const ObjectPointer" type, 6304 // so don't check if the pointee type is constant. 6305 isConstant = T.isConstant(S.Context); 6306 } 6307 6308 if (isConstant) { 6309 if (const Expr *Init = VD->getAnyInitializer()) { 6310 // Look through initializers like const char c[] = { "foo" } 6311 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6312 if (InitList->isStringLiteralInit()) 6313 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6314 } 6315 return checkFormatStringExpr(S, Init, Args, 6316 HasVAListArg, format_idx, 6317 firstDataArg, Type, CallType, 6318 /*InFunctionCall*/ false, CheckedVarArgs, 6319 UncoveredArg, Offset); 6320 } 6321 } 6322 6323 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6324 // special check to see if the format string is a function parameter 6325 // of the function calling the printf function. If the function 6326 // has an attribute indicating it is a printf-like function, then we 6327 // should suppress warnings concerning non-literals being used in a call 6328 // to a vprintf function. For example: 6329 // 6330 // void 6331 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6332 // va_list ap; 6333 // va_start(ap, fmt); 6334 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6335 // ... 6336 // } 6337 if (HasVAListArg) { 6338 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6339 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6340 int PVIndex = PV->getFunctionScopeIndex() + 1; 6341 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6342 // adjust for implicit parameter 6343 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6344 if (MD->isInstance()) 6345 ++PVIndex; 6346 // We also check if the formats are compatible. 6347 // We can't pass a 'scanf' string to a 'printf' function. 6348 if (PVIndex == PVFormat->getFormatIdx() && 6349 Type == S.GetFormatStringType(PVFormat)) 6350 return SLCT_UncheckedLiteral; 6351 } 6352 } 6353 } 6354 } 6355 } 6356 6357 return SLCT_NotALiteral; 6358 } 6359 6360 case Stmt::CallExprClass: 6361 case Stmt::CXXMemberCallExprClass: { 6362 const CallExpr *CE = cast<CallExpr>(E); 6363 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6364 bool IsFirst = true; 6365 StringLiteralCheckType CommonResult; 6366 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6367 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6368 StringLiteralCheckType Result = checkFormatStringExpr( 6369 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6370 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6371 if (IsFirst) { 6372 CommonResult = Result; 6373 IsFirst = false; 6374 } 6375 } 6376 if (!IsFirst) 6377 return CommonResult; 6378 6379 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6380 unsigned BuiltinID = FD->getBuiltinID(); 6381 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6382 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6383 const Expr *Arg = CE->getArg(0); 6384 return checkFormatStringExpr(S, Arg, Args, 6385 HasVAListArg, format_idx, 6386 firstDataArg, Type, CallType, 6387 InFunctionCall, CheckedVarArgs, 6388 UncoveredArg, Offset); 6389 } 6390 } 6391 } 6392 6393 return SLCT_NotALiteral; 6394 } 6395 case Stmt::ObjCMessageExprClass: { 6396 const auto *ME = cast<ObjCMessageExpr>(E); 6397 if (const auto *ND = ME->getMethodDecl()) { 6398 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6399 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6400 return checkFormatStringExpr( 6401 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6402 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6403 } 6404 } 6405 6406 return SLCT_NotALiteral; 6407 } 6408 case Stmt::ObjCStringLiteralClass: 6409 case Stmt::StringLiteralClass: { 6410 const StringLiteral *StrE = nullptr; 6411 6412 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6413 StrE = ObjCFExpr->getString(); 6414 else 6415 StrE = cast<StringLiteral>(E); 6416 6417 if (StrE) { 6418 if (Offset.isNegative() || Offset > StrE->getLength()) { 6419 // TODO: It would be better to have an explicit warning for out of 6420 // bounds literals. 6421 return SLCT_NotALiteral; 6422 } 6423 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6424 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6425 firstDataArg, Type, InFunctionCall, CallType, 6426 CheckedVarArgs, UncoveredArg); 6427 return SLCT_CheckedLiteral; 6428 } 6429 6430 return SLCT_NotALiteral; 6431 } 6432 case Stmt::BinaryOperatorClass: { 6433 llvm::APSInt LResult; 6434 llvm::APSInt RResult; 6435 6436 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6437 6438 // A string literal + an int offset is still a string literal. 6439 if (BinOp->isAdditiveOp()) { 6440 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6441 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6442 6443 if (LIsInt != RIsInt) { 6444 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6445 6446 if (LIsInt) { 6447 if (BinOpKind == BO_Add) { 6448 sumOffsets(Offset, LResult, BinOpKind, RIsInt); 6449 E = BinOp->getRHS(); 6450 goto tryAgain; 6451 } 6452 } else { 6453 sumOffsets(Offset, RResult, BinOpKind, RIsInt); 6454 E = BinOp->getLHS(); 6455 goto tryAgain; 6456 } 6457 } 6458 } 6459 6460 return SLCT_NotALiteral; 6461 } 6462 case Stmt::UnaryOperatorClass: { 6463 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6464 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6465 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6466 llvm::APSInt IndexResult; 6467 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6468 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true); 6469 E = ASE->getBase(); 6470 goto tryAgain; 6471 } 6472 } 6473 6474 return SLCT_NotALiteral; 6475 } 6476 6477 default: 6478 return SLCT_NotALiteral; 6479 } 6480 } 6481 6482 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6483 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6484 .Case("scanf", FST_Scanf) 6485 .Cases("printf", "printf0", FST_Printf) 6486 .Cases("NSString", "CFString", FST_NSString) 6487 .Case("strftime", FST_Strftime) 6488 .Case("strfmon", FST_Strfmon) 6489 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6490 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6491 .Case("os_trace", FST_OSLog) 6492 .Case("os_log", FST_OSLog) 6493 .Default(FST_Unknown); 6494 } 6495 6496 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6497 /// functions) for correct use of format strings. 6498 /// Returns true if a format string has been fully checked. 6499 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6500 ArrayRef<const Expr *> Args, 6501 bool IsCXXMember, 6502 VariadicCallType CallType, 6503 SourceLocation Loc, SourceRange Range, 6504 llvm::SmallBitVector &CheckedVarArgs) { 6505 FormatStringInfo FSI; 6506 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6507 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6508 FSI.FirstDataArg, GetFormatStringType(Format), 6509 CallType, Loc, Range, CheckedVarArgs); 6510 return false; 6511 } 6512 6513 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6514 bool HasVAListArg, unsigned format_idx, 6515 unsigned firstDataArg, FormatStringType Type, 6516 VariadicCallType CallType, 6517 SourceLocation Loc, SourceRange Range, 6518 llvm::SmallBitVector &CheckedVarArgs) { 6519 // CHECK: printf/scanf-like function is called with no format string. 6520 if (format_idx >= Args.size()) { 6521 Diag(Loc, diag::warn_missing_format_string) << Range; 6522 return false; 6523 } 6524 6525 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6526 6527 // CHECK: format string is not a string literal. 6528 // 6529 // Dynamically generated format strings are difficult to 6530 // automatically vet at compile time. Requiring that format strings 6531 // are string literals: (1) permits the checking of format strings by 6532 // the compiler and thereby (2) can practically remove the source of 6533 // many format string exploits. 6534 6535 // Format string can be either ObjC string (e.g. @"%d") or 6536 // C string (e.g. "%d") 6537 // ObjC string uses the same format specifiers as C string, so we can use 6538 // the same format string checking logic for both ObjC and C strings. 6539 UncoveredArgHandler UncoveredArg; 6540 StringLiteralCheckType CT = 6541 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6542 format_idx, firstDataArg, Type, CallType, 6543 /*IsFunctionCall*/ true, CheckedVarArgs, 6544 UncoveredArg, 6545 /*no string offset*/ llvm::APSInt(64, false) = 0); 6546 6547 // Generate a diagnostic where an uncovered argument is detected. 6548 if (UncoveredArg.hasUncoveredArg()) { 6549 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6550 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6551 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6552 } 6553 6554 if (CT != SLCT_NotALiteral) 6555 // Literal format string found, check done! 6556 return CT == SLCT_CheckedLiteral; 6557 6558 // Strftime is particular as it always uses a single 'time' argument, 6559 // so it is safe to pass a non-literal string. 6560 if (Type == FST_Strftime) 6561 return false; 6562 6563 // Do not emit diag when the string param is a macro expansion and the 6564 // format is either NSString or CFString. This is a hack to prevent 6565 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6566 // which are usually used in place of NS and CF string literals. 6567 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6568 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6569 return false; 6570 6571 // If there are no arguments specified, warn with -Wformat-security, otherwise 6572 // warn only with -Wformat-nonliteral. 6573 if (Args.size() == firstDataArg) { 6574 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6575 << OrigFormatExpr->getSourceRange(); 6576 switch (Type) { 6577 default: 6578 break; 6579 case FST_Kprintf: 6580 case FST_FreeBSDKPrintf: 6581 case FST_Printf: 6582 Diag(FormatLoc, diag::note_format_security_fixit) 6583 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6584 break; 6585 case FST_NSString: 6586 Diag(FormatLoc, diag::note_format_security_fixit) 6587 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6588 break; 6589 } 6590 } else { 6591 Diag(FormatLoc, diag::warn_format_nonliteral) 6592 << OrigFormatExpr->getSourceRange(); 6593 } 6594 return false; 6595 } 6596 6597 namespace { 6598 6599 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6600 protected: 6601 Sema &S; 6602 const FormatStringLiteral *FExpr; 6603 const Expr *OrigFormatExpr; 6604 const Sema::FormatStringType FSType; 6605 const unsigned FirstDataArg; 6606 const unsigned NumDataArgs; 6607 const char *Beg; // Start of format string. 6608 const bool HasVAListArg; 6609 ArrayRef<const Expr *> Args; 6610 unsigned FormatIdx; 6611 llvm::SmallBitVector CoveredArgs; 6612 bool usesPositionalArgs = false; 6613 bool atFirstArg = true; 6614 bool inFunctionCall; 6615 Sema::VariadicCallType CallType; 6616 llvm::SmallBitVector &CheckedVarArgs; 6617 UncoveredArgHandler &UncoveredArg; 6618 6619 public: 6620 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6621 const Expr *origFormatExpr, 6622 const Sema::FormatStringType type, unsigned firstDataArg, 6623 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6624 ArrayRef<const Expr *> Args, unsigned formatIdx, 6625 bool inFunctionCall, Sema::VariadicCallType callType, 6626 llvm::SmallBitVector &CheckedVarArgs, 6627 UncoveredArgHandler &UncoveredArg) 6628 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6629 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6630 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6631 inFunctionCall(inFunctionCall), CallType(callType), 6632 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6633 CoveredArgs.resize(numDataArgs); 6634 CoveredArgs.reset(); 6635 } 6636 6637 void DoneProcessing(); 6638 6639 void HandleIncompleteSpecifier(const char *startSpecifier, 6640 unsigned specifierLen) override; 6641 6642 void HandleInvalidLengthModifier( 6643 const analyze_format_string::FormatSpecifier &FS, 6644 const analyze_format_string::ConversionSpecifier &CS, 6645 const char *startSpecifier, unsigned specifierLen, 6646 unsigned DiagID); 6647 6648 void HandleNonStandardLengthModifier( 6649 const analyze_format_string::FormatSpecifier &FS, 6650 const char *startSpecifier, unsigned specifierLen); 6651 6652 void HandleNonStandardConversionSpecifier( 6653 const analyze_format_string::ConversionSpecifier &CS, 6654 const char *startSpecifier, unsigned specifierLen); 6655 6656 void HandlePosition(const char *startPos, unsigned posLen) override; 6657 6658 void HandleInvalidPosition(const char *startSpecifier, 6659 unsigned specifierLen, 6660 analyze_format_string::PositionContext p) override; 6661 6662 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6663 6664 void HandleNullChar(const char *nullCharacter) override; 6665 6666 template <typename Range> 6667 static void 6668 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6669 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6670 bool IsStringLocation, Range StringRange, 6671 ArrayRef<FixItHint> Fixit = None); 6672 6673 protected: 6674 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6675 const char *startSpec, 6676 unsigned specifierLen, 6677 const char *csStart, unsigned csLen); 6678 6679 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6680 const char *startSpec, 6681 unsigned specifierLen); 6682 6683 SourceRange getFormatStringRange(); 6684 CharSourceRange getSpecifierRange(const char *startSpecifier, 6685 unsigned specifierLen); 6686 SourceLocation getLocationOfByte(const char *x); 6687 6688 const Expr *getDataArg(unsigned i) const; 6689 6690 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6691 const analyze_format_string::ConversionSpecifier &CS, 6692 const char *startSpecifier, unsigned specifierLen, 6693 unsigned argIndex); 6694 6695 template <typename Range> 6696 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6697 bool IsStringLocation, Range StringRange, 6698 ArrayRef<FixItHint> Fixit = None); 6699 }; 6700 6701 } // namespace 6702 6703 SourceRange CheckFormatHandler::getFormatStringRange() { 6704 return OrigFormatExpr->getSourceRange(); 6705 } 6706 6707 CharSourceRange CheckFormatHandler:: 6708 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6709 SourceLocation Start = getLocationOfByte(startSpecifier); 6710 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6711 6712 // Advance the end SourceLocation by one due to half-open ranges. 6713 End = End.getLocWithOffset(1); 6714 6715 return CharSourceRange::getCharRange(Start, End); 6716 } 6717 6718 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6719 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6720 S.getLangOpts(), S.Context.getTargetInfo()); 6721 } 6722 6723 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6724 unsigned specifierLen){ 6725 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6726 getLocationOfByte(startSpecifier), 6727 /*IsStringLocation*/true, 6728 getSpecifierRange(startSpecifier, specifierLen)); 6729 } 6730 6731 void CheckFormatHandler::HandleInvalidLengthModifier( 6732 const analyze_format_string::FormatSpecifier &FS, 6733 const analyze_format_string::ConversionSpecifier &CS, 6734 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6735 using namespace analyze_format_string; 6736 6737 const LengthModifier &LM = FS.getLengthModifier(); 6738 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6739 6740 // See if we know how to fix this length modifier. 6741 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6742 if (FixedLM) { 6743 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6744 getLocationOfByte(LM.getStart()), 6745 /*IsStringLocation*/true, 6746 getSpecifierRange(startSpecifier, specifierLen)); 6747 6748 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6749 << FixedLM->toString() 6750 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6751 6752 } else { 6753 FixItHint Hint; 6754 if (DiagID == diag::warn_format_nonsensical_length) 6755 Hint = FixItHint::CreateRemoval(LMRange); 6756 6757 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6758 getLocationOfByte(LM.getStart()), 6759 /*IsStringLocation*/true, 6760 getSpecifierRange(startSpecifier, specifierLen), 6761 Hint); 6762 } 6763 } 6764 6765 void CheckFormatHandler::HandleNonStandardLengthModifier( 6766 const analyze_format_string::FormatSpecifier &FS, 6767 const char *startSpecifier, unsigned specifierLen) { 6768 using namespace analyze_format_string; 6769 6770 const LengthModifier &LM = FS.getLengthModifier(); 6771 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6772 6773 // See if we know how to fix this length modifier. 6774 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6775 if (FixedLM) { 6776 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6777 << LM.toString() << 0, 6778 getLocationOfByte(LM.getStart()), 6779 /*IsStringLocation*/true, 6780 getSpecifierRange(startSpecifier, specifierLen)); 6781 6782 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6783 << FixedLM->toString() 6784 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6785 6786 } else { 6787 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6788 << LM.toString() << 0, 6789 getLocationOfByte(LM.getStart()), 6790 /*IsStringLocation*/true, 6791 getSpecifierRange(startSpecifier, specifierLen)); 6792 } 6793 } 6794 6795 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6796 const analyze_format_string::ConversionSpecifier &CS, 6797 const char *startSpecifier, unsigned specifierLen) { 6798 using namespace analyze_format_string; 6799 6800 // See if we know how to fix this conversion specifier. 6801 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6802 if (FixedCS) { 6803 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6804 << CS.toString() << /*conversion specifier*/1, 6805 getLocationOfByte(CS.getStart()), 6806 /*IsStringLocation*/true, 6807 getSpecifierRange(startSpecifier, specifierLen)); 6808 6809 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6810 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6811 << FixedCS->toString() 6812 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6813 } else { 6814 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6815 << CS.toString() << /*conversion specifier*/1, 6816 getLocationOfByte(CS.getStart()), 6817 /*IsStringLocation*/true, 6818 getSpecifierRange(startSpecifier, specifierLen)); 6819 } 6820 } 6821 6822 void CheckFormatHandler::HandlePosition(const char *startPos, 6823 unsigned posLen) { 6824 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6825 getLocationOfByte(startPos), 6826 /*IsStringLocation*/true, 6827 getSpecifierRange(startPos, posLen)); 6828 } 6829 6830 void 6831 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 6832 analyze_format_string::PositionContext p) { 6833 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 6834 << (unsigned) p, 6835 getLocationOfByte(startPos), /*IsStringLocation*/true, 6836 getSpecifierRange(startPos, posLen)); 6837 } 6838 6839 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6840 unsigned posLen) { 6841 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6842 getLocationOfByte(startPos), 6843 /*IsStringLocation*/true, 6844 getSpecifierRange(startPos, posLen)); 6845 } 6846 6847 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6848 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6849 // The presence of a null character is likely an error. 6850 EmitFormatDiagnostic( 6851 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6852 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6853 getFormatStringRange()); 6854 } 6855 } 6856 6857 // Note that this may return NULL if there was an error parsing or building 6858 // one of the argument expressions. 6859 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6860 return Args[FirstDataArg + i]; 6861 } 6862 6863 void CheckFormatHandler::DoneProcessing() { 6864 // Does the number of data arguments exceed the number of 6865 // format conversions in the format string? 6866 if (!HasVAListArg) { 6867 // Find any arguments that weren't covered. 6868 CoveredArgs.flip(); 6869 signed notCoveredArg = CoveredArgs.find_first(); 6870 if (notCoveredArg >= 0) { 6871 assert((unsigned)notCoveredArg < NumDataArgs); 6872 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6873 } else { 6874 UncoveredArg.setAllCovered(); 6875 } 6876 } 6877 } 6878 6879 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6880 const Expr *ArgExpr) { 6881 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 6882 "Invalid state"); 6883 6884 if (!ArgExpr) 6885 return; 6886 6887 SourceLocation Loc = ArgExpr->getBeginLoc(); 6888 6889 if (S.getSourceManager().isInSystemMacro(Loc)) 6890 return; 6891 6892 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6893 for (auto E : DiagnosticExprs) 6894 PDiag << E->getSourceRange(); 6895 6896 CheckFormatHandler::EmitFormatDiagnostic( 6897 S, IsFunctionCall, DiagnosticExprs[0], 6898 PDiag, Loc, /*IsStringLocation*/false, 6899 DiagnosticExprs[0]->getSourceRange()); 6900 } 6901 6902 bool 6903 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6904 SourceLocation Loc, 6905 const char *startSpec, 6906 unsigned specifierLen, 6907 const char *csStart, 6908 unsigned csLen) { 6909 bool keepGoing = true; 6910 if (argIndex < NumDataArgs) { 6911 // Consider the argument coverered, even though the specifier doesn't 6912 // make sense. 6913 CoveredArgs.set(argIndex); 6914 } 6915 else { 6916 // If argIndex exceeds the number of data arguments we 6917 // don't issue a warning because that is just a cascade of warnings (and 6918 // they may have intended '%%' anyway). We don't want to continue processing 6919 // the format string after this point, however, as we will like just get 6920 // gibberish when trying to match arguments. 6921 keepGoing = false; 6922 } 6923 6924 StringRef Specifier(csStart, csLen); 6925 6926 // If the specifier in non-printable, it could be the first byte of a UTF-8 6927 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6928 // hex value. 6929 std::string CodePointStr; 6930 if (!llvm::sys::locale::isPrint(*csStart)) { 6931 llvm::UTF32 CodePoint; 6932 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6933 const llvm::UTF8 *E = 6934 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6935 llvm::ConversionResult Result = 6936 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6937 6938 if (Result != llvm::conversionOK) { 6939 unsigned char FirstChar = *csStart; 6940 CodePoint = (llvm::UTF32)FirstChar; 6941 } 6942 6943 llvm::raw_string_ostream OS(CodePointStr); 6944 if (CodePoint < 256) 6945 OS << "\\x" << llvm::format("%02x", CodePoint); 6946 else if (CodePoint <= 0xFFFF) 6947 OS << "\\u" << llvm::format("%04x", CodePoint); 6948 else 6949 OS << "\\U" << llvm::format("%08x", CodePoint); 6950 OS.flush(); 6951 Specifier = CodePointStr; 6952 } 6953 6954 EmitFormatDiagnostic( 6955 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 6956 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 6957 6958 return keepGoing; 6959 } 6960 6961 void 6962 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 6963 const char *startSpec, 6964 unsigned specifierLen) { 6965 EmitFormatDiagnostic( 6966 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 6967 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 6968 } 6969 6970 bool 6971 CheckFormatHandler::CheckNumArgs( 6972 const analyze_format_string::FormatSpecifier &FS, 6973 const analyze_format_string::ConversionSpecifier &CS, 6974 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 6975 6976 if (argIndex >= NumDataArgs) { 6977 PartialDiagnostic PDiag = FS.usesPositionalArg() 6978 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 6979 << (argIndex+1) << NumDataArgs) 6980 : S.PDiag(diag::warn_printf_insufficient_data_args); 6981 EmitFormatDiagnostic( 6982 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 6983 getSpecifierRange(startSpecifier, specifierLen)); 6984 6985 // Since more arguments than conversion tokens are given, by extension 6986 // all arguments are covered, so mark this as so. 6987 UncoveredArg.setAllCovered(); 6988 return false; 6989 } 6990 return true; 6991 } 6992 6993 template<typename Range> 6994 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 6995 SourceLocation Loc, 6996 bool IsStringLocation, 6997 Range StringRange, 6998 ArrayRef<FixItHint> FixIt) { 6999 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7000 Loc, IsStringLocation, StringRange, FixIt); 7001 } 7002 7003 /// If the format string is not within the function call, emit a note 7004 /// so that the function call and string are in diagnostic messages. 7005 /// 7006 /// \param InFunctionCall if true, the format string is within the function 7007 /// call and only one diagnostic message will be produced. Otherwise, an 7008 /// extra note will be emitted pointing to location of the format string. 7009 /// 7010 /// \param ArgumentExpr the expression that is passed as the format string 7011 /// argument in the function call. Used for getting locations when two 7012 /// diagnostics are emitted. 7013 /// 7014 /// \param PDiag the callee should already have provided any strings for the 7015 /// diagnostic message. This function only adds locations and fixits 7016 /// to diagnostics. 7017 /// 7018 /// \param Loc primary location for diagnostic. If two diagnostics are 7019 /// required, one will be at Loc and a new SourceLocation will be created for 7020 /// the other one. 7021 /// 7022 /// \param IsStringLocation if true, Loc points to the format string should be 7023 /// used for the note. Otherwise, Loc points to the argument list and will 7024 /// be used with PDiag. 7025 /// 7026 /// \param StringRange some or all of the string to highlight. This is 7027 /// templated so it can accept either a CharSourceRange or a SourceRange. 7028 /// 7029 /// \param FixIt optional fix it hint for the format string. 7030 template <typename Range> 7031 void CheckFormatHandler::EmitFormatDiagnostic( 7032 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7033 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7034 Range StringRange, ArrayRef<FixItHint> FixIt) { 7035 if (InFunctionCall) { 7036 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7037 D << StringRange; 7038 D << FixIt; 7039 } else { 7040 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7041 << ArgumentExpr->getSourceRange(); 7042 7043 const Sema::SemaDiagnosticBuilder &Note = 7044 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7045 diag::note_format_string_defined); 7046 7047 Note << StringRange; 7048 Note << FixIt; 7049 } 7050 } 7051 7052 //===--- CHECK: Printf format string checking ------------------------------===// 7053 7054 namespace { 7055 7056 class CheckPrintfHandler : public CheckFormatHandler { 7057 public: 7058 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7059 const Expr *origFormatExpr, 7060 const Sema::FormatStringType type, unsigned firstDataArg, 7061 unsigned numDataArgs, bool isObjC, const char *beg, 7062 bool hasVAListArg, ArrayRef<const Expr *> Args, 7063 unsigned formatIdx, bool inFunctionCall, 7064 Sema::VariadicCallType CallType, 7065 llvm::SmallBitVector &CheckedVarArgs, 7066 UncoveredArgHandler &UncoveredArg) 7067 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7068 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7069 inFunctionCall, CallType, CheckedVarArgs, 7070 UncoveredArg) {} 7071 7072 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7073 7074 /// Returns true if '%@' specifiers are allowed in the format string. 7075 bool allowsObjCArg() const { 7076 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7077 FSType == Sema::FST_OSTrace; 7078 } 7079 7080 bool HandleInvalidPrintfConversionSpecifier( 7081 const analyze_printf::PrintfSpecifier &FS, 7082 const char *startSpecifier, 7083 unsigned specifierLen) override; 7084 7085 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7086 const char *startSpecifier, 7087 unsigned specifierLen) override; 7088 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7089 const char *StartSpecifier, 7090 unsigned SpecifierLen, 7091 const Expr *E); 7092 7093 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7094 const char *startSpecifier, unsigned specifierLen); 7095 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7096 const analyze_printf::OptionalAmount &Amt, 7097 unsigned type, 7098 const char *startSpecifier, unsigned specifierLen); 7099 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7100 const analyze_printf::OptionalFlag &flag, 7101 const char *startSpecifier, unsigned specifierLen); 7102 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7103 const analyze_printf::OptionalFlag &ignoredFlag, 7104 const analyze_printf::OptionalFlag &flag, 7105 const char *startSpecifier, unsigned specifierLen); 7106 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7107 const Expr *E); 7108 7109 void HandleEmptyObjCModifierFlag(const char *startFlag, 7110 unsigned flagLen) override; 7111 7112 void HandleInvalidObjCModifierFlag(const char *startFlag, 7113 unsigned flagLen) override; 7114 7115 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7116 const char *flagsEnd, 7117 const char *conversionPosition) 7118 override; 7119 }; 7120 7121 } // namespace 7122 7123 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7124 const analyze_printf::PrintfSpecifier &FS, 7125 const char *startSpecifier, 7126 unsigned specifierLen) { 7127 const analyze_printf::PrintfConversionSpecifier &CS = 7128 FS.getConversionSpecifier(); 7129 7130 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7131 getLocationOfByte(CS.getStart()), 7132 startSpecifier, specifierLen, 7133 CS.getStart(), CS.getLength()); 7134 } 7135 7136 bool CheckPrintfHandler::HandleAmount( 7137 const analyze_format_string::OptionalAmount &Amt, 7138 unsigned k, const char *startSpecifier, 7139 unsigned specifierLen) { 7140 if (Amt.hasDataArgument()) { 7141 if (!HasVAListArg) { 7142 unsigned argIndex = Amt.getArgIndex(); 7143 if (argIndex >= NumDataArgs) { 7144 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7145 << k, 7146 getLocationOfByte(Amt.getStart()), 7147 /*IsStringLocation*/true, 7148 getSpecifierRange(startSpecifier, specifierLen)); 7149 // Don't do any more checking. We will just emit 7150 // spurious errors. 7151 return false; 7152 } 7153 7154 // Type check the data argument. It should be an 'int'. 7155 // Although not in conformance with C99, we also allow the argument to be 7156 // an 'unsigned int' as that is a reasonably safe case. GCC also 7157 // doesn't emit a warning for that case. 7158 CoveredArgs.set(argIndex); 7159 const Expr *Arg = getDataArg(argIndex); 7160 if (!Arg) 7161 return false; 7162 7163 QualType T = Arg->getType(); 7164 7165 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7166 assert(AT.isValid()); 7167 7168 if (!AT.matchesType(S.Context, T)) { 7169 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7170 << k << AT.getRepresentativeTypeName(S.Context) 7171 << T << Arg->getSourceRange(), 7172 getLocationOfByte(Amt.getStart()), 7173 /*IsStringLocation*/true, 7174 getSpecifierRange(startSpecifier, specifierLen)); 7175 // Don't do any more checking. We will just emit 7176 // spurious errors. 7177 return false; 7178 } 7179 } 7180 } 7181 return true; 7182 } 7183 7184 void CheckPrintfHandler::HandleInvalidAmount( 7185 const analyze_printf::PrintfSpecifier &FS, 7186 const analyze_printf::OptionalAmount &Amt, 7187 unsigned type, 7188 const char *startSpecifier, 7189 unsigned specifierLen) { 7190 const analyze_printf::PrintfConversionSpecifier &CS = 7191 FS.getConversionSpecifier(); 7192 7193 FixItHint fixit = 7194 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7195 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7196 Amt.getConstantLength())) 7197 : FixItHint(); 7198 7199 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7200 << type << CS.toString(), 7201 getLocationOfByte(Amt.getStart()), 7202 /*IsStringLocation*/true, 7203 getSpecifierRange(startSpecifier, specifierLen), 7204 fixit); 7205 } 7206 7207 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7208 const analyze_printf::OptionalFlag &flag, 7209 const char *startSpecifier, 7210 unsigned specifierLen) { 7211 // Warn about pointless flag with a fixit removal. 7212 const analyze_printf::PrintfConversionSpecifier &CS = 7213 FS.getConversionSpecifier(); 7214 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7215 << flag.toString() << CS.toString(), 7216 getLocationOfByte(flag.getPosition()), 7217 /*IsStringLocation*/true, 7218 getSpecifierRange(startSpecifier, specifierLen), 7219 FixItHint::CreateRemoval( 7220 getSpecifierRange(flag.getPosition(), 1))); 7221 } 7222 7223 void CheckPrintfHandler::HandleIgnoredFlag( 7224 const analyze_printf::PrintfSpecifier &FS, 7225 const analyze_printf::OptionalFlag &ignoredFlag, 7226 const analyze_printf::OptionalFlag &flag, 7227 const char *startSpecifier, 7228 unsigned specifierLen) { 7229 // Warn about ignored flag with a fixit removal. 7230 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7231 << ignoredFlag.toString() << flag.toString(), 7232 getLocationOfByte(ignoredFlag.getPosition()), 7233 /*IsStringLocation*/true, 7234 getSpecifierRange(startSpecifier, specifierLen), 7235 FixItHint::CreateRemoval( 7236 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7237 } 7238 7239 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7240 unsigned flagLen) { 7241 // Warn about an empty flag. 7242 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7243 getLocationOfByte(startFlag), 7244 /*IsStringLocation*/true, 7245 getSpecifierRange(startFlag, flagLen)); 7246 } 7247 7248 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7249 unsigned flagLen) { 7250 // Warn about an invalid flag. 7251 auto Range = getSpecifierRange(startFlag, flagLen); 7252 StringRef flag(startFlag, flagLen); 7253 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7254 getLocationOfByte(startFlag), 7255 /*IsStringLocation*/true, 7256 Range, FixItHint::CreateRemoval(Range)); 7257 } 7258 7259 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7260 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7261 // Warn about using '[...]' without a '@' conversion. 7262 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7263 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7264 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7265 getLocationOfByte(conversionPosition), 7266 /*IsStringLocation*/true, 7267 Range, FixItHint::CreateRemoval(Range)); 7268 } 7269 7270 // Determines if the specified is a C++ class or struct containing 7271 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7272 // "c_str()"). 7273 template<typename MemberKind> 7274 static llvm::SmallPtrSet<MemberKind*, 1> 7275 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7276 const RecordType *RT = Ty->getAs<RecordType>(); 7277 llvm::SmallPtrSet<MemberKind*, 1> Results; 7278 7279 if (!RT) 7280 return Results; 7281 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7282 if (!RD || !RD->getDefinition()) 7283 return Results; 7284 7285 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7286 Sema::LookupMemberName); 7287 R.suppressDiagnostics(); 7288 7289 // We just need to include all members of the right kind turned up by the 7290 // filter, at this point. 7291 if (S.LookupQualifiedName(R, RT->getDecl())) 7292 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7293 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7294 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7295 Results.insert(FK); 7296 } 7297 return Results; 7298 } 7299 7300 /// Check if we could call '.c_str()' on an object. 7301 /// 7302 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7303 /// allow the call, or if it would be ambiguous). 7304 bool Sema::hasCStrMethod(const Expr *E) { 7305 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7306 7307 MethodSet Results = 7308 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7309 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7310 MI != ME; ++MI) 7311 if ((*MI)->getMinRequiredArguments() == 0) 7312 return true; 7313 return false; 7314 } 7315 7316 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7317 // better diagnostic if so. AT is assumed to be valid. 7318 // Returns true when a c_str() conversion method is found. 7319 bool CheckPrintfHandler::checkForCStrMembers( 7320 const analyze_printf::ArgType &AT, const Expr *E) { 7321 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7322 7323 MethodSet Results = 7324 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7325 7326 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7327 MI != ME; ++MI) { 7328 const CXXMethodDecl *Method = *MI; 7329 if (Method->getMinRequiredArguments() == 0 && 7330 AT.matchesType(S.Context, Method->getReturnType())) { 7331 // FIXME: Suggest parens if the expression needs them. 7332 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7333 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7334 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7335 return true; 7336 } 7337 } 7338 7339 return false; 7340 } 7341 7342 bool 7343 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7344 &FS, 7345 const char *startSpecifier, 7346 unsigned specifierLen) { 7347 using namespace analyze_format_string; 7348 using namespace analyze_printf; 7349 7350 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7351 7352 if (FS.consumesDataArgument()) { 7353 if (atFirstArg) { 7354 atFirstArg = false; 7355 usesPositionalArgs = FS.usesPositionalArg(); 7356 } 7357 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7358 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7359 startSpecifier, specifierLen); 7360 return false; 7361 } 7362 } 7363 7364 // First check if the field width, precision, and conversion specifier 7365 // have matching data arguments. 7366 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7367 startSpecifier, specifierLen)) { 7368 return false; 7369 } 7370 7371 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7372 startSpecifier, specifierLen)) { 7373 return false; 7374 } 7375 7376 if (!CS.consumesDataArgument()) { 7377 // FIXME: Technically specifying a precision or field width here 7378 // makes no sense. Worth issuing a warning at some point. 7379 return true; 7380 } 7381 7382 // Consume the argument. 7383 unsigned argIndex = FS.getArgIndex(); 7384 if (argIndex < NumDataArgs) { 7385 // The check to see if the argIndex is valid will come later. 7386 // We set the bit here because we may exit early from this 7387 // function if we encounter some other error. 7388 CoveredArgs.set(argIndex); 7389 } 7390 7391 // FreeBSD kernel extensions. 7392 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7393 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7394 // We need at least two arguments. 7395 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7396 return false; 7397 7398 // Claim the second argument. 7399 CoveredArgs.set(argIndex + 1); 7400 7401 // Type check the first argument (int for %b, pointer for %D) 7402 const Expr *Ex = getDataArg(argIndex); 7403 const analyze_printf::ArgType &AT = 7404 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7405 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7406 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7407 EmitFormatDiagnostic( 7408 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7409 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7410 << false << Ex->getSourceRange(), 7411 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7412 getSpecifierRange(startSpecifier, specifierLen)); 7413 7414 // Type check the second argument (char * for both %b and %D) 7415 Ex = getDataArg(argIndex + 1); 7416 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7417 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7418 EmitFormatDiagnostic( 7419 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7420 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7421 << false << Ex->getSourceRange(), 7422 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7423 getSpecifierRange(startSpecifier, specifierLen)); 7424 7425 return true; 7426 } 7427 7428 // Check for using an Objective-C specific conversion specifier 7429 // in a non-ObjC literal. 7430 if (!allowsObjCArg() && CS.isObjCArg()) { 7431 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7432 specifierLen); 7433 } 7434 7435 // %P can only be used with os_log. 7436 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7437 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7438 specifierLen); 7439 } 7440 7441 // %n is not allowed with os_log. 7442 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7443 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7444 getLocationOfByte(CS.getStart()), 7445 /*IsStringLocation*/ false, 7446 getSpecifierRange(startSpecifier, specifierLen)); 7447 7448 return true; 7449 } 7450 7451 // Only scalars are allowed for os_trace. 7452 if (FSType == Sema::FST_OSTrace && 7453 (CS.getKind() == ConversionSpecifier::PArg || 7454 CS.getKind() == ConversionSpecifier::sArg || 7455 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7456 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7457 specifierLen); 7458 } 7459 7460 // Check for use of public/private annotation outside of os_log(). 7461 if (FSType != Sema::FST_OSLog) { 7462 if (FS.isPublic().isSet()) { 7463 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7464 << "public", 7465 getLocationOfByte(FS.isPublic().getPosition()), 7466 /*IsStringLocation*/ false, 7467 getSpecifierRange(startSpecifier, specifierLen)); 7468 } 7469 if (FS.isPrivate().isSet()) { 7470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7471 << "private", 7472 getLocationOfByte(FS.isPrivate().getPosition()), 7473 /*IsStringLocation*/ false, 7474 getSpecifierRange(startSpecifier, specifierLen)); 7475 } 7476 } 7477 7478 // Check for invalid use of field width 7479 if (!FS.hasValidFieldWidth()) { 7480 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7481 startSpecifier, specifierLen); 7482 } 7483 7484 // Check for invalid use of precision 7485 if (!FS.hasValidPrecision()) { 7486 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7487 startSpecifier, specifierLen); 7488 } 7489 7490 // Precision is mandatory for %P specifier. 7491 if (CS.getKind() == ConversionSpecifier::PArg && 7492 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7493 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7494 getLocationOfByte(startSpecifier), 7495 /*IsStringLocation*/ false, 7496 getSpecifierRange(startSpecifier, specifierLen)); 7497 } 7498 7499 // Check each flag does not conflict with any other component. 7500 if (!FS.hasValidThousandsGroupingPrefix()) 7501 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7502 if (!FS.hasValidLeadingZeros()) 7503 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7504 if (!FS.hasValidPlusPrefix()) 7505 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7506 if (!FS.hasValidSpacePrefix()) 7507 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7508 if (!FS.hasValidAlternativeForm()) 7509 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7510 if (!FS.hasValidLeftJustified()) 7511 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7512 7513 // Check that flags are not ignored by another flag 7514 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7515 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7516 startSpecifier, specifierLen); 7517 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7518 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7519 startSpecifier, specifierLen); 7520 7521 // Check the length modifier is valid with the given conversion specifier. 7522 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 7523 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7524 diag::warn_format_nonsensical_length); 7525 else if (!FS.hasStandardLengthModifier()) 7526 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7527 else if (!FS.hasStandardLengthConversionCombination()) 7528 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7529 diag::warn_format_non_standard_conversion_spec); 7530 7531 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7532 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7533 7534 // The remaining checks depend on the data arguments. 7535 if (HasVAListArg) 7536 return true; 7537 7538 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7539 return false; 7540 7541 const Expr *Arg = getDataArg(argIndex); 7542 if (!Arg) 7543 return true; 7544 7545 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7546 } 7547 7548 static bool requiresParensToAddCast(const Expr *E) { 7549 // FIXME: We should have a general way to reason about operator 7550 // precedence and whether parens are actually needed here. 7551 // Take care of a few common cases where they aren't. 7552 const Expr *Inside = E->IgnoreImpCasts(); 7553 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7554 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7555 7556 switch (Inside->getStmtClass()) { 7557 case Stmt::ArraySubscriptExprClass: 7558 case Stmt::CallExprClass: 7559 case Stmt::CharacterLiteralClass: 7560 case Stmt::CXXBoolLiteralExprClass: 7561 case Stmt::DeclRefExprClass: 7562 case Stmt::FloatingLiteralClass: 7563 case Stmt::IntegerLiteralClass: 7564 case Stmt::MemberExprClass: 7565 case Stmt::ObjCArrayLiteralClass: 7566 case Stmt::ObjCBoolLiteralExprClass: 7567 case Stmt::ObjCBoxedExprClass: 7568 case Stmt::ObjCDictionaryLiteralClass: 7569 case Stmt::ObjCEncodeExprClass: 7570 case Stmt::ObjCIvarRefExprClass: 7571 case Stmt::ObjCMessageExprClass: 7572 case Stmt::ObjCPropertyRefExprClass: 7573 case Stmt::ObjCStringLiteralClass: 7574 case Stmt::ObjCSubscriptRefExprClass: 7575 case Stmt::ParenExprClass: 7576 case Stmt::StringLiteralClass: 7577 case Stmt::UnaryOperatorClass: 7578 return false; 7579 default: 7580 return true; 7581 } 7582 } 7583 7584 static std::pair<QualType, StringRef> 7585 shouldNotPrintDirectly(const ASTContext &Context, 7586 QualType IntendedTy, 7587 const Expr *E) { 7588 // Use a 'while' to peel off layers of typedefs. 7589 QualType TyTy = IntendedTy; 7590 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7591 StringRef Name = UserTy->getDecl()->getName(); 7592 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7593 .Case("CFIndex", Context.getNSIntegerType()) 7594 .Case("NSInteger", Context.getNSIntegerType()) 7595 .Case("NSUInteger", Context.getNSUIntegerType()) 7596 .Case("SInt32", Context.IntTy) 7597 .Case("UInt32", Context.UnsignedIntTy) 7598 .Default(QualType()); 7599 7600 if (!CastTy.isNull()) 7601 return std::make_pair(CastTy, Name); 7602 7603 TyTy = UserTy->desugar(); 7604 } 7605 7606 // Strip parens if necessary. 7607 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7608 return shouldNotPrintDirectly(Context, 7609 PE->getSubExpr()->getType(), 7610 PE->getSubExpr()); 7611 7612 // If this is a conditional expression, then its result type is constructed 7613 // via usual arithmetic conversions and thus there might be no necessary 7614 // typedef sugar there. Recurse to operands to check for NSInteger & 7615 // Co. usage condition. 7616 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7617 QualType TrueTy, FalseTy; 7618 StringRef TrueName, FalseName; 7619 7620 std::tie(TrueTy, TrueName) = 7621 shouldNotPrintDirectly(Context, 7622 CO->getTrueExpr()->getType(), 7623 CO->getTrueExpr()); 7624 std::tie(FalseTy, FalseName) = 7625 shouldNotPrintDirectly(Context, 7626 CO->getFalseExpr()->getType(), 7627 CO->getFalseExpr()); 7628 7629 if (TrueTy == FalseTy) 7630 return std::make_pair(TrueTy, TrueName); 7631 else if (TrueTy.isNull()) 7632 return std::make_pair(FalseTy, FalseName); 7633 else if (FalseTy.isNull()) 7634 return std::make_pair(TrueTy, TrueName); 7635 } 7636 7637 return std::make_pair(QualType(), StringRef()); 7638 } 7639 7640 bool 7641 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7642 const char *StartSpecifier, 7643 unsigned SpecifierLen, 7644 const Expr *E) { 7645 using namespace analyze_format_string; 7646 using namespace analyze_printf; 7647 7648 // Now type check the data expression that matches the 7649 // format specifier. 7650 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7651 if (!AT.isValid()) 7652 return true; 7653 7654 QualType ExprTy = E->getType(); 7655 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7656 ExprTy = TET->getUnderlyingExpr()->getType(); 7657 } 7658 7659 const analyze_printf::ArgType::MatchKind Match = 7660 AT.matchesType(S.Context, ExprTy); 7661 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7662 if (Match == analyze_printf::ArgType::Match) 7663 return true; 7664 7665 // Look through argument promotions for our error message's reported type. 7666 // This includes the integral and floating promotions, but excludes array 7667 // and function pointer decay; seeing that an argument intended to be a 7668 // string has type 'char [6]' is probably more confusing than 'char *'. 7669 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7670 if (ICE->getCastKind() == CK_IntegralCast || 7671 ICE->getCastKind() == CK_FloatingCast) { 7672 E = ICE->getSubExpr(); 7673 ExprTy = E->getType(); 7674 7675 // Check if we didn't match because of an implicit cast from a 'char' 7676 // or 'short' to an 'int'. This is done because printf is a varargs 7677 // function. 7678 if (ICE->getType() == S.Context.IntTy || 7679 ICE->getType() == S.Context.UnsignedIntTy) { 7680 // All further checking is done on the subexpression. 7681 if (AT.matchesType(S.Context, ExprTy)) 7682 return true; 7683 } 7684 } 7685 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7686 // Special case for 'a', which has type 'int' in C. 7687 // Note, however, that we do /not/ want to treat multibyte constants like 7688 // 'MooV' as characters! This form is deprecated but still exists. 7689 if (ExprTy == S.Context.IntTy) 7690 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7691 ExprTy = S.Context.CharTy; 7692 } 7693 7694 // Look through enums to their underlying type. 7695 bool IsEnum = false; 7696 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7697 ExprTy = EnumTy->getDecl()->getIntegerType(); 7698 IsEnum = true; 7699 } 7700 7701 // %C in an Objective-C context prints a unichar, not a wchar_t. 7702 // If the argument is an integer of some kind, believe the %C and suggest 7703 // a cast instead of changing the conversion specifier. 7704 QualType IntendedTy = ExprTy; 7705 if (isObjCContext() && 7706 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7707 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7708 !ExprTy->isCharType()) { 7709 // 'unichar' is defined as a typedef of unsigned short, but we should 7710 // prefer using the typedef if it is visible. 7711 IntendedTy = S.Context.UnsignedShortTy; 7712 7713 // While we are here, check if the value is an IntegerLiteral that happens 7714 // to be within the valid range. 7715 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7716 const llvm::APInt &V = IL->getValue(); 7717 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7718 return true; 7719 } 7720 7721 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7722 Sema::LookupOrdinaryName); 7723 if (S.LookupName(Result, S.getCurScope())) { 7724 NamedDecl *ND = Result.getFoundDecl(); 7725 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7726 if (TD->getUnderlyingType() == IntendedTy) 7727 IntendedTy = S.Context.getTypedefType(TD); 7728 } 7729 } 7730 } 7731 7732 // Special-case some of Darwin's platform-independence types by suggesting 7733 // casts to primitive types that are known to be large enough. 7734 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7735 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7736 QualType CastTy; 7737 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7738 if (!CastTy.isNull()) { 7739 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7740 // (long in ASTContext). Only complain to pedants. 7741 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7742 (AT.isSizeT() || AT.isPtrdiffT()) && 7743 AT.matchesType(S.Context, CastTy)) 7744 Pedantic = true; 7745 IntendedTy = CastTy; 7746 ShouldNotPrintDirectly = true; 7747 } 7748 } 7749 7750 // We may be able to offer a FixItHint if it is a supported type. 7751 PrintfSpecifier fixedFS = FS; 7752 bool Success = 7753 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7754 7755 if (Success) { 7756 // Get the fix string from the fixed format specifier 7757 SmallString<16> buf; 7758 llvm::raw_svector_ostream os(buf); 7759 fixedFS.toString(os); 7760 7761 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7762 7763 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7764 unsigned Diag = 7765 Pedantic 7766 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7767 : diag::warn_format_conversion_argument_type_mismatch; 7768 // In this case, the specifier is wrong and should be changed to match 7769 // the argument. 7770 EmitFormatDiagnostic(S.PDiag(Diag) 7771 << AT.getRepresentativeTypeName(S.Context) 7772 << IntendedTy << IsEnum << E->getSourceRange(), 7773 E->getBeginLoc(), 7774 /*IsStringLocation*/ false, SpecRange, 7775 FixItHint::CreateReplacement(SpecRange, os.str())); 7776 } else { 7777 // The canonical type for formatting this value is different from the 7778 // actual type of the expression. (This occurs, for example, with Darwin's 7779 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7780 // should be printed as 'long' for 64-bit compatibility.) 7781 // Rather than emitting a normal format/argument mismatch, we want to 7782 // add a cast to the recommended type (and correct the format string 7783 // if necessary). 7784 SmallString<16> CastBuf; 7785 llvm::raw_svector_ostream CastFix(CastBuf); 7786 CastFix << "("; 7787 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7788 CastFix << ")"; 7789 7790 SmallVector<FixItHint,4> Hints; 7791 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 7792 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7793 7794 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7795 // If there's already a cast present, just replace it. 7796 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7797 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7798 7799 } else if (!requiresParensToAddCast(E)) { 7800 // If the expression has high enough precedence, 7801 // just write the C-style cast. 7802 Hints.push_back( 7803 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7804 } else { 7805 // Otherwise, add parens around the expression as well as the cast. 7806 CastFix << "("; 7807 Hints.push_back( 7808 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7809 7810 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 7811 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7812 } 7813 7814 if (ShouldNotPrintDirectly) { 7815 // The expression has a type that should not be printed directly. 7816 // We extract the name from the typedef because we don't want to show 7817 // the underlying type in the diagnostic. 7818 StringRef Name; 7819 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 7820 Name = TypedefTy->getDecl()->getName(); 7821 else 7822 Name = CastTyName; 7823 unsigned Diag = Pedantic 7824 ? diag::warn_format_argument_needs_cast_pedantic 7825 : diag::warn_format_argument_needs_cast; 7826 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7827 << E->getSourceRange(), 7828 E->getBeginLoc(), /*IsStringLocation=*/false, 7829 SpecRange, Hints); 7830 } else { 7831 // In this case, the expression could be printed using a different 7832 // specifier, but we've decided that the specifier is probably correct 7833 // and we should cast instead. Just use the normal warning message. 7834 EmitFormatDiagnostic( 7835 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7836 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 7837 << E->getSourceRange(), 7838 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7839 } 7840 } 7841 } else { 7842 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7843 SpecifierLen); 7844 // Since the warning for passing non-POD types to variadic functions 7845 // was deferred until now, we emit a warning for non-POD 7846 // arguments here. 7847 switch (S.isValidVarArgType(ExprTy)) { 7848 case Sema::VAK_Valid: 7849 case Sema::VAK_ValidInCXX11: { 7850 unsigned Diag = 7851 Pedantic 7852 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7853 : diag::warn_format_conversion_argument_type_mismatch; 7854 7855 EmitFormatDiagnostic( 7856 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7857 << IsEnum << CSR << E->getSourceRange(), 7858 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7859 break; 7860 } 7861 case Sema::VAK_Undefined: 7862 case Sema::VAK_MSVCUndefined: 7863 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 7864 << S.getLangOpts().CPlusPlus11 << ExprTy 7865 << CallType 7866 << AT.getRepresentativeTypeName(S.Context) << CSR 7867 << E->getSourceRange(), 7868 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7869 checkForCStrMembers(AT, E); 7870 break; 7871 7872 case Sema::VAK_Invalid: 7873 if (ExprTy->isObjCObjectType()) 7874 EmitFormatDiagnostic( 7875 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7876 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 7877 << AT.getRepresentativeTypeName(S.Context) << CSR 7878 << E->getSourceRange(), 7879 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7880 else 7881 // FIXME: If this is an initializer list, suggest removing the braces 7882 // or inserting a cast to the target type. 7883 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 7884 << isa<InitListExpr>(E) << ExprTy << CallType 7885 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 7886 break; 7887 } 7888 7889 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7890 "format string specifier index out of range"); 7891 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7892 } 7893 7894 return true; 7895 } 7896 7897 //===--- CHECK: Scanf format string checking ------------------------------===// 7898 7899 namespace { 7900 7901 class CheckScanfHandler : public CheckFormatHandler { 7902 public: 7903 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7904 const Expr *origFormatExpr, Sema::FormatStringType type, 7905 unsigned firstDataArg, unsigned numDataArgs, 7906 const char *beg, bool hasVAListArg, 7907 ArrayRef<const Expr *> Args, unsigned formatIdx, 7908 bool inFunctionCall, Sema::VariadicCallType CallType, 7909 llvm::SmallBitVector &CheckedVarArgs, 7910 UncoveredArgHandler &UncoveredArg) 7911 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7912 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7913 inFunctionCall, CallType, CheckedVarArgs, 7914 UncoveredArg) {} 7915 7916 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7917 const char *startSpecifier, 7918 unsigned specifierLen) override; 7919 7920 bool HandleInvalidScanfConversionSpecifier( 7921 const analyze_scanf::ScanfSpecifier &FS, 7922 const char *startSpecifier, 7923 unsigned specifierLen) override; 7924 7925 void HandleIncompleteScanList(const char *start, const char *end) override; 7926 }; 7927 7928 } // namespace 7929 7930 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7931 const char *end) { 7932 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7933 getLocationOfByte(end), /*IsStringLocation*/true, 7934 getSpecifierRange(start, end - start)); 7935 } 7936 7937 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7938 const analyze_scanf::ScanfSpecifier &FS, 7939 const char *startSpecifier, 7940 unsigned specifierLen) { 7941 const analyze_scanf::ScanfConversionSpecifier &CS = 7942 FS.getConversionSpecifier(); 7943 7944 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7945 getLocationOfByte(CS.getStart()), 7946 startSpecifier, specifierLen, 7947 CS.getStart(), CS.getLength()); 7948 } 7949 7950 bool CheckScanfHandler::HandleScanfSpecifier( 7951 const analyze_scanf::ScanfSpecifier &FS, 7952 const char *startSpecifier, 7953 unsigned specifierLen) { 7954 using namespace analyze_scanf; 7955 using namespace analyze_format_string; 7956 7957 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 7958 7959 // Handle case where '%' and '*' don't consume an argument. These shouldn't 7960 // be used to decide if we are using positional arguments consistently. 7961 if (FS.consumesDataArgument()) { 7962 if (atFirstArg) { 7963 atFirstArg = false; 7964 usesPositionalArgs = FS.usesPositionalArg(); 7965 } 7966 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7967 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7968 startSpecifier, specifierLen); 7969 return false; 7970 } 7971 } 7972 7973 // Check if the field with is non-zero. 7974 const OptionalAmount &Amt = FS.getFieldWidth(); 7975 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 7976 if (Amt.getConstantAmount() == 0) { 7977 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 7978 Amt.getConstantLength()); 7979 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 7980 getLocationOfByte(Amt.getStart()), 7981 /*IsStringLocation*/true, R, 7982 FixItHint::CreateRemoval(R)); 7983 } 7984 } 7985 7986 if (!FS.consumesDataArgument()) { 7987 // FIXME: Technically specifying a precision or field width here 7988 // makes no sense. Worth issuing a warning at some point. 7989 return true; 7990 } 7991 7992 // Consume the argument. 7993 unsigned argIndex = FS.getArgIndex(); 7994 if (argIndex < NumDataArgs) { 7995 // The check to see if the argIndex is valid will come later. 7996 // We set the bit here because we may exit early from this 7997 // function if we encounter some other error. 7998 CoveredArgs.set(argIndex); 7999 } 8000 8001 // Check the length modifier is valid with the given conversion specifier. 8002 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo())) 8003 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8004 diag::warn_format_nonsensical_length); 8005 else if (!FS.hasStandardLengthModifier()) 8006 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8007 else if (!FS.hasStandardLengthConversionCombination()) 8008 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8009 diag::warn_format_non_standard_conversion_spec); 8010 8011 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8012 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8013 8014 // The remaining checks depend on the data arguments. 8015 if (HasVAListArg) 8016 return true; 8017 8018 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8019 return false; 8020 8021 // Check that the argument type matches the format specifier. 8022 const Expr *Ex = getDataArg(argIndex); 8023 if (!Ex) 8024 return true; 8025 8026 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8027 8028 if (!AT.isValid()) { 8029 return true; 8030 } 8031 8032 analyze_format_string::ArgType::MatchKind Match = 8033 AT.matchesType(S.Context, Ex->getType()); 8034 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8035 if (Match == analyze_format_string::ArgType::Match) 8036 return true; 8037 8038 ScanfSpecifier fixedFS = FS; 8039 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8040 S.getLangOpts(), S.Context); 8041 8042 unsigned Diag = 8043 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8044 : diag::warn_format_conversion_argument_type_mismatch; 8045 8046 if (Success) { 8047 // Get the fix string from the fixed format specifier. 8048 SmallString<128> buf; 8049 llvm::raw_svector_ostream os(buf); 8050 fixedFS.toString(os); 8051 8052 EmitFormatDiagnostic( 8053 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8054 << Ex->getType() << false << Ex->getSourceRange(), 8055 Ex->getBeginLoc(), 8056 /*IsStringLocation*/ false, 8057 getSpecifierRange(startSpecifier, specifierLen), 8058 FixItHint::CreateReplacement( 8059 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8060 } else { 8061 EmitFormatDiagnostic(S.PDiag(Diag) 8062 << AT.getRepresentativeTypeName(S.Context) 8063 << Ex->getType() << false << Ex->getSourceRange(), 8064 Ex->getBeginLoc(), 8065 /*IsStringLocation*/ false, 8066 getSpecifierRange(startSpecifier, specifierLen)); 8067 } 8068 8069 return true; 8070 } 8071 8072 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8073 const Expr *OrigFormatExpr, 8074 ArrayRef<const Expr *> Args, 8075 bool HasVAListArg, unsigned format_idx, 8076 unsigned firstDataArg, 8077 Sema::FormatStringType Type, 8078 bool inFunctionCall, 8079 Sema::VariadicCallType CallType, 8080 llvm::SmallBitVector &CheckedVarArgs, 8081 UncoveredArgHandler &UncoveredArg) { 8082 // CHECK: is the format string a wide literal? 8083 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8084 CheckFormatHandler::EmitFormatDiagnostic( 8085 S, inFunctionCall, Args[format_idx], 8086 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8087 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8088 return; 8089 } 8090 8091 // Str - The format string. NOTE: this is NOT null-terminated! 8092 StringRef StrRef = FExpr->getString(); 8093 const char *Str = StrRef.data(); 8094 // Account for cases where the string literal is truncated in a declaration. 8095 const ConstantArrayType *T = 8096 S.Context.getAsConstantArrayType(FExpr->getType()); 8097 assert(T && "String literal not of constant array type!"); 8098 size_t TypeSize = T->getSize().getZExtValue(); 8099 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8100 const unsigned numDataArgs = Args.size() - firstDataArg; 8101 8102 // Emit a warning if the string literal is truncated and does not contain an 8103 // embedded null character. 8104 if (TypeSize <= StrRef.size() && 8105 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8106 CheckFormatHandler::EmitFormatDiagnostic( 8107 S, inFunctionCall, Args[format_idx], 8108 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8109 FExpr->getBeginLoc(), 8110 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8111 return; 8112 } 8113 8114 // CHECK: empty format string? 8115 if (StrLen == 0 && numDataArgs > 0) { 8116 CheckFormatHandler::EmitFormatDiagnostic( 8117 S, inFunctionCall, Args[format_idx], 8118 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8119 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8120 return; 8121 } 8122 8123 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8124 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8125 Type == Sema::FST_OSTrace) { 8126 CheckPrintfHandler H( 8127 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8128 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8129 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8130 CheckedVarArgs, UncoveredArg); 8131 8132 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8133 S.getLangOpts(), 8134 S.Context.getTargetInfo(), 8135 Type == Sema::FST_FreeBSDKPrintf)) 8136 H.DoneProcessing(); 8137 } else if (Type == Sema::FST_Scanf) { 8138 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8139 numDataArgs, Str, HasVAListArg, Args, format_idx, 8140 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8141 8142 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8143 S.getLangOpts(), 8144 S.Context.getTargetInfo())) 8145 H.DoneProcessing(); 8146 } // TODO: handle other formats 8147 } 8148 8149 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8150 // Str - The format string. NOTE: this is NOT null-terminated! 8151 StringRef StrRef = FExpr->getString(); 8152 const char *Str = StrRef.data(); 8153 // Account for cases where the string literal is truncated in a declaration. 8154 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8155 assert(T && "String literal not of constant array type!"); 8156 size_t TypeSize = T->getSize().getZExtValue(); 8157 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8158 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8159 getLangOpts(), 8160 Context.getTargetInfo()); 8161 } 8162 8163 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8164 8165 // Returns the related absolute value function that is larger, of 0 if one 8166 // does not exist. 8167 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8168 switch (AbsFunction) { 8169 default: 8170 return 0; 8171 8172 case Builtin::BI__builtin_abs: 8173 return Builtin::BI__builtin_labs; 8174 case Builtin::BI__builtin_labs: 8175 return Builtin::BI__builtin_llabs; 8176 case Builtin::BI__builtin_llabs: 8177 return 0; 8178 8179 case Builtin::BI__builtin_fabsf: 8180 return Builtin::BI__builtin_fabs; 8181 case Builtin::BI__builtin_fabs: 8182 return Builtin::BI__builtin_fabsl; 8183 case Builtin::BI__builtin_fabsl: 8184 return 0; 8185 8186 case Builtin::BI__builtin_cabsf: 8187 return Builtin::BI__builtin_cabs; 8188 case Builtin::BI__builtin_cabs: 8189 return Builtin::BI__builtin_cabsl; 8190 case Builtin::BI__builtin_cabsl: 8191 return 0; 8192 8193 case Builtin::BIabs: 8194 return Builtin::BIlabs; 8195 case Builtin::BIlabs: 8196 return Builtin::BIllabs; 8197 case Builtin::BIllabs: 8198 return 0; 8199 8200 case Builtin::BIfabsf: 8201 return Builtin::BIfabs; 8202 case Builtin::BIfabs: 8203 return Builtin::BIfabsl; 8204 case Builtin::BIfabsl: 8205 return 0; 8206 8207 case Builtin::BIcabsf: 8208 return Builtin::BIcabs; 8209 case Builtin::BIcabs: 8210 return Builtin::BIcabsl; 8211 case Builtin::BIcabsl: 8212 return 0; 8213 } 8214 } 8215 8216 // Returns the argument type of the absolute value function. 8217 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8218 unsigned AbsType) { 8219 if (AbsType == 0) 8220 return QualType(); 8221 8222 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8223 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8224 if (Error != ASTContext::GE_None) 8225 return QualType(); 8226 8227 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8228 if (!FT) 8229 return QualType(); 8230 8231 if (FT->getNumParams() != 1) 8232 return QualType(); 8233 8234 return FT->getParamType(0); 8235 } 8236 8237 // Returns the best absolute value function, or zero, based on type and 8238 // current absolute value function. 8239 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8240 unsigned AbsFunctionKind) { 8241 unsigned BestKind = 0; 8242 uint64_t ArgSize = Context.getTypeSize(ArgType); 8243 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8244 Kind = getLargerAbsoluteValueFunction(Kind)) { 8245 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8246 if (Context.getTypeSize(ParamType) >= ArgSize) { 8247 if (BestKind == 0) 8248 BestKind = Kind; 8249 else if (Context.hasSameType(ParamType, ArgType)) { 8250 BestKind = Kind; 8251 break; 8252 } 8253 } 8254 } 8255 return BestKind; 8256 } 8257 8258 enum AbsoluteValueKind { 8259 AVK_Integer, 8260 AVK_Floating, 8261 AVK_Complex 8262 }; 8263 8264 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8265 if (T->isIntegralOrEnumerationType()) 8266 return AVK_Integer; 8267 if (T->isRealFloatingType()) 8268 return AVK_Floating; 8269 if (T->isAnyComplexType()) 8270 return AVK_Complex; 8271 8272 llvm_unreachable("Type not integer, floating, or complex"); 8273 } 8274 8275 // Changes the absolute value function to a different type. Preserves whether 8276 // the function is a builtin. 8277 static unsigned changeAbsFunction(unsigned AbsKind, 8278 AbsoluteValueKind ValueKind) { 8279 switch (ValueKind) { 8280 case AVK_Integer: 8281 switch (AbsKind) { 8282 default: 8283 return 0; 8284 case Builtin::BI__builtin_fabsf: 8285 case Builtin::BI__builtin_fabs: 8286 case Builtin::BI__builtin_fabsl: 8287 case Builtin::BI__builtin_cabsf: 8288 case Builtin::BI__builtin_cabs: 8289 case Builtin::BI__builtin_cabsl: 8290 return Builtin::BI__builtin_abs; 8291 case Builtin::BIfabsf: 8292 case Builtin::BIfabs: 8293 case Builtin::BIfabsl: 8294 case Builtin::BIcabsf: 8295 case Builtin::BIcabs: 8296 case Builtin::BIcabsl: 8297 return Builtin::BIabs; 8298 } 8299 case AVK_Floating: 8300 switch (AbsKind) { 8301 default: 8302 return 0; 8303 case Builtin::BI__builtin_abs: 8304 case Builtin::BI__builtin_labs: 8305 case Builtin::BI__builtin_llabs: 8306 case Builtin::BI__builtin_cabsf: 8307 case Builtin::BI__builtin_cabs: 8308 case Builtin::BI__builtin_cabsl: 8309 return Builtin::BI__builtin_fabsf; 8310 case Builtin::BIabs: 8311 case Builtin::BIlabs: 8312 case Builtin::BIllabs: 8313 case Builtin::BIcabsf: 8314 case Builtin::BIcabs: 8315 case Builtin::BIcabsl: 8316 return Builtin::BIfabsf; 8317 } 8318 case AVK_Complex: 8319 switch (AbsKind) { 8320 default: 8321 return 0; 8322 case Builtin::BI__builtin_abs: 8323 case Builtin::BI__builtin_labs: 8324 case Builtin::BI__builtin_llabs: 8325 case Builtin::BI__builtin_fabsf: 8326 case Builtin::BI__builtin_fabs: 8327 case Builtin::BI__builtin_fabsl: 8328 return Builtin::BI__builtin_cabsf; 8329 case Builtin::BIabs: 8330 case Builtin::BIlabs: 8331 case Builtin::BIllabs: 8332 case Builtin::BIfabsf: 8333 case Builtin::BIfabs: 8334 case Builtin::BIfabsl: 8335 return Builtin::BIcabsf; 8336 } 8337 } 8338 llvm_unreachable("Unable to convert function"); 8339 } 8340 8341 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8342 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8343 if (!FnInfo) 8344 return 0; 8345 8346 switch (FDecl->getBuiltinID()) { 8347 default: 8348 return 0; 8349 case Builtin::BI__builtin_abs: 8350 case Builtin::BI__builtin_fabs: 8351 case Builtin::BI__builtin_fabsf: 8352 case Builtin::BI__builtin_fabsl: 8353 case Builtin::BI__builtin_labs: 8354 case Builtin::BI__builtin_llabs: 8355 case Builtin::BI__builtin_cabs: 8356 case Builtin::BI__builtin_cabsf: 8357 case Builtin::BI__builtin_cabsl: 8358 case Builtin::BIabs: 8359 case Builtin::BIlabs: 8360 case Builtin::BIllabs: 8361 case Builtin::BIfabs: 8362 case Builtin::BIfabsf: 8363 case Builtin::BIfabsl: 8364 case Builtin::BIcabs: 8365 case Builtin::BIcabsf: 8366 case Builtin::BIcabsl: 8367 return FDecl->getBuiltinID(); 8368 } 8369 llvm_unreachable("Unknown Builtin type"); 8370 } 8371 8372 // If the replacement is valid, emit a note with replacement function. 8373 // Additionally, suggest including the proper header if not already included. 8374 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8375 unsigned AbsKind, QualType ArgType) { 8376 bool EmitHeaderHint = true; 8377 const char *HeaderName = nullptr; 8378 const char *FunctionName = nullptr; 8379 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8380 FunctionName = "std::abs"; 8381 if (ArgType->isIntegralOrEnumerationType()) { 8382 HeaderName = "cstdlib"; 8383 } else if (ArgType->isRealFloatingType()) { 8384 HeaderName = "cmath"; 8385 } else { 8386 llvm_unreachable("Invalid Type"); 8387 } 8388 8389 // Lookup all std::abs 8390 if (NamespaceDecl *Std = S.getStdNamespace()) { 8391 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8392 R.suppressDiagnostics(); 8393 S.LookupQualifiedName(R, Std); 8394 8395 for (const auto *I : R) { 8396 const FunctionDecl *FDecl = nullptr; 8397 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8398 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8399 } else { 8400 FDecl = dyn_cast<FunctionDecl>(I); 8401 } 8402 if (!FDecl) 8403 continue; 8404 8405 // Found std::abs(), check that they are the right ones. 8406 if (FDecl->getNumParams() != 1) 8407 continue; 8408 8409 // Check that the parameter type can handle the argument. 8410 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8411 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8412 S.Context.getTypeSize(ArgType) <= 8413 S.Context.getTypeSize(ParamType)) { 8414 // Found a function, don't need the header hint. 8415 EmitHeaderHint = false; 8416 break; 8417 } 8418 } 8419 } 8420 } else { 8421 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8422 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8423 8424 if (HeaderName) { 8425 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8426 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8427 R.suppressDiagnostics(); 8428 S.LookupName(R, S.getCurScope()); 8429 8430 if (R.isSingleResult()) { 8431 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8432 if (FD && FD->getBuiltinID() == AbsKind) { 8433 EmitHeaderHint = false; 8434 } else { 8435 return; 8436 } 8437 } else if (!R.empty()) { 8438 return; 8439 } 8440 } 8441 } 8442 8443 S.Diag(Loc, diag::note_replace_abs_function) 8444 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8445 8446 if (!HeaderName) 8447 return; 8448 8449 if (!EmitHeaderHint) 8450 return; 8451 8452 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8453 << FunctionName; 8454 } 8455 8456 template <std::size_t StrLen> 8457 static bool IsStdFunction(const FunctionDecl *FDecl, 8458 const char (&Str)[StrLen]) { 8459 if (!FDecl) 8460 return false; 8461 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8462 return false; 8463 if (!FDecl->isInStdNamespace()) 8464 return false; 8465 8466 return true; 8467 } 8468 8469 // Warn when using the wrong abs() function. 8470 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8471 const FunctionDecl *FDecl) { 8472 if (Call->getNumArgs() != 1) 8473 return; 8474 8475 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8476 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8477 if (AbsKind == 0 && !IsStdAbs) 8478 return; 8479 8480 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8481 QualType ParamType = Call->getArg(0)->getType(); 8482 8483 // Unsigned types cannot be negative. Suggest removing the absolute value 8484 // function call. 8485 if (ArgType->isUnsignedIntegerType()) { 8486 const char *FunctionName = 8487 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8488 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8489 Diag(Call->getExprLoc(), diag::note_remove_abs) 8490 << FunctionName 8491 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8492 return; 8493 } 8494 8495 // Taking the absolute value of a pointer is very suspicious, they probably 8496 // wanted to index into an array, dereference a pointer, call a function, etc. 8497 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8498 unsigned DiagType = 0; 8499 if (ArgType->isFunctionType()) 8500 DiagType = 1; 8501 else if (ArgType->isArrayType()) 8502 DiagType = 2; 8503 8504 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8505 return; 8506 } 8507 8508 // std::abs has overloads which prevent most of the absolute value problems 8509 // from occurring. 8510 if (IsStdAbs) 8511 return; 8512 8513 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8514 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8515 8516 // The argument and parameter are the same kind. Check if they are the right 8517 // size. 8518 if (ArgValueKind == ParamValueKind) { 8519 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8520 return; 8521 8522 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8523 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8524 << FDecl << ArgType << ParamType; 8525 8526 if (NewAbsKind == 0) 8527 return; 8528 8529 emitReplacement(*this, Call->getExprLoc(), 8530 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8531 return; 8532 } 8533 8534 // ArgValueKind != ParamValueKind 8535 // The wrong type of absolute value function was used. Attempt to find the 8536 // proper one. 8537 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8538 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8539 if (NewAbsKind == 0) 8540 return; 8541 8542 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8543 << FDecl << ParamValueKind << ArgValueKind; 8544 8545 emitReplacement(*this, Call->getExprLoc(), 8546 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8547 } 8548 8549 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8550 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8551 const FunctionDecl *FDecl) { 8552 if (!Call || !FDecl) return; 8553 8554 // Ignore template specializations and macros. 8555 if (inTemplateInstantiation()) return; 8556 if (Call->getExprLoc().isMacroID()) return; 8557 8558 // Only care about the one template argument, two function parameter std::max 8559 if (Call->getNumArgs() != 2) return; 8560 if (!IsStdFunction(FDecl, "max")) return; 8561 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8562 if (!ArgList) return; 8563 if (ArgList->size() != 1) return; 8564 8565 // Check that template type argument is unsigned integer. 8566 const auto& TA = ArgList->get(0); 8567 if (TA.getKind() != TemplateArgument::Type) return; 8568 QualType ArgType = TA.getAsType(); 8569 if (!ArgType->isUnsignedIntegerType()) return; 8570 8571 // See if either argument is a literal zero. 8572 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8573 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8574 if (!MTE) return false; 8575 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8576 if (!Num) return false; 8577 if (Num->getValue() != 0) return false; 8578 return true; 8579 }; 8580 8581 const Expr *FirstArg = Call->getArg(0); 8582 const Expr *SecondArg = Call->getArg(1); 8583 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8584 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8585 8586 // Only warn when exactly one argument is zero. 8587 if (IsFirstArgZero == IsSecondArgZero) return; 8588 8589 SourceRange FirstRange = FirstArg->getSourceRange(); 8590 SourceRange SecondRange = SecondArg->getSourceRange(); 8591 8592 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8593 8594 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8595 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8596 8597 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8598 SourceRange RemovalRange; 8599 if (IsFirstArgZero) { 8600 RemovalRange = SourceRange(FirstRange.getBegin(), 8601 SecondRange.getBegin().getLocWithOffset(-1)); 8602 } else { 8603 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8604 SecondRange.getEnd()); 8605 } 8606 8607 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8608 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8609 << FixItHint::CreateRemoval(RemovalRange); 8610 } 8611 8612 //===--- CHECK: Standard memory functions ---------------------------------===// 8613 8614 /// Takes the expression passed to the size_t parameter of functions 8615 /// such as memcmp, strncat, etc and warns if it's a comparison. 8616 /// 8617 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8618 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8619 IdentifierInfo *FnName, 8620 SourceLocation FnLoc, 8621 SourceLocation RParenLoc) { 8622 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8623 if (!Size) 8624 return false; 8625 8626 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8627 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8628 return false; 8629 8630 SourceRange SizeRange = Size->getSourceRange(); 8631 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8632 << SizeRange << FnName; 8633 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8634 << FnName 8635 << FixItHint::CreateInsertion( 8636 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8637 << FixItHint::CreateRemoval(RParenLoc); 8638 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8639 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8640 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8641 ")"); 8642 8643 return true; 8644 } 8645 8646 /// Determine whether the given type is or contains a dynamic class type 8647 /// (e.g., whether it has a vtable). 8648 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8649 bool &IsContained) { 8650 // Look through array types while ignoring qualifiers. 8651 const Type *Ty = T->getBaseElementTypeUnsafe(); 8652 IsContained = false; 8653 8654 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8655 RD = RD ? RD->getDefinition() : nullptr; 8656 if (!RD || RD->isInvalidDecl()) 8657 return nullptr; 8658 8659 if (RD->isDynamicClass()) 8660 return RD; 8661 8662 // Check all the fields. If any bases were dynamic, the class is dynamic. 8663 // It's impossible for a class to transitively contain itself by value, so 8664 // infinite recursion is impossible. 8665 for (auto *FD : RD->fields()) { 8666 bool SubContained; 8667 if (const CXXRecordDecl *ContainedRD = 8668 getContainedDynamicClass(FD->getType(), SubContained)) { 8669 IsContained = true; 8670 return ContainedRD; 8671 } 8672 } 8673 8674 return nullptr; 8675 } 8676 8677 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8678 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8679 if (Unary->getKind() == UETT_SizeOf) 8680 return Unary; 8681 return nullptr; 8682 } 8683 8684 /// If E is a sizeof expression, returns its argument expression, 8685 /// otherwise returns NULL. 8686 static const Expr *getSizeOfExprArg(const Expr *E) { 8687 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8688 if (!SizeOf->isArgumentType()) 8689 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8690 return nullptr; 8691 } 8692 8693 /// If E is a sizeof expression, returns its argument type. 8694 static QualType getSizeOfArgType(const Expr *E) { 8695 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8696 return SizeOf->getTypeOfArgument(); 8697 return QualType(); 8698 } 8699 8700 namespace { 8701 8702 struct SearchNonTrivialToInitializeField 8703 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8704 using Super = 8705 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8706 8707 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8708 8709 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8710 SourceLocation SL) { 8711 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8712 asDerived().visitArray(PDIK, AT, SL); 8713 return; 8714 } 8715 8716 Super::visitWithKind(PDIK, FT, SL); 8717 } 8718 8719 void visitARCStrong(QualType FT, SourceLocation SL) { 8720 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8721 } 8722 void visitARCWeak(QualType FT, SourceLocation SL) { 8723 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8724 } 8725 void visitStruct(QualType FT, SourceLocation SL) { 8726 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8727 visit(FD->getType(), FD->getLocation()); 8728 } 8729 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8730 const ArrayType *AT, SourceLocation SL) { 8731 visit(getContext().getBaseElementType(AT), SL); 8732 } 8733 void visitTrivial(QualType FT, SourceLocation SL) {} 8734 8735 static void diag(QualType RT, const Expr *E, Sema &S) { 8736 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8737 } 8738 8739 ASTContext &getContext() { return S.getASTContext(); } 8740 8741 const Expr *E; 8742 Sema &S; 8743 }; 8744 8745 struct SearchNonTrivialToCopyField 8746 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8747 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8748 8749 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8750 8751 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8752 SourceLocation SL) { 8753 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8754 asDerived().visitArray(PCK, AT, SL); 8755 return; 8756 } 8757 8758 Super::visitWithKind(PCK, FT, SL); 8759 } 8760 8761 void visitARCStrong(QualType FT, SourceLocation SL) { 8762 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8763 } 8764 void visitARCWeak(QualType FT, SourceLocation SL) { 8765 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8766 } 8767 void visitStruct(QualType FT, SourceLocation SL) { 8768 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8769 visit(FD->getType(), FD->getLocation()); 8770 } 8771 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8772 SourceLocation SL) { 8773 visit(getContext().getBaseElementType(AT), SL); 8774 } 8775 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8776 SourceLocation SL) {} 8777 void visitTrivial(QualType FT, SourceLocation SL) {} 8778 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8779 8780 static void diag(QualType RT, const Expr *E, Sema &S) { 8781 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8782 } 8783 8784 ASTContext &getContext() { return S.getASTContext(); } 8785 8786 const Expr *E; 8787 Sema &S; 8788 }; 8789 8790 } 8791 8792 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8793 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8794 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8795 8796 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8797 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8798 return false; 8799 8800 return doesExprLikelyComputeSize(BO->getLHS()) || 8801 doesExprLikelyComputeSize(BO->getRHS()); 8802 } 8803 8804 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8805 } 8806 8807 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8808 /// 8809 /// \code 8810 /// #define MACRO 0 8811 /// foo(MACRO); 8812 /// foo(0); 8813 /// \endcode 8814 /// 8815 /// This should return true for the first call to foo, but not for the second 8816 /// (regardless of whether foo is a macro or function). 8817 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8818 SourceLocation CallLoc, 8819 SourceLocation ArgLoc) { 8820 if (!CallLoc.isMacroID()) 8821 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8822 8823 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8824 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8825 } 8826 8827 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8828 /// last two arguments transposed. 8829 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8830 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8831 return; 8832 8833 const Expr *SizeArg = 8834 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8835 8836 auto isLiteralZero = [](const Expr *E) { 8837 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 8838 }; 8839 8840 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8841 SourceLocation CallLoc = Call->getRParenLoc(); 8842 SourceManager &SM = S.getSourceManager(); 8843 if (isLiteralZero(SizeArg) && 8844 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 8845 8846 SourceLocation DiagLoc = SizeArg->getExprLoc(); 8847 8848 // Some platforms #define bzero to __builtin_memset. See if this is the 8849 // case, and if so, emit a better diagnostic. 8850 if (BId == Builtin::BIbzero || 8851 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 8852 CallLoc, SM, S.getLangOpts()) == "bzero")) { 8853 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 8854 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 8855 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 8856 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 8857 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 8858 } 8859 return; 8860 } 8861 8862 // If the second argument to a memset is a sizeof expression and the third 8863 // isn't, this is also likely an error. This should catch 8864 // 'memset(buf, sizeof(buf), 0xff)'. 8865 if (BId == Builtin::BImemset && 8866 doesExprLikelyComputeSize(Call->getArg(1)) && 8867 !doesExprLikelyComputeSize(Call->getArg(2))) { 8868 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 8869 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 8870 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 8871 return; 8872 } 8873 } 8874 8875 /// Check for dangerous or invalid arguments to memset(). 8876 /// 8877 /// This issues warnings on known problematic, dangerous or unspecified 8878 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 8879 /// function calls. 8880 /// 8881 /// \param Call The call expression to diagnose. 8882 void Sema::CheckMemaccessArguments(const CallExpr *Call, 8883 unsigned BId, 8884 IdentifierInfo *FnName) { 8885 assert(BId != 0); 8886 8887 // It is possible to have a non-standard definition of memset. Validate 8888 // we have enough arguments, and if not, abort further checking. 8889 unsigned ExpectedNumArgs = 8890 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 8891 if (Call->getNumArgs() < ExpectedNumArgs) 8892 return; 8893 8894 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 8895 BId == Builtin::BIstrndup ? 1 : 2); 8896 unsigned LenArg = 8897 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 8898 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 8899 8900 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 8901 Call->getBeginLoc(), Call->getRParenLoc())) 8902 return; 8903 8904 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 8905 CheckMemaccessSize(*this, BId, Call); 8906 8907 // We have special checking when the length is a sizeof expression. 8908 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 8909 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 8910 llvm::FoldingSetNodeID SizeOfArgID; 8911 8912 // Although widely used, 'bzero' is not a standard function. Be more strict 8913 // with the argument types before allowing diagnostics and only allow the 8914 // form bzero(ptr, sizeof(...)). 8915 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8916 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 8917 return; 8918 8919 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 8920 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 8921 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 8922 8923 QualType DestTy = Dest->getType(); 8924 QualType PointeeTy; 8925 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 8926 PointeeTy = DestPtrTy->getPointeeType(); 8927 8928 // Never warn about void type pointers. This can be used to suppress 8929 // false positives. 8930 if (PointeeTy->isVoidType()) 8931 continue; 8932 8933 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 8934 // actually comparing the expressions for equality. Because computing the 8935 // expression IDs can be expensive, we only do this if the diagnostic is 8936 // enabled. 8937 if (SizeOfArg && 8938 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 8939 SizeOfArg->getExprLoc())) { 8940 // We only compute IDs for expressions if the warning is enabled, and 8941 // cache the sizeof arg's ID. 8942 if (SizeOfArgID == llvm::FoldingSetNodeID()) 8943 SizeOfArg->Profile(SizeOfArgID, Context, true); 8944 llvm::FoldingSetNodeID DestID; 8945 Dest->Profile(DestID, Context, true); 8946 if (DestID == SizeOfArgID) { 8947 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 8948 // over sizeof(src) as well. 8949 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 8950 StringRef ReadableName = FnName->getName(); 8951 8952 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 8953 if (UnaryOp->getOpcode() == UO_AddrOf) 8954 ActionIdx = 1; // If its an address-of operator, just remove it. 8955 if (!PointeeTy->isIncompleteType() && 8956 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 8957 ActionIdx = 2; // If the pointee's size is sizeof(char), 8958 // suggest an explicit length. 8959 8960 // If the function is defined as a builtin macro, do not show macro 8961 // expansion. 8962 SourceLocation SL = SizeOfArg->getExprLoc(); 8963 SourceRange DSR = Dest->getSourceRange(); 8964 SourceRange SSR = SizeOfArg->getSourceRange(); 8965 SourceManager &SM = getSourceManager(); 8966 8967 if (SM.isMacroArgExpansion(SL)) { 8968 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 8969 SL = SM.getSpellingLoc(SL); 8970 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 8971 SM.getSpellingLoc(DSR.getEnd())); 8972 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 8973 SM.getSpellingLoc(SSR.getEnd())); 8974 } 8975 8976 DiagRuntimeBehavior(SL, SizeOfArg, 8977 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 8978 << ReadableName 8979 << PointeeTy 8980 << DestTy 8981 << DSR 8982 << SSR); 8983 DiagRuntimeBehavior(SL, SizeOfArg, 8984 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 8985 << ActionIdx 8986 << SSR); 8987 8988 break; 8989 } 8990 } 8991 8992 // Also check for cases where the sizeof argument is the exact same 8993 // type as the memory argument, and where it points to a user-defined 8994 // record type. 8995 if (SizeOfArgTy != QualType()) { 8996 if (PointeeTy->isRecordType() && 8997 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 8998 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 8999 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9000 << FnName << SizeOfArgTy << ArgIdx 9001 << PointeeTy << Dest->getSourceRange() 9002 << LenExpr->getSourceRange()); 9003 break; 9004 } 9005 } 9006 } else if (DestTy->isArrayType()) { 9007 PointeeTy = DestTy; 9008 } 9009 9010 if (PointeeTy == QualType()) 9011 continue; 9012 9013 // Always complain about dynamic classes. 9014 bool IsContained; 9015 if (const CXXRecordDecl *ContainedRD = 9016 getContainedDynamicClass(PointeeTy, IsContained)) { 9017 9018 unsigned OperationType = 0; 9019 // "overwritten" if we're warning about the destination for any call 9020 // but memcmp; otherwise a verb appropriate to the call. 9021 if (ArgIdx != 0 || BId == Builtin::BImemcmp) { 9022 if (BId == Builtin::BImemcpy) 9023 OperationType = 1; 9024 else if(BId == Builtin::BImemmove) 9025 OperationType = 2; 9026 else if (BId == Builtin::BImemcmp) 9027 OperationType = 3; 9028 } 9029 9030 DiagRuntimeBehavior( 9031 Dest->getExprLoc(), Dest, 9032 PDiag(diag::warn_dyn_class_memaccess) 9033 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx) 9034 << FnName << IsContained << ContainedRD << OperationType 9035 << Call->getCallee()->getSourceRange()); 9036 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9037 BId != Builtin::BImemset) 9038 DiagRuntimeBehavior( 9039 Dest->getExprLoc(), Dest, 9040 PDiag(diag::warn_arc_object_memaccess) 9041 << ArgIdx << FnName << PointeeTy 9042 << Call->getCallee()->getSourceRange()); 9043 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9044 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9045 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9046 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9047 PDiag(diag::warn_cstruct_memaccess) 9048 << ArgIdx << FnName << PointeeTy << 0); 9049 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9050 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9051 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9052 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9053 PDiag(diag::warn_cstruct_memaccess) 9054 << ArgIdx << FnName << PointeeTy << 1); 9055 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9056 } else { 9057 continue; 9058 } 9059 } else 9060 continue; 9061 9062 DiagRuntimeBehavior( 9063 Dest->getExprLoc(), Dest, 9064 PDiag(diag::note_bad_memaccess_silence) 9065 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9066 break; 9067 } 9068 } 9069 9070 // A little helper routine: ignore addition and subtraction of integer literals. 9071 // This intentionally does not ignore all integer constant expressions because 9072 // we don't want to remove sizeof(). 9073 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9074 Ex = Ex->IgnoreParenCasts(); 9075 9076 while (true) { 9077 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9078 if (!BO || !BO->isAdditiveOp()) 9079 break; 9080 9081 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9082 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9083 9084 if (isa<IntegerLiteral>(RHS)) 9085 Ex = LHS; 9086 else if (isa<IntegerLiteral>(LHS)) 9087 Ex = RHS; 9088 else 9089 break; 9090 } 9091 9092 return Ex; 9093 } 9094 9095 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9096 ASTContext &Context) { 9097 // Only handle constant-sized or VLAs, but not flexible members. 9098 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9099 // Only issue the FIXIT for arrays of size > 1. 9100 if (CAT->getSize().getSExtValue() <= 1) 9101 return false; 9102 } else if (!Ty->isVariableArrayType()) { 9103 return false; 9104 } 9105 return true; 9106 } 9107 9108 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9109 // be the size of the source, instead of the destination. 9110 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9111 IdentifierInfo *FnName) { 9112 9113 // Don't crash if the user has the wrong number of arguments 9114 unsigned NumArgs = Call->getNumArgs(); 9115 if ((NumArgs != 3) && (NumArgs != 4)) 9116 return; 9117 9118 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9119 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9120 const Expr *CompareWithSrc = nullptr; 9121 9122 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9123 Call->getBeginLoc(), Call->getRParenLoc())) 9124 return; 9125 9126 // Look for 'strlcpy(dst, x, sizeof(x))' 9127 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9128 CompareWithSrc = Ex; 9129 else { 9130 // Look for 'strlcpy(dst, x, strlen(x))' 9131 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9132 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9133 SizeCall->getNumArgs() == 1) 9134 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9135 } 9136 } 9137 9138 if (!CompareWithSrc) 9139 return; 9140 9141 // Determine if the argument to sizeof/strlen is equal to the source 9142 // argument. In principle there's all kinds of things you could do 9143 // here, for instance creating an == expression and evaluating it with 9144 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9145 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9146 if (!SrcArgDRE) 9147 return; 9148 9149 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9150 if (!CompareWithSrcDRE || 9151 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9152 return; 9153 9154 const Expr *OriginalSizeArg = Call->getArg(2); 9155 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9156 << OriginalSizeArg->getSourceRange() << FnName; 9157 9158 // Output a FIXIT hint if the destination is an array (rather than a 9159 // pointer to an array). This could be enhanced to handle some 9160 // pointers if we know the actual size, like if DstArg is 'array+2' 9161 // we could say 'sizeof(array)-2'. 9162 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9163 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9164 return; 9165 9166 SmallString<128> sizeString; 9167 llvm::raw_svector_ostream OS(sizeString); 9168 OS << "sizeof("; 9169 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9170 OS << ")"; 9171 9172 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9173 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9174 OS.str()); 9175 } 9176 9177 /// Check if two expressions refer to the same declaration. 9178 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9179 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9180 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9181 return D1->getDecl() == D2->getDecl(); 9182 return false; 9183 } 9184 9185 static const Expr *getStrlenExprArg(const Expr *E) { 9186 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9187 const FunctionDecl *FD = CE->getDirectCallee(); 9188 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9189 return nullptr; 9190 return CE->getArg(0)->IgnoreParenCasts(); 9191 } 9192 return nullptr; 9193 } 9194 9195 // Warn on anti-patterns as the 'size' argument to strncat. 9196 // The correct size argument should look like following: 9197 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9198 void Sema::CheckStrncatArguments(const CallExpr *CE, 9199 IdentifierInfo *FnName) { 9200 // Don't crash if the user has the wrong number of arguments. 9201 if (CE->getNumArgs() < 3) 9202 return; 9203 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9204 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9205 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9206 9207 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9208 CE->getRParenLoc())) 9209 return; 9210 9211 // Identify common expressions, which are wrongly used as the size argument 9212 // to strncat and may lead to buffer overflows. 9213 unsigned PatternType = 0; 9214 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9215 // - sizeof(dst) 9216 if (referToTheSameDecl(SizeOfArg, DstArg)) 9217 PatternType = 1; 9218 // - sizeof(src) 9219 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9220 PatternType = 2; 9221 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9222 if (BE->getOpcode() == BO_Sub) { 9223 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9224 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9225 // - sizeof(dst) - strlen(dst) 9226 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9227 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9228 PatternType = 1; 9229 // - sizeof(src) - (anything) 9230 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9231 PatternType = 2; 9232 } 9233 } 9234 9235 if (PatternType == 0) 9236 return; 9237 9238 // Generate the diagnostic. 9239 SourceLocation SL = LenArg->getBeginLoc(); 9240 SourceRange SR = LenArg->getSourceRange(); 9241 SourceManager &SM = getSourceManager(); 9242 9243 // If the function is defined as a builtin macro, do not show macro expansion. 9244 if (SM.isMacroArgExpansion(SL)) { 9245 SL = SM.getSpellingLoc(SL); 9246 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9247 SM.getSpellingLoc(SR.getEnd())); 9248 } 9249 9250 // Check if the destination is an array (rather than a pointer to an array). 9251 QualType DstTy = DstArg->getType(); 9252 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9253 Context); 9254 if (!isKnownSizeArray) { 9255 if (PatternType == 1) 9256 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9257 else 9258 Diag(SL, diag::warn_strncat_src_size) << SR; 9259 return; 9260 } 9261 9262 if (PatternType == 1) 9263 Diag(SL, diag::warn_strncat_large_size) << SR; 9264 else 9265 Diag(SL, diag::warn_strncat_src_size) << SR; 9266 9267 SmallString<128> sizeString; 9268 llvm::raw_svector_ostream OS(sizeString); 9269 OS << "sizeof("; 9270 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9271 OS << ") - "; 9272 OS << "strlen("; 9273 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9274 OS << ") - 1"; 9275 9276 Diag(SL, diag::note_strncat_wrong_size) 9277 << FixItHint::CreateReplacement(SR, OS.str()); 9278 } 9279 9280 void 9281 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9282 SourceLocation ReturnLoc, 9283 bool isObjCMethod, 9284 const AttrVec *Attrs, 9285 const FunctionDecl *FD) { 9286 // Check if the return value is null but should not be. 9287 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9288 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9289 CheckNonNullExpr(*this, RetValExp)) 9290 Diag(ReturnLoc, diag::warn_null_ret) 9291 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9292 9293 // C++11 [basic.stc.dynamic.allocation]p4: 9294 // If an allocation function declared with a non-throwing 9295 // exception-specification fails to allocate storage, it shall return 9296 // a null pointer. Any other allocation function that fails to allocate 9297 // storage shall indicate failure only by throwing an exception [...] 9298 if (FD) { 9299 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9300 if (Op == OO_New || Op == OO_Array_New) { 9301 const FunctionProtoType *Proto 9302 = FD->getType()->castAs<FunctionProtoType>(); 9303 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9304 CheckNonNullExpr(*this, RetValExp)) 9305 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9306 << FD << getLangOpts().CPlusPlus11; 9307 } 9308 } 9309 } 9310 9311 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9312 9313 /// Check for comparisons of floating point operands using != and ==. 9314 /// Issue a warning if these are no self-comparisons, as they are not likely 9315 /// to do what the programmer intended. 9316 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9317 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9318 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9319 9320 // Special case: check for x == x (which is OK). 9321 // Do not emit warnings for such cases. 9322 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9323 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9324 if (DRL->getDecl() == DRR->getDecl()) 9325 return; 9326 9327 // Special case: check for comparisons against literals that can be exactly 9328 // represented by APFloat. In such cases, do not emit a warning. This 9329 // is a heuristic: often comparison against such literals are used to 9330 // detect if a value in a variable has not changed. This clearly can 9331 // lead to false negatives. 9332 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9333 if (FLL->isExact()) 9334 return; 9335 } else 9336 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9337 if (FLR->isExact()) 9338 return; 9339 9340 // Check for comparisons with builtin types. 9341 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9342 if (CL->getBuiltinCallee()) 9343 return; 9344 9345 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9346 if (CR->getBuiltinCallee()) 9347 return; 9348 9349 // Emit the diagnostic. 9350 Diag(Loc, diag::warn_floatingpoint_eq) 9351 << LHS->getSourceRange() << RHS->getSourceRange(); 9352 } 9353 9354 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9355 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9356 9357 namespace { 9358 9359 /// Structure recording the 'active' range of an integer-valued 9360 /// expression. 9361 struct IntRange { 9362 /// The number of bits active in the int. 9363 unsigned Width; 9364 9365 /// True if the int is known not to have negative values. 9366 bool NonNegative; 9367 9368 IntRange(unsigned Width, bool NonNegative) 9369 : Width(Width), NonNegative(NonNegative) {} 9370 9371 /// Returns the range of the bool type. 9372 static IntRange forBoolType() { 9373 return IntRange(1, true); 9374 } 9375 9376 /// Returns the range of an opaque value of the given integral type. 9377 static IntRange forValueOfType(ASTContext &C, QualType T) { 9378 return forValueOfCanonicalType(C, 9379 T->getCanonicalTypeInternal().getTypePtr()); 9380 } 9381 9382 /// Returns the range of an opaque value of a canonical integral type. 9383 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9384 assert(T->isCanonicalUnqualified()); 9385 9386 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9387 T = VT->getElementType().getTypePtr(); 9388 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9389 T = CT->getElementType().getTypePtr(); 9390 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9391 T = AT->getValueType().getTypePtr(); 9392 9393 if (!C.getLangOpts().CPlusPlus) { 9394 // For enum types in C code, use the underlying datatype. 9395 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9396 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9397 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9398 // For enum types in C++, use the known bit width of the enumerators. 9399 EnumDecl *Enum = ET->getDecl(); 9400 // In C++11, enums can have a fixed underlying type. Use this type to 9401 // compute the range. 9402 if (Enum->isFixed()) { 9403 return IntRange(C.getIntWidth(QualType(T, 0)), 9404 !ET->isSignedIntegerOrEnumerationType()); 9405 } 9406 9407 unsigned NumPositive = Enum->getNumPositiveBits(); 9408 unsigned NumNegative = Enum->getNumNegativeBits(); 9409 9410 if (NumNegative == 0) 9411 return IntRange(NumPositive, true/*NonNegative*/); 9412 else 9413 return IntRange(std::max(NumPositive + 1, NumNegative), 9414 false/*NonNegative*/); 9415 } 9416 9417 const BuiltinType *BT = cast<BuiltinType>(T); 9418 assert(BT->isInteger()); 9419 9420 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9421 } 9422 9423 /// Returns the "target" range of a canonical integral type, i.e. 9424 /// the range of values expressible in the type. 9425 /// 9426 /// This matches forValueOfCanonicalType except that enums have the 9427 /// full range of their type, not the range of their enumerators. 9428 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9429 assert(T->isCanonicalUnqualified()); 9430 9431 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9432 T = VT->getElementType().getTypePtr(); 9433 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9434 T = CT->getElementType().getTypePtr(); 9435 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9436 T = AT->getValueType().getTypePtr(); 9437 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9438 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9439 9440 const BuiltinType *BT = cast<BuiltinType>(T); 9441 assert(BT->isInteger()); 9442 9443 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9444 } 9445 9446 /// Returns the supremum of two ranges: i.e. their conservative merge. 9447 static IntRange join(IntRange L, IntRange R) { 9448 return IntRange(std::max(L.Width, R.Width), 9449 L.NonNegative && R.NonNegative); 9450 } 9451 9452 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9453 static IntRange meet(IntRange L, IntRange R) { 9454 return IntRange(std::min(L.Width, R.Width), 9455 L.NonNegative || R.NonNegative); 9456 } 9457 }; 9458 9459 } // namespace 9460 9461 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9462 unsigned MaxWidth) { 9463 if (value.isSigned() && value.isNegative()) 9464 return IntRange(value.getMinSignedBits(), false); 9465 9466 if (value.getBitWidth() > MaxWidth) 9467 value = value.trunc(MaxWidth); 9468 9469 // isNonNegative() just checks the sign bit without considering 9470 // signedness. 9471 return IntRange(value.getActiveBits(), true); 9472 } 9473 9474 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9475 unsigned MaxWidth) { 9476 if (result.isInt()) 9477 return GetValueRange(C, result.getInt(), MaxWidth); 9478 9479 if (result.isVector()) { 9480 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9481 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9482 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9483 R = IntRange::join(R, El); 9484 } 9485 return R; 9486 } 9487 9488 if (result.isComplexInt()) { 9489 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9490 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9491 return IntRange::join(R, I); 9492 } 9493 9494 // This can happen with lossless casts to intptr_t of "based" lvalues. 9495 // Assume it might use arbitrary bits. 9496 // FIXME: The only reason we need to pass the type in here is to get 9497 // the sign right on this one case. It would be nice if APValue 9498 // preserved this. 9499 assert(result.isLValue() || result.isAddrLabelDiff()); 9500 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9501 } 9502 9503 static QualType GetExprType(const Expr *E) { 9504 QualType Ty = E->getType(); 9505 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9506 Ty = AtomicRHS->getValueType(); 9507 return Ty; 9508 } 9509 9510 /// Pseudo-evaluate the given integer expression, estimating the 9511 /// range of values it might take. 9512 /// 9513 /// \param MaxWidth - the width to which the value will be truncated 9514 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9515 E = E->IgnoreParens(); 9516 9517 // Try a full evaluation first. 9518 Expr::EvalResult result; 9519 if (E->EvaluateAsRValue(result, C)) 9520 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9521 9522 // I think we only want to look through implicit casts here; if the 9523 // user has an explicit widening cast, we should treat the value as 9524 // being of the new, wider type. 9525 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9526 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9527 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9528 9529 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9530 9531 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9532 CE->getCastKind() == CK_BooleanToSignedIntegral; 9533 9534 // Assume that non-integer casts can span the full range of the type. 9535 if (!isIntegerCast) 9536 return OutputTypeRange; 9537 9538 IntRange SubRange 9539 = GetExprRange(C, CE->getSubExpr(), 9540 std::min(MaxWidth, OutputTypeRange.Width)); 9541 9542 // Bail out if the subexpr's range is as wide as the cast type. 9543 if (SubRange.Width >= OutputTypeRange.Width) 9544 return OutputTypeRange; 9545 9546 // Otherwise, we take the smaller width, and we're non-negative if 9547 // either the output type or the subexpr is. 9548 return IntRange(SubRange.Width, 9549 SubRange.NonNegative || OutputTypeRange.NonNegative); 9550 } 9551 9552 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9553 // If we can fold the condition, just take that operand. 9554 bool CondResult; 9555 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9556 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9557 : CO->getFalseExpr(), 9558 MaxWidth); 9559 9560 // Otherwise, conservatively merge. 9561 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9562 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9563 return IntRange::join(L, R); 9564 } 9565 9566 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9567 switch (BO->getOpcode()) { 9568 case BO_Cmp: 9569 llvm_unreachable("builtin <=> should have class type"); 9570 9571 // Boolean-valued operations are single-bit and positive. 9572 case BO_LAnd: 9573 case BO_LOr: 9574 case BO_LT: 9575 case BO_GT: 9576 case BO_LE: 9577 case BO_GE: 9578 case BO_EQ: 9579 case BO_NE: 9580 return IntRange::forBoolType(); 9581 9582 // The type of the assignments is the type of the LHS, so the RHS 9583 // is not necessarily the same type. 9584 case BO_MulAssign: 9585 case BO_DivAssign: 9586 case BO_RemAssign: 9587 case BO_AddAssign: 9588 case BO_SubAssign: 9589 case BO_XorAssign: 9590 case BO_OrAssign: 9591 // TODO: bitfields? 9592 return IntRange::forValueOfType(C, GetExprType(E)); 9593 9594 // Simple assignments just pass through the RHS, which will have 9595 // been coerced to the LHS type. 9596 case BO_Assign: 9597 // TODO: bitfields? 9598 return GetExprRange(C, BO->getRHS(), MaxWidth); 9599 9600 // Operations with opaque sources are black-listed. 9601 case BO_PtrMemD: 9602 case BO_PtrMemI: 9603 return IntRange::forValueOfType(C, GetExprType(E)); 9604 9605 // Bitwise-and uses the *infinum* of the two source ranges. 9606 case BO_And: 9607 case BO_AndAssign: 9608 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9609 GetExprRange(C, BO->getRHS(), MaxWidth)); 9610 9611 // Left shift gets black-listed based on a judgement call. 9612 case BO_Shl: 9613 // ...except that we want to treat '1 << (blah)' as logically 9614 // positive. It's an important idiom. 9615 if (IntegerLiteral *I 9616 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9617 if (I->getValue() == 1) { 9618 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9619 return IntRange(R.Width, /*NonNegative*/ true); 9620 } 9621 } 9622 LLVM_FALLTHROUGH; 9623 9624 case BO_ShlAssign: 9625 return IntRange::forValueOfType(C, GetExprType(E)); 9626 9627 // Right shift by a constant can narrow its left argument. 9628 case BO_Shr: 9629 case BO_ShrAssign: { 9630 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9631 9632 // If the shift amount is a positive constant, drop the width by 9633 // that much. 9634 llvm::APSInt shift; 9635 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9636 shift.isNonNegative()) { 9637 unsigned zext = shift.getZExtValue(); 9638 if (zext >= L.Width) 9639 L.Width = (L.NonNegative ? 0 : 1); 9640 else 9641 L.Width -= zext; 9642 } 9643 9644 return L; 9645 } 9646 9647 // Comma acts as its right operand. 9648 case BO_Comma: 9649 return GetExprRange(C, BO->getRHS(), MaxWidth); 9650 9651 // Black-list pointer subtractions. 9652 case BO_Sub: 9653 if (BO->getLHS()->getType()->isPointerType()) 9654 return IntRange::forValueOfType(C, GetExprType(E)); 9655 break; 9656 9657 // The width of a division result is mostly determined by the size 9658 // of the LHS. 9659 case BO_Div: { 9660 // Don't 'pre-truncate' the operands. 9661 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9662 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9663 9664 // If the divisor is constant, use that. 9665 llvm::APSInt divisor; 9666 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9667 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9668 if (log2 >= L.Width) 9669 L.Width = (L.NonNegative ? 0 : 1); 9670 else 9671 L.Width = std::min(L.Width - log2, MaxWidth); 9672 return L; 9673 } 9674 9675 // Otherwise, just use the LHS's width. 9676 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9677 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9678 } 9679 9680 // The result of a remainder can't be larger than the result of 9681 // either side. 9682 case BO_Rem: { 9683 // Don't 'pre-truncate' the operands. 9684 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9685 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9686 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9687 9688 IntRange meet = IntRange::meet(L, R); 9689 meet.Width = std::min(meet.Width, MaxWidth); 9690 return meet; 9691 } 9692 9693 // The default behavior is okay for these. 9694 case BO_Mul: 9695 case BO_Add: 9696 case BO_Xor: 9697 case BO_Or: 9698 break; 9699 } 9700 9701 // The default case is to treat the operation as if it were closed 9702 // on the narrowest type that encompasses both operands. 9703 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9704 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9705 return IntRange::join(L, R); 9706 } 9707 9708 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9709 switch (UO->getOpcode()) { 9710 // Boolean-valued operations are white-listed. 9711 case UO_LNot: 9712 return IntRange::forBoolType(); 9713 9714 // Operations with opaque sources are black-listed. 9715 case UO_Deref: 9716 case UO_AddrOf: // should be impossible 9717 return IntRange::forValueOfType(C, GetExprType(E)); 9718 9719 default: 9720 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9721 } 9722 } 9723 9724 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9725 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9726 9727 if (const auto *BitField = E->getSourceBitField()) 9728 return IntRange(BitField->getBitWidthValue(C), 9729 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9730 9731 return IntRange::forValueOfType(C, GetExprType(E)); 9732 } 9733 9734 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9735 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9736 } 9737 9738 /// Checks whether the given value, which currently has the given 9739 /// source semantics, has the same value when coerced through the 9740 /// target semantics. 9741 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9742 const llvm::fltSemantics &Src, 9743 const llvm::fltSemantics &Tgt) { 9744 llvm::APFloat truncated = value; 9745 9746 bool ignored; 9747 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9748 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9749 9750 return truncated.bitwiseIsEqual(value); 9751 } 9752 9753 /// Checks whether the given value, which currently has the given 9754 /// source semantics, has the same value when coerced through the 9755 /// target semantics. 9756 /// 9757 /// The value might be a vector of floats (or a complex number). 9758 static bool IsSameFloatAfterCast(const APValue &value, 9759 const llvm::fltSemantics &Src, 9760 const llvm::fltSemantics &Tgt) { 9761 if (value.isFloat()) 9762 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9763 9764 if (value.isVector()) { 9765 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9766 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9767 return false; 9768 return true; 9769 } 9770 9771 assert(value.isComplexFloat()); 9772 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 9773 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 9774 } 9775 9776 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 9777 9778 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 9779 // Suppress cases where we are comparing against an enum constant. 9780 if (const DeclRefExpr *DR = 9781 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 9782 if (isa<EnumConstantDecl>(DR->getDecl())) 9783 return true; 9784 9785 // Suppress cases where the '0' value is expanded from a macro. 9786 if (E->getBeginLoc().isMacroID()) 9787 return true; 9788 9789 return false; 9790 } 9791 9792 static bool isKnownToHaveUnsignedValue(Expr *E) { 9793 return E->getType()->isIntegerType() && 9794 (!E->getType()->isSignedIntegerType() || 9795 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 9796 } 9797 9798 namespace { 9799 /// The promoted range of values of a type. In general this has the 9800 /// following structure: 9801 /// 9802 /// |-----------| . . . |-----------| 9803 /// ^ ^ ^ ^ 9804 /// Min HoleMin HoleMax Max 9805 /// 9806 /// ... where there is only a hole if a signed type is promoted to unsigned 9807 /// (in which case Min and Max are the smallest and largest representable 9808 /// values). 9809 struct PromotedRange { 9810 // Min, or HoleMax if there is a hole. 9811 llvm::APSInt PromotedMin; 9812 // Max, or HoleMin if there is a hole. 9813 llvm::APSInt PromotedMax; 9814 9815 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 9816 if (R.Width == 0) 9817 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 9818 else if (R.Width >= BitWidth && !Unsigned) { 9819 // Promotion made the type *narrower*. This happens when promoting 9820 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 9821 // Treat all values of 'signed int' as being in range for now. 9822 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 9823 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 9824 } else { 9825 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 9826 .extOrTrunc(BitWidth); 9827 PromotedMin.setIsUnsigned(Unsigned); 9828 9829 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 9830 .extOrTrunc(BitWidth); 9831 PromotedMax.setIsUnsigned(Unsigned); 9832 } 9833 } 9834 9835 // Determine whether this range is contiguous (has no hole). 9836 bool isContiguous() const { return PromotedMin <= PromotedMax; } 9837 9838 // Where a constant value is within the range. 9839 enum ComparisonResult { 9840 LT = 0x1, 9841 LE = 0x2, 9842 GT = 0x4, 9843 GE = 0x8, 9844 EQ = 0x10, 9845 NE = 0x20, 9846 InRangeFlag = 0x40, 9847 9848 Less = LE | LT | NE, 9849 Min = LE | InRangeFlag, 9850 InRange = InRangeFlag, 9851 Max = GE | InRangeFlag, 9852 Greater = GE | GT | NE, 9853 9854 OnlyValue = LE | GE | EQ | InRangeFlag, 9855 InHole = NE 9856 }; 9857 9858 ComparisonResult compare(const llvm::APSInt &Value) const { 9859 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 9860 Value.isUnsigned() == PromotedMin.isUnsigned()); 9861 if (!isContiguous()) { 9862 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 9863 if (Value.isMinValue()) return Min; 9864 if (Value.isMaxValue()) return Max; 9865 if (Value >= PromotedMin) return InRange; 9866 if (Value <= PromotedMax) return InRange; 9867 return InHole; 9868 } 9869 9870 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 9871 case -1: return Less; 9872 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 9873 case 1: 9874 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 9875 case -1: return InRange; 9876 case 0: return Max; 9877 case 1: return Greater; 9878 } 9879 } 9880 9881 llvm_unreachable("impossible compare result"); 9882 } 9883 9884 static llvm::Optional<StringRef> 9885 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 9886 if (Op == BO_Cmp) { 9887 ComparisonResult LTFlag = LT, GTFlag = GT; 9888 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 9889 9890 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 9891 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 9892 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 9893 return llvm::None; 9894 } 9895 9896 ComparisonResult TrueFlag, FalseFlag; 9897 if (Op == BO_EQ) { 9898 TrueFlag = EQ; 9899 FalseFlag = NE; 9900 } else if (Op == BO_NE) { 9901 TrueFlag = NE; 9902 FalseFlag = EQ; 9903 } else { 9904 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 9905 TrueFlag = LT; 9906 FalseFlag = GE; 9907 } else { 9908 TrueFlag = GT; 9909 FalseFlag = LE; 9910 } 9911 if (Op == BO_GE || Op == BO_LE) 9912 std::swap(TrueFlag, FalseFlag); 9913 } 9914 if (R & TrueFlag) 9915 return StringRef("true"); 9916 if (R & FalseFlag) 9917 return StringRef("false"); 9918 return llvm::None; 9919 } 9920 }; 9921 } 9922 9923 static bool HasEnumType(Expr *E) { 9924 // Strip off implicit integral promotions. 9925 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9926 if (ICE->getCastKind() != CK_IntegralCast && 9927 ICE->getCastKind() != CK_NoOp) 9928 break; 9929 E = ICE->getSubExpr(); 9930 } 9931 9932 return E->getType()->isEnumeralType(); 9933 } 9934 9935 static int classifyConstantValue(Expr *Constant) { 9936 // The values of this enumeration are used in the diagnostics 9937 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 9938 enum ConstantValueKind { 9939 Miscellaneous = 0, 9940 LiteralTrue, 9941 LiteralFalse 9942 }; 9943 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 9944 return BL->getValue() ? ConstantValueKind::LiteralTrue 9945 : ConstantValueKind::LiteralFalse; 9946 return ConstantValueKind::Miscellaneous; 9947 } 9948 9949 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 9950 Expr *Constant, Expr *Other, 9951 const llvm::APSInt &Value, 9952 bool RhsConstant) { 9953 if (S.inTemplateInstantiation()) 9954 return false; 9955 9956 Expr *OriginalOther = Other; 9957 9958 Constant = Constant->IgnoreParenImpCasts(); 9959 Other = Other->IgnoreParenImpCasts(); 9960 9961 // Suppress warnings on tautological comparisons between values of the same 9962 // enumeration type. There are only two ways we could warn on this: 9963 // - If the constant is outside the range of representable values of 9964 // the enumeration. In such a case, we should warn about the cast 9965 // to enumeration type, not about the comparison. 9966 // - If the constant is the maximum / minimum in-range value. For an 9967 // enumeratin type, such comparisons can be meaningful and useful. 9968 if (Constant->getType()->isEnumeralType() && 9969 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 9970 return false; 9971 9972 // TODO: Investigate using GetExprRange() to get tighter bounds 9973 // on the bit ranges. 9974 QualType OtherT = Other->getType(); 9975 if (const auto *AT = OtherT->getAs<AtomicType>()) 9976 OtherT = AT->getValueType(); 9977 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 9978 9979 // Whether we're treating Other as being a bool because of the form of 9980 // expression despite it having another type (typically 'int' in C). 9981 bool OtherIsBooleanDespiteType = 9982 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 9983 if (OtherIsBooleanDespiteType) 9984 OtherRange = IntRange::forBoolType(); 9985 9986 // Determine the promoted range of the other type and see if a comparison of 9987 // the constant against that range is tautological. 9988 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 9989 Value.isUnsigned()); 9990 auto Cmp = OtherPromotedRange.compare(Value); 9991 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 9992 if (!Result) 9993 return false; 9994 9995 // Suppress the diagnostic for an in-range comparison if the constant comes 9996 // from a macro or enumerator. We don't want to diagnose 9997 // 9998 // some_long_value <= INT_MAX 9999 // 10000 // when sizeof(int) == sizeof(long). 10001 bool InRange = Cmp & PromotedRange::InRangeFlag; 10002 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10003 return false; 10004 10005 // If this is a comparison to an enum constant, include that 10006 // constant in the diagnostic. 10007 const EnumConstantDecl *ED = nullptr; 10008 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10009 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10010 10011 // Should be enough for uint128 (39 decimal digits) 10012 SmallString<64> PrettySourceValue; 10013 llvm::raw_svector_ostream OS(PrettySourceValue); 10014 if (ED) 10015 OS << '\'' << *ED << "' (" << Value << ")"; 10016 else 10017 OS << Value; 10018 10019 // FIXME: We use a somewhat different formatting for the in-range cases and 10020 // cases involving boolean values for historical reasons. We should pick a 10021 // consistent way of presenting these diagnostics. 10022 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10023 S.DiagRuntimeBehavior( 10024 E->getOperatorLoc(), E, 10025 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10026 : diag::warn_tautological_bool_compare) 10027 << OS.str() << classifyConstantValue(Constant) 10028 << OtherT << OtherIsBooleanDespiteType << *Result 10029 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10030 } else { 10031 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10032 ? (HasEnumType(OriginalOther) 10033 ? diag::warn_unsigned_enum_always_true_comparison 10034 : diag::warn_unsigned_always_true_comparison) 10035 : diag::warn_tautological_constant_compare; 10036 10037 S.Diag(E->getOperatorLoc(), Diag) 10038 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10039 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10040 } 10041 10042 return true; 10043 } 10044 10045 /// Analyze the operands of the given comparison. Implements the 10046 /// fallback case from AnalyzeComparison. 10047 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10048 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10049 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10050 } 10051 10052 /// Implements -Wsign-compare. 10053 /// 10054 /// \param E the binary operator to check for warnings 10055 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10056 // The type the comparison is being performed in. 10057 QualType T = E->getLHS()->getType(); 10058 10059 // Only analyze comparison operators where both sides have been converted to 10060 // the same type. 10061 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10062 return AnalyzeImpConvsInComparison(S, E); 10063 10064 // Don't analyze value-dependent comparisons directly. 10065 if (E->isValueDependent()) 10066 return AnalyzeImpConvsInComparison(S, E); 10067 10068 Expr *LHS = E->getLHS(); 10069 Expr *RHS = E->getRHS(); 10070 10071 if (T->isIntegralType(S.Context)) { 10072 llvm::APSInt RHSValue; 10073 llvm::APSInt LHSValue; 10074 10075 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10076 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10077 10078 // We don't care about expressions whose result is a constant. 10079 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10080 return AnalyzeImpConvsInComparison(S, E); 10081 10082 // We only care about expressions where just one side is literal 10083 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10084 // Is the constant on the RHS or LHS? 10085 const bool RhsConstant = IsRHSIntegralLiteral; 10086 Expr *Const = RhsConstant ? RHS : LHS; 10087 Expr *Other = RhsConstant ? LHS : RHS; 10088 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10089 10090 // Check whether an integer constant comparison results in a value 10091 // of 'true' or 'false'. 10092 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10093 return AnalyzeImpConvsInComparison(S, E); 10094 } 10095 } 10096 10097 if (!T->hasUnsignedIntegerRepresentation()) { 10098 // We don't do anything special if this isn't an unsigned integral 10099 // comparison: we're only interested in integral comparisons, and 10100 // signed comparisons only happen in cases we don't care to warn about. 10101 return AnalyzeImpConvsInComparison(S, E); 10102 } 10103 10104 LHS = LHS->IgnoreParenImpCasts(); 10105 RHS = RHS->IgnoreParenImpCasts(); 10106 10107 if (!S.getLangOpts().CPlusPlus) { 10108 // Avoid warning about comparison of integers with different signs when 10109 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10110 // the type of `E`. 10111 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10112 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10113 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10114 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10115 } 10116 10117 // Check to see if one of the (unmodified) operands is of different 10118 // signedness. 10119 Expr *signedOperand, *unsignedOperand; 10120 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10121 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10122 "unsigned comparison between two signed integer expressions?"); 10123 signedOperand = LHS; 10124 unsignedOperand = RHS; 10125 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10126 signedOperand = RHS; 10127 unsignedOperand = LHS; 10128 } else { 10129 return AnalyzeImpConvsInComparison(S, E); 10130 } 10131 10132 // Otherwise, calculate the effective range of the signed operand. 10133 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10134 10135 // Go ahead and analyze implicit conversions in the operands. Note 10136 // that we skip the implicit conversions on both sides. 10137 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10138 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10139 10140 // If the signed range is non-negative, -Wsign-compare won't fire. 10141 if (signedRange.NonNegative) 10142 return; 10143 10144 // For (in)equality comparisons, if the unsigned operand is a 10145 // constant which cannot collide with a overflowed signed operand, 10146 // then reinterpreting the signed operand as unsigned will not 10147 // change the result of the comparison. 10148 if (E->isEqualityOp()) { 10149 unsigned comparisonWidth = S.Context.getIntWidth(T); 10150 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10151 10152 // We should never be unable to prove that the unsigned operand is 10153 // non-negative. 10154 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10155 10156 if (unsignedRange.Width < comparisonWidth) 10157 return; 10158 } 10159 10160 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10161 S.PDiag(diag::warn_mixed_sign_comparison) 10162 << LHS->getType() << RHS->getType() 10163 << LHS->getSourceRange() << RHS->getSourceRange()); 10164 } 10165 10166 /// Analyzes an attempt to assign the given value to a bitfield. 10167 /// 10168 /// Returns true if there was something fishy about the attempt. 10169 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10170 SourceLocation InitLoc) { 10171 assert(Bitfield->isBitField()); 10172 if (Bitfield->isInvalidDecl()) 10173 return false; 10174 10175 // White-list bool bitfields. 10176 QualType BitfieldType = Bitfield->getType(); 10177 if (BitfieldType->isBooleanType()) 10178 return false; 10179 10180 if (BitfieldType->isEnumeralType()) { 10181 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10182 // If the underlying enum type was not explicitly specified as an unsigned 10183 // type and the enum contain only positive values, MSVC++ will cause an 10184 // inconsistency by storing this as a signed type. 10185 if (S.getLangOpts().CPlusPlus11 && 10186 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10187 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10188 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10189 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10190 << BitfieldEnumDecl->getNameAsString(); 10191 } 10192 } 10193 10194 if (Bitfield->getType()->isBooleanType()) 10195 return false; 10196 10197 // Ignore value- or type-dependent expressions. 10198 if (Bitfield->getBitWidth()->isValueDependent() || 10199 Bitfield->getBitWidth()->isTypeDependent() || 10200 Init->isValueDependent() || 10201 Init->isTypeDependent()) 10202 return false; 10203 10204 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10205 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10206 10207 llvm::APSInt Value; 10208 if (!OriginalInit->EvaluateAsInt(Value, S.Context, 10209 Expr::SE_AllowSideEffects)) { 10210 // The RHS is not constant. If the RHS has an enum type, make sure the 10211 // bitfield is wide enough to hold all the values of the enum without 10212 // truncation. 10213 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10214 EnumDecl *ED = EnumTy->getDecl(); 10215 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10216 10217 // Enum types are implicitly signed on Windows, so check if there are any 10218 // negative enumerators to see if the enum was intended to be signed or 10219 // not. 10220 bool SignedEnum = ED->getNumNegativeBits() > 0; 10221 10222 // Check for surprising sign changes when assigning enum values to a 10223 // bitfield of different signedness. If the bitfield is signed and we 10224 // have exactly the right number of bits to store this unsigned enum, 10225 // suggest changing the enum to an unsigned type. This typically happens 10226 // on Windows where unfixed enums always use an underlying type of 'int'. 10227 unsigned DiagID = 0; 10228 if (SignedEnum && !SignedBitfield) { 10229 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10230 } else if (SignedBitfield && !SignedEnum && 10231 ED->getNumPositiveBits() == FieldWidth) { 10232 DiagID = diag::warn_signed_bitfield_enum_conversion; 10233 } 10234 10235 if (DiagID) { 10236 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10237 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10238 SourceRange TypeRange = 10239 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10240 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10241 << SignedEnum << TypeRange; 10242 } 10243 10244 // Compute the required bitwidth. If the enum has negative values, we need 10245 // one more bit than the normal number of positive bits to represent the 10246 // sign bit. 10247 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10248 ED->getNumNegativeBits()) 10249 : ED->getNumPositiveBits(); 10250 10251 // Check the bitwidth. 10252 if (BitsNeeded > FieldWidth) { 10253 Expr *WidthExpr = Bitfield->getBitWidth(); 10254 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10255 << Bitfield << ED; 10256 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10257 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10258 } 10259 } 10260 10261 return false; 10262 } 10263 10264 unsigned OriginalWidth = Value.getBitWidth(); 10265 10266 if (!Value.isSigned() || Value.isNegative()) 10267 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10268 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10269 OriginalWidth = Value.getMinSignedBits(); 10270 10271 if (OriginalWidth <= FieldWidth) 10272 return false; 10273 10274 // Compute the value which the bitfield will contain. 10275 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10276 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10277 10278 // Check whether the stored value is equal to the original value. 10279 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10280 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10281 return false; 10282 10283 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10284 // therefore don't strictly fit into a signed bitfield of width 1. 10285 if (FieldWidth == 1 && Value == 1) 10286 return false; 10287 10288 std::string PrettyValue = Value.toString(10); 10289 std::string PrettyTrunc = TruncatedValue.toString(10); 10290 10291 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10292 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10293 << Init->getSourceRange(); 10294 10295 return true; 10296 } 10297 10298 /// Analyze the given simple or compound assignment for warning-worthy 10299 /// operations. 10300 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10301 // Just recurse on the LHS. 10302 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10303 10304 // We want to recurse on the RHS as normal unless we're assigning to 10305 // a bitfield. 10306 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10307 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10308 E->getOperatorLoc())) { 10309 // Recurse, ignoring any implicit conversions on the RHS. 10310 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10311 E->getOperatorLoc()); 10312 } 10313 } 10314 10315 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10316 10317 // Diagnose implicitly sequentially-consistent atomic assignment. 10318 if (E->getLHS()->getType()->isAtomicType()) 10319 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10320 } 10321 10322 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10323 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10324 SourceLocation CContext, unsigned diag, 10325 bool pruneControlFlow = false) { 10326 if (pruneControlFlow) { 10327 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10328 S.PDiag(diag) 10329 << SourceType << T << E->getSourceRange() 10330 << SourceRange(CContext)); 10331 return; 10332 } 10333 S.Diag(E->getExprLoc(), diag) 10334 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10335 } 10336 10337 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10338 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10339 SourceLocation CContext, 10340 unsigned diag, bool pruneControlFlow = false) { 10341 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10342 } 10343 10344 /// Diagnose an implicit cast from a floating point value to an integer value. 10345 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10346 SourceLocation CContext) { 10347 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10348 const bool PruneWarnings = S.inTemplateInstantiation(); 10349 10350 Expr *InnerE = E->IgnoreParenImpCasts(); 10351 // We also want to warn on, e.g., "int i = -1.234" 10352 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10353 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10354 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10355 10356 const bool IsLiteral = 10357 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10358 10359 llvm::APFloat Value(0.0); 10360 bool IsConstant = 10361 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10362 if (!IsConstant) { 10363 return DiagnoseImpCast(S, E, T, CContext, 10364 diag::warn_impcast_float_integer, PruneWarnings); 10365 } 10366 10367 bool isExact = false; 10368 10369 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10370 T->hasUnsignedIntegerRepresentation()); 10371 llvm::APFloat::opStatus Result = Value.convertToInteger( 10372 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10373 10374 if (Result == llvm::APFloat::opOK && isExact) { 10375 if (IsLiteral) return; 10376 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10377 PruneWarnings); 10378 } 10379 10380 // Conversion of a floating-point value to a non-bool integer where the 10381 // integral part cannot be represented by the integer type is undefined. 10382 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10383 return DiagnoseImpCast( 10384 S, E, T, CContext, 10385 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10386 : diag::warn_impcast_float_to_integer_out_of_range, 10387 PruneWarnings); 10388 10389 unsigned DiagID = 0; 10390 if (IsLiteral) { 10391 // Warn on floating point literal to integer. 10392 DiagID = diag::warn_impcast_literal_float_to_integer; 10393 } else if (IntegerValue == 0) { 10394 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10395 return DiagnoseImpCast(S, E, T, CContext, 10396 diag::warn_impcast_float_integer, PruneWarnings); 10397 } 10398 // Warn on non-zero to zero conversion. 10399 DiagID = diag::warn_impcast_float_to_integer_zero; 10400 } else { 10401 if (IntegerValue.isUnsigned()) { 10402 if (!IntegerValue.isMaxValue()) { 10403 return DiagnoseImpCast(S, E, T, CContext, 10404 diag::warn_impcast_float_integer, PruneWarnings); 10405 } 10406 } else { // IntegerValue.isSigned() 10407 if (!IntegerValue.isMaxSignedValue() && 10408 !IntegerValue.isMinSignedValue()) { 10409 return DiagnoseImpCast(S, E, T, CContext, 10410 diag::warn_impcast_float_integer, PruneWarnings); 10411 } 10412 } 10413 // Warn on evaluatable floating point expression to integer conversion. 10414 DiagID = diag::warn_impcast_float_to_integer; 10415 } 10416 10417 // FIXME: Force the precision of the source value down so we don't print 10418 // digits which are usually useless (we don't really care here if we 10419 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10420 // would automatically print the shortest representation, but it's a bit 10421 // tricky to implement. 10422 SmallString<16> PrettySourceValue; 10423 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10424 precision = (precision * 59 + 195) / 196; 10425 Value.toString(PrettySourceValue, precision); 10426 10427 SmallString<16> PrettyTargetValue; 10428 if (IsBool) 10429 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10430 else 10431 IntegerValue.toString(PrettyTargetValue); 10432 10433 if (PruneWarnings) { 10434 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10435 S.PDiag(DiagID) 10436 << E->getType() << T.getUnqualifiedType() 10437 << PrettySourceValue << PrettyTargetValue 10438 << E->getSourceRange() << SourceRange(CContext)); 10439 } else { 10440 S.Diag(E->getExprLoc(), DiagID) 10441 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10442 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10443 } 10444 } 10445 10446 /// Analyze the given compound assignment for the possible losing of 10447 /// floating-point precision. 10448 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10449 assert(isa<CompoundAssignOperator>(E) && 10450 "Must be compound assignment operation"); 10451 // Recurse on the LHS and RHS in here 10452 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10453 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10454 10455 if (E->getLHS()->getType()->isAtomicType()) 10456 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10457 10458 // Now check the outermost expression 10459 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10460 const auto *RBT = cast<CompoundAssignOperator>(E) 10461 ->getComputationResultType() 10462 ->getAs<BuiltinType>(); 10463 10464 // The below checks assume source is floating point. 10465 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10466 10467 // If source is floating point but target is not. 10468 if (!ResultBT->isFloatingPoint()) 10469 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(), 10470 E->getExprLoc()); 10471 10472 // If both source and target are floating points. 10473 // Builtin FP kinds are ordered by increasing FP rank. 10474 if (ResultBT->getKind() < RBT->getKind() && 10475 // We don't want to warn for system macro. 10476 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10477 // warn about dropping FP rank. 10478 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10479 diag::warn_impcast_float_result_precision); 10480 } 10481 10482 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10483 IntRange Range) { 10484 if (!Range.Width) return "0"; 10485 10486 llvm::APSInt ValueInRange = Value; 10487 ValueInRange.setIsSigned(!Range.NonNegative); 10488 ValueInRange = ValueInRange.trunc(Range.Width); 10489 return ValueInRange.toString(10); 10490 } 10491 10492 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10493 if (!isa<ImplicitCastExpr>(Ex)) 10494 return false; 10495 10496 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10497 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10498 const Type *Source = 10499 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10500 if (Target->isDependentType()) 10501 return false; 10502 10503 const BuiltinType *FloatCandidateBT = 10504 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10505 const Type *BoolCandidateType = ToBool ? Target : Source; 10506 10507 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10508 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10509 } 10510 10511 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10512 SourceLocation CC) { 10513 unsigned NumArgs = TheCall->getNumArgs(); 10514 for (unsigned i = 0; i < NumArgs; ++i) { 10515 Expr *CurrA = TheCall->getArg(i); 10516 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10517 continue; 10518 10519 bool IsSwapped = ((i > 0) && 10520 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10521 IsSwapped |= ((i < (NumArgs - 1)) && 10522 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10523 if (IsSwapped) { 10524 // Warn on this floating-point to bool conversion. 10525 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10526 CurrA->getType(), CC, 10527 diag::warn_impcast_floating_point_to_bool); 10528 } 10529 } 10530 } 10531 10532 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10533 SourceLocation CC) { 10534 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10535 E->getExprLoc())) 10536 return; 10537 10538 // Don't warn on functions which have return type nullptr_t. 10539 if (isa<CallExpr>(E)) 10540 return; 10541 10542 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10543 const Expr::NullPointerConstantKind NullKind = 10544 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10545 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10546 return; 10547 10548 // Return if target type is a safe conversion. 10549 if (T->isAnyPointerType() || T->isBlockPointerType() || 10550 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10551 return; 10552 10553 SourceLocation Loc = E->getSourceRange().getBegin(); 10554 10555 // Venture through the macro stacks to get to the source of macro arguments. 10556 // The new location is a better location than the complete location that was 10557 // passed in. 10558 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10559 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10560 10561 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10562 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10563 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10564 Loc, S.SourceMgr, S.getLangOpts()); 10565 if (MacroName == "NULL") 10566 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10567 } 10568 10569 // Only warn if the null and context location are in the same macro expansion. 10570 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10571 return; 10572 10573 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10574 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10575 << FixItHint::CreateReplacement(Loc, 10576 S.getFixItZeroLiteralForType(T, Loc)); 10577 } 10578 10579 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10580 ObjCArrayLiteral *ArrayLiteral); 10581 10582 static void 10583 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10584 ObjCDictionaryLiteral *DictionaryLiteral); 10585 10586 /// Check a single element within a collection literal against the 10587 /// target element type. 10588 static void checkObjCCollectionLiteralElement(Sema &S, 10589 QualType TargetElementType, 10590 Expr *Element, 10591 unsigned ElementKind) { 10592 // Skip a bitcast to 'id' or qualified 'id'. 10593 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10594 if (ICE->getCastKind() == CK_BitCast && 10595 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10596 Element = ICE->getSubExpr(); 10597 } 10598 10599 QualType ElementType = Element->getType(); 10600 ExprResult ElementResult(Element); 10601 if (ElementType->getAs<ObjCObjectPointerType>() && 10602 S.CheckSingleAssignmentConstraints(TargetElementType, 10603 ElementResult, 10604 false, false) 10605 != Sema::Compatible) { 10606 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10607 << ElementType << ElementKind << TargetElementType 10608 << Element->getSourceRange(); 10609 } 10610 10611 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10612 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10613 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10614 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10615 } 10616 10617 /// Check an Objective-C array literal being converted to the given 10618 /// target type. 10619 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10620 ObjCArrayLiteral *ArrayLiteral) { 10621 if (!S.NSArrayDecl) 10622 return; 10623 10624 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10625 if (!TargetObjCPtr) 10626 return; 10627 10628 if (TargetObjCPtr->isUnspecialized() || 10629 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10630 != S.NSArrayDecl->getCanonicalDecl()) 10631 return; 10632 10633 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10634 if (TypeArgs.size() != 1) 10635 return; 10636 10637 QualType TargetElementType = TypeArgs[0]; 10638 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10639 checkObjCCollectionLiteralElement(S, TargetElementType, 10640 ArrayLiteral->getElement(I), 10641 0); 10642 } 10643 } 10644 10645 /// Check an Objective-C dictionary literal being converted to the given 10646 /// target type. 10647 static void 10648 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10649 ObjCDictionaryLiteral *DictionaryLiteral) { 10650 if (!S.NSDictionaryDecl) 10651 return; 10652 10653 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10654 if (!TargetObjCPtr) 10655 return; 10656 10657 if (TargetObjCPtr->isUnspecialized() || 10658 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10659 != S.NSDictionaryDecl->getCanonicalDecl()) 10660 return; 10661 10662 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10663 if (TypeArgs.size() != 2) 10664 return; 10665 10666 QualType TargetKeyType = TypeArgs[0]; 10667 QualType TargetObjectType = TypeArgs[1]; 10668 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10669 auto Element = DictionaryLiteral->getKeyValueElement(I); 10670 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10671 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10672 } 10673 } 10674 10675 // Helper function to filter out cases for constant width constant conversion. 10676 // Don't warn on char array initialization or for non-decimal values. 10677 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10678 SourceLocation CC) { 10679 // If initializing from a constant, and the constant starts with '0', 10680 // then it is a binary, octal, or hexadecimal. Allow these constants 10681 // to fill all the bits, even if there is a sign change. 10682 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10683 const char FirstLiteralCharacter = 10684 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10685 if (FirstLiteralCharacter == '0') 10686 return false; 10687 } 10688 10689 // If the CC location points to a '{', and the type is char, then assume 10690 // assume it is an array initialization. 10691 if (CC.isValid() && T->isCharType()) { 10692 const char FirstContextCharacter = 10693 S.getSourceManager().getCharacterData(CC)[0]; 10694 if (FirstContextCharacter == '{') 10695 return false; 10696 } 10697 10698 return true; 10699 } 10700 10701 static void 10702 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10703 bool *ICContext = nullptr) { 10704 if (E->isTypeDependent() || E->isValueDependent()) return; 10705 10706 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10707 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10708 if (Source == Target) return; 10709 if (Target->isDependentType()) return; 10710 10711 // If the conversion context location is invalid don't complain. We also 10712 // don't want to emit a warning if the issue occurs from the expansion of 10713 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10714 // delay this check as long as possible. Once we detect we are in that 10715 // scenario, we just return. 10716 if (CC.isInvalid()) 10717 return; 10718 10719 if (Source->isAtomicType()) 10720 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 10721 10722 // Diagnose implicit casts to bool. 10723 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10724 if (isa<StringLiteral>(E)) 10725 // Warn on string literal to bool. Checks for string literals in logical 10726 // and expressions, for instance, assert(0 && "error here"), are 10727 // prevented by a check in AnalyzeImplicitConversions(). 10728 return DiagnoseImpCast(S, E, T, CC, 10729 diag::warn_impcast_string_literal_to_bool); 10730 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10731 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10732 // This covers the literal expressions that evaluate to Objective-C 10733 // objects. 10734 return DiagnoseImpCast(S, E, T, CC, 10735 diag::warn_impcast_objective_c_literal_to_bool); 10736 } 10737 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10738 // Warn on pointer to bool conversion that is always true. 10739 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10740 SourceRange(CC)); 10741 } 10742 } 10743 10744 // Check implicit casts from Objective-C collection literals to specialized 10745 // collection types, e.g., NSArray<NSString *> *. 10746 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10747 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10748 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10749 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10750 10751 // Strip vector types. 10752 if (isa<VectorType>(Source)) { 10753 if (!isa<VectorType>(Target)) { 10754 if (S.SourceMgr.isInSystemMacro(CC)) 10755 return; 10756 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10757 } 10758 10759 // If the vector cast is cast between two vectors of the same size, it is 10760 // a bitcast, not a conversion. 10761 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10762 return; 10763 10764 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 10765 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 10766 } 10767 if (auto VecTy = dyn_cast<VectorType>(Target)) 10768 Target = VecTy->getElementType().getTypePtr(); 10769 10770 // Strip complex types. 10771 if (isa<ComplexType>(Source)) { 10772 if (!isa<ComplexType>(Target)) { 10773 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 10774 return; 10775 10776 return DiagnoseImpCast(S, E, T, CC, 10777 S.getLangOpts().CPlusPlus 10778 ? diag::err_impcast_complex_scalar 10779 : diag::warn_impcast_complex_scalar); 10780 } 10781 10782 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 10783 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 10784 } 10785 10786 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 10787 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 10788 10789 // If the source is floating point... 10790 if (SourceBT && SourceBT->isFloatingPoint()) { 10791 // ...and the target is floating point... 10792 if (TargetBT && TargetBT->isFloatingPoint()) { 10793 // ...then warn if we're dropping FP rank. 10794 10795 // Builtin FP kinds are ordered by increasing FP rank. 10796 if (SourceBT->getKind() > TargetBT->getKind()) { 10797 // Don't warn about float constants that are precisely 10798 // representable in the target type. 10799 Expr::EvalResult result; 10800 if (E->EvaluateAsRValue(result, S.Context)) { 10801 // Value might be a float, a float vector, or a float complex. 10802 if (IsSameFloatAfterCast(result.Val, 10803 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 10804 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 10805 return; 10806 } 10807 10808 if (S.SourceMgr.isInSystemMacro(CC)) 10809 return; 10810 10811 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 10812 } 10813 // ... or possibly if we're increasing rank, too 10814 else if (TargetBT->getKind() > SourceBT->getKind()) { 10815 if (S.SourceMgr.isInSystemMacro(CC)) 10816 return; 10817 10818 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 10819 } 10820 return; 10821 } 10822 10823 // If the target is integral, always warn. 10824 if (TargetBT && TargetBT->isInteger()) { 10825 if (S.SourceMgr.isInSystemMacro(CC)) 10826 return; 10827 10828 DiagnoseFloatingImpCast(S, E, T, CC); 10829 } 10830 10831 // Detect the case where a call result is converted from floating-point to 10832 // to bool, and the final argument to the call is converted from bool, to 10833 // discover this typo: 10834 // 10835 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 10836 // 10837 // FIXME: This is an incredibly special case; is there some more general 10838 // way to detect this class of misplaced-parentheses bug? 10839 if (Target->isBooleanType() && isa<CallExpr>(E)) { 10840 // Check last argument of function call to see if it is an 10841 // implicit cast from a type matching the type the result 10842 // is being cast to. 10843 CallExpr *CEx = cast<CallExpr>(E); 10844 if (unsigned NumArgs = CEx->getNumArgs()) { 10845 Expr *LastA = CEx->getArg(NumArgs - 1); 10846 Expr *InnerE = LastA->IgnoreParenImpCasts(); 10847 if (isa<ImplicitCastExpr>(LastA) && 10848 InnerE->getType()->isBooleanType()) { 10849 // Warn on this floating-point to bool conversion 10850 DiagnoseImpCast(S, E, T, CC, 10851 diag::warn_impcast_floating_point_to_bool); 10852 } 10853 } 10854 } 10855 return; 10856 } 10857 10858 DiagnoseNullConversion(S, E, T, CC); 10859 10860 S.DiscardMisalignedMemberAddress(Target, E); 10861 10862 if (!Source->isIntegerType() || !Target->isIntegerType()) 10863 return; 10864 10865 // TODO: remove this early return once the false positives for constant->bool 10866 // in templates, macros, etc, are reduced or removed. 10867 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 10868 return; 10869 10870 IntRange SourceRange = GetExprRange(S.Context, E); 10871 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 10872 10873 if (SourceRange.Width > TargetRange.Width) { 10874 // If the source is a constant, use a default-on diagnostic. 10875 // TODO: this should happen for bitfield stores, too. 10876 llvm::APSInt Value(32); 10877 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) { 10878 if (S.SourceMgr.isInSystemMacro(CC)) 10879 return; 10880 10881 std::string PrettySourceValue = Value.toString(10); 10882 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10883 10884 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10885 S.PDiag(diag::warn_impcast_integer_precision_constant) 10886 << PrettySourceValue << PrettyTargetValue 10887 << E->getType() << T << E->getSourceRange() 10888 << clang::SourceRange(CC)); 10889 return; 10890 } 10891 10892 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 10893 if (S.SourceMgr.isInSystemMacro(CC)) 10894 return; 10895 10896 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 10897 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 10898 /* pruneControlFlow */ true); 10899 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 10900 } 10901 10902 if (TargetRange.Width > SourceRange.Width) { 10903 if (auto *UO = dyn_cast<UnaryOperator>(E)) 10904 if (UO->getOpcode() == UO_Minus) 10905 if (Source->isUnsignedIntegerType()) { 10906 if (Target->isUnsignedIntegerType()) 10907 return DiagnoseImpCast(S, E, T, CC, 10908 diag::warn_impcast_high_order_zero_bits); 10909 if (Target->isSignedIntegerType()) 10910 return DiagnoseImpCast(S, E, T, CC, 10911 diag::warn_impcast_nonnegative_result); 10912 } 10913 } 10914 10915 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 10916 SourceRange.NonNegative && Source->isSignedIntegerType()) { 10917 // Warn when doing a signed to signed conversion, warn if the positive 10918 // source value is exactly the width of the target type, which will 10919 // cause a negative value to be stored. 10920 10921 llvm::APSInt Value; 10922 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) && 10923 !S.SourceMgr.isInSystemMacro(CC)) { 10924 if (isSameWidthConstantConversion(S, E, T, CC)) { 10925 std::string PrettySourceValue = Value.toString(10); 10926 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 10927 10928 S.DiagRuntimeBehavior( 10929 E->getExprLoc(), E, 10930 S.PDiag(diag::warn_impcast_integer_precision_constant) 10931 << PrettySourceValue << PrettyTargetValue << E->getType() << T 10932 << E->getSourceRange() << clang::SourceRange(CC)); 10933 return; 10934 } 10935 } 10936 10937 // Fall through for non-constants to give a sign conversion warning. 10938 } 10939 10940 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 10941 (!TargetRange.NonNegative && SourceRange.NonNegative && 10942 SourceRange.Width == TargetRange.Width)) { 10943 if (S.SourceMgr.isInSystemMacro(CC)) 10944 return; 10945 10946 unsigned DiagID = diag::warn_impcast_integer_sign; 10947 10948 // Traditionally, gcc has warned about this under -Wsign-compare. 10949 // We also want to warn about it in -Wconversion. 10950 // So if -Wconversion is off, use a completely identical diagnostic 10951 // in the sign-compare group. 10952 // The conditional-checking code will 10953 if (ICContext) { 10954 DiagID = diag::warn_impcast_integer_sign_conditional; 10955 *ICContext = true; 10956 } 10957 10958 return DiagnoseImpCast(S, E, T, CC, DiagID); 10959 } 10960 10961 // Diagnose conversions between different enumeration types. 10962 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 10963 // type, to give us better diagnostics. 10964 QualType SourceType = E->getType(); 10965 if (!S.getLangOpts().CPlusPlus) { 10966 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10967 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 10968 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 10969 SourceType = S.Context.getTypeDeclType(Enum); 10970 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 10971 } 10972 } 10973 10974 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 10975 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 10976 if (SourceEnum->getDecl()->hasNameForLinkage() && 10977 TargetEnum->getDecl()->hasNameForLinkage() && 10978 SourceEnum != TargetEnum) { 10979 if (S.SourceMgr.isInSystemMacro(CC)) 10980 return; 10981 10982 return DiagnoseImpCast(S, E, SourceType, T, CC, 10983 diag::warn_impcast_different_enum_types); 10984 } 10985 } 10986 10987 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 10988 SourceLocation CC, QualType T); 10989 10990 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 10991 SourceLocation CC, bool &ICContext) { 10992 E = E->IgnoreParenImpCasts(); 10993 10994 if (isa<ConditionalOperator>(E)) 10995 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 10996 10997 AnalyzeImplicitConversions(S, E, CC); 10998 if (E->getType() != T) 10999 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11000 } 11001 11002 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11003 SourceLocation CC, QualType T) { 11004 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11005 11006 bool Suspicious = false; 11007 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11008 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11009 11010 // If -Wconversion would have warned about either of the candidates 11011 // for a signedness conversion to the context type... 11012 if (!Suspicious) return; 11013 11014 // ...but it's currently ignored... 11015 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11016 return; 11017 11018 // ...then check whether it would have warned about either of the 11019 // candidates for a signedness conversion to the condition type. 11020 if (E->getType() == T) return; 11021 11022 Suspicious = false; 11023 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11024 E->getType(), CC, &Suspicious); 11025 if (!Suspicious) 11026 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11027 E->getType(), CC, &Suspicious); 11028 } 11029 11030 /// Check conversion of given expression to boolean. 11031 /// Input argument E is a logical expression. 11032 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11033 if (S.getLangOpts().Bool) 11034 return; 11035 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11036 return; 11037 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11038 } 11039 11040 /// AnalyzeImplicitConversions - Find and report any interesting 11041 /// implicit conversions in the given expression. There are a couple 11042 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11043 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11044 SourceLocation CC) { 11045 QualType T = OrigE->getType(); 11046 Expr *E = OrigE->IgnoreParenImpCasts(); 11047 11048 if (E->isTypeDependent() || E->isValueDependent()) 11049 return; 11050 11051 // For conditional operators, we analyze the arguments as if they 11052 // were being fed directly into the output. 11053 if (isa<ConditionalOperator>(E)) { 11054 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11055 CheckConditionalOperator(S, CO, CC, T); 11056 return; 11057 } 11058 11059 // Check implicit argument conversions for function calls. 11060 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11061 CheckImplicitArgumentConversions(S, Call, CC); 11062 11063 // Go ahead and check any implicit conversions we might have skipped. 11064 // The non-canonical typecheck is just an optimization; 11065 // CheckImplicitConversion will filter out dead implicit conversions. 11066 if (E->getType() != T) 11067 CheckImplicitConversion(S, E, T, CC); 11068 11069 // Now continue drilling into this expression. 11070 11071 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11072 // The bound subexpressions in a PseudoObjectExpr are not reachable 11073 // as transitive children. 11074 // FIXME: Use a more uniform representation for this. 11075 for (auto *SE : POE->semantics()) 11076 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11077 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11078 } 11079 11080 // Skip past explicit casts. 11081 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11082 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11083 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11084 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11085 return AnalyzeImplicitConversions(S, E, CC); 11086 } 11087 11088 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11089 // Do a somewhat different check with comparison operators. 11090 if (BO->isComparisonOp()) 11091 return AnalyzeComparison(S, BO); 11092 11093 // And with simple assignments. 11094 if (BO->getOpcode() == BO_Assign) 11095 return AnalyzeAssignment(S, BO); 11096 // And with compound assignments. 11097 if (BO->isAssignmentOp()) 11098 return AnalyzeCompoundAssignment(S, BO); 11099 } 11100 11101 // These break the otherwise-useful invariant below. Fortunately, 11102 // we don't really need to recurse into them, because any internal 11103 // expressions should have been analyzed already when they were 11104 // built into statements. 11105 if (isa<StmtExpr>(E)) return; 11106 11107 // Don't descend into unevaluated contexts. 11108 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11109 11110 // Now just recurse over the expression's children. 11111 CC = E->getExprLoc(); 11112 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11113 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11114 for (Stmt *SubStmt : E->children()) { 11115 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11116 if (!ChildExpr) 11117 continue; 11118 11119 if (IsLogicalAndOperator && 11120 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11121 // Ignore checking string literals that are in logical and operators. 11122 // This is a common pattern for asserts. 11123 continue; 11124 AnalyzeImplicitConversions(S, ChildExpr, CC); 11125 } 11126 11127 if (BO && BO->isLogicalOp()) { 11128 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11129 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11130 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11131 11132 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11133 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11134 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11135 } 11136 11137 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11138 if (U->getOpcode() == UO_LNot) { 11139 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11140 } else if (U->getOpcode() != UO_AddrOf) { 11141 if (U->getSubExpr()->getType()->isAtomicType()) 11142 S.Diag(U->getSubExpr()->getBeginLoc(), 11143 diag::warn_atomic_implicit_seq_cst); 11144 } 11145 } 11146 } 11147 11148 /// Diagnose integer type and any valid implicit conversion to it. 11149 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11150 // Taking into account implicit conversions, 11151 // allow any integer. 11152 if (!E->getType()->isIntegerType()) { 11153 S.Diag(E->getBeginLoc(), 11154 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11155 return true; 11156 } 11157 // Potentially emit standard warnings for implicit conversions if enabled 11158 // using -Wconversion. 11159 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11160 return false; 11161 } 11162 11163 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11164 // Returns true when emitting a warning about taking the address of a reference. 11165 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11166 const PartialDiagnostic &PD) { 11167 E = E->IgnoreParenImpCasts(); 11168 11169 const FunctionDecl *FD = nullptr; 11170 11171 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11172 if (!DRE->getDecl()->getType()->isReferenceType()) 11173 return false; 11174 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11175 if (!M->getMemberDecl()->getType()->isReferenceType()) 11176 return false; 11177 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11178 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11179 return false; 11180 FD = Call->getDirectCallee(); 11181 } else { 11182 return false; 11183 } 11184 11185 SemaRef.Diag(E->getExprLoc(), PD); 11186 11187 // If possible, point to location of function. 11188 if (FD) { 11189 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11190 } 11191 11192 return true; 11193 } 11194 11195 // Returns true if the SourceLocation is expanded from any macro body. 11196 // Returns false if the SourceLocation is invalid, is from not in a macro 11197 // expansion, or is from expanded from a top-level macro argument. 11198 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11199 if (Loc.isInvalid()) 11200 return false; 11201 11202 while (Loc.isMacroID()) { 11203 if (SM.isMacroBodyExpansion(Loc)) 11204 return true; 11205 Loc = SM.getImmediateMacroCallerLoc(Loc); 11206 } 11207 11208 return false; 11209 } 11210 11211 /// Diagnose pointers that are always non-null. 11212 /// \param E the expression containing the pointer 11213 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11214 /// compared to a null pointer 11215 /// \param IsEqual True when the comparison is equal to a null pointer 11216 /// \param Range Extra SourceRange to highlight in the diagnostic 11217 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11218 Expr::NullPointerConstantKind NullKind, 11219 bool IsEqual, SourceRange Range) { 11220 if (!E) 11221 return; 11222 11223 // Don't warn inside macros. 11224 if (E->getExprLoc().isMacroID()) { 11225 const SourceManager &SM = getSourceManager(); 11226 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11227 IsInAnyMacroBody(SM, Range.getBegin())) 11228 return; 11229 } 11230 E = E->IgnoreImpCasts(); 11231 11232 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11233 11234 if (isa<CXXThisExpr>(E)) { 11235 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11236 : diag::warn_this_bool_conversion; 11237 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11238 return; 11239 } 11240 11241 bool IsAddressOf = false; 11242 11243 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11244 if (UO->getOpcode() != UO_AddrOf) 11245 return; 11246 IsAddressOf = true; 11247 E = UO->getSubExpr(); 11248 } 11249 11250 if (IsAddressOf) { 11251 unsigned DiagID = IsCompare 11252 ? diag::warn_address_of_reference_null_compare 11253 : diag::warn_address_of_reference_bool_conversion; 11254 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11255 << IsEqual; 11256 if (CheckForReference(*this, E, PD)) { 11257 return; 11258 } 11259 } 11260 11261 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11262 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11263 std::string Str; 11264 llvm::raw_string_ostream S(Str); 11265 E->printPretty(S, nullptr, getPrintingPolicy()); 11266 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11267 : diag::warn_cast_nonnull_to_bool; 11268 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11269 << E->getSourceRange() << Range << IsEqual; 11270 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11271 }; 11272 11273 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11274 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11275 if (auto *Callee = Call->getDirectCallee()) { 11276 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11277 ComplainAboutNonnullParamOrCall(A); 11278 return; 11279 } 11280 } 11281 } 11282 11283 // Expect to find a single Decl. Skip anything more complicated. 11284 ValueDecl *D = nullptr; 11285 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11286 D = R->getDecl(); 11287 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11288 D = M->getMemberDecl(); 11289 } 11290 11291 // Weak Decls can be null. 11292 if (!D || D->isWeak()) 11293 return; 11294 11295 // Check for parameter decl with nonnull attribute 11296 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11297 if (getCurFunction() && 11298 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11299 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11300 ComplainAboutNonnullParamOrCall(A); 11301 return; 11302 } 11303 11304 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11305 auto ParamIter = llvm::find(FD->parameters(), PV); 11306 assert(ParamIter != FD->param_end()); 11307 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11308 11309 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11310 if (!NonNull->args_size()) { 11311 ComplainAboutNonnullParamOrCall(NonNull); 11312 return; 11313 } 11314 11315 for (const ParamIdx &ArgNo : NonNull->args()) { 11316 if (ArgNo.getASTIndex() == ParamNo) { 11317 ComplainAboutNonnullParamOrCall(NonNull); 11318 return; 11319 } 11320 } 11321 } 11322 } 11323 } 11324 } 11325 11326 QualType T = D->getType(); 11327 const bool IsArray = T->isArrayType(); 11328 const bool IsFunction = T->isFunctionType(); 11329 11330 // Address of function is used to silence the function warning. 11331 if (IsAddressOf && IsFunction) { 11332 return; 11333 } 11334 11335 // Found nothing. 11336 if (!IsAddressOf && !IsFunction && !IsArray) 11337 return; 11338 11339 // Pretty print the expression for the diagnostic. 11340 std::string Str; 11341 llvm::raw_string_ostream S(Str); 11342 E->printPretty(S, nullptr, getPrintingPolicy()); 11343 11344 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11345 : diag::warn_impcast_pointer_to_bool; 11346 enum { 11347 AddressOf, 11348 FunctionPointer, 11349 ArrayPointer 11350 } DiagType; 11351 if (IsAddressOf) 11352 DiagType = AddressOf; 11353 else if (IsFunction) 11354 DiagType = FunctionPointer; 11355 else if (IsArray) 11356 DiagType = ArrayPointer; 11357 else 11358 llvm_unreachable("Could not determine diagnostic."); 11359 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11360 << Range << IsEqual; 11361 11362 if (!IsFunction) 11363 return; 11364 11365 // Suggest '&' to silence the function warning. 11366 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11367 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11368 11369 // Check to see if '()' fixit should be emitted. 11370 QualType ReturnType; 11371 UnresolvedSet<4> NonTemplateOverloads; 11372 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11373 if (ReturnType.isNull()) 11374 return; 11375 11376 if (IsCompare) { 11377 // There are two cases here. If there is null constant, the only suggest 11378 // for a pointer return type. If the null is 0, then suggest if the return 11379 // type is a pointer or an integer type. 11380 if (!ReturnType->isPointerType()) { 11381 if (NullKind == Expr::NPCK_ZeroExpression || 11382 NullKind == Expr::NPCK_ZeroLiteral) { 11383 if (!ReturnType->isIntegerType()) 11384 return; 11385 } else { 11386 return; 11387 } 11388 } 11389 } else { // !IsCompare 11390 // For function to bool, only suggest if the function pointer has bool 11391 // return type. 11392 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11393 return; 11394 } 11395 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11396 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11397 } 11398 11399 /// Diagnoses "dangerous" implicit conversions within the given 11400 /// expression (which is a full expression). Implements -Wconversion 11401 /// and -Wsign-compare. 11402 /// 11403 /// \param CC the "context" location of the implicit conversion, i.e. 11404 /// the most location of the syntactic entity requiring the implicit 11405 /// conversion 11406 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11407 // Don't diagnose in unevaluated contexts. 11408 if (isUnevaluatedContext()) 11409 return; 11410 11411 // Don't diagnose for value- or type-dependent expressions. 11412 if (E->isTypeDependent() || E->isValueDependent()) 11413 return; 11414 11415 // Check for array bounds violations in cases where the check isn't triggered 11416 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11417 // ArraySubscriptExpr is on the RHS of a variable initialization. 11418 CheckArrayAccess(E); 11419 11420 // This is not the right CC for (e.g.) a variable initialization. 11421 AnalyzeImplicitConversions(*this, E, CC); 11422 } 11423 11424 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11425 /// Input argument E is a logical expression. 11426 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11427 ::CheckBoolLikeConversion(*this, E, CC); 11428 } 11429 11430 /// Diagnose when expression is an integer constant expression and its evaluation 11431 /// results in integer overflow 11432 void Sema::CheckForIntOverflow (Expr *E) { 11433 // Use a work list to deal with nested struct initializers. 11434 SmallVector<Expr *, 2> Exprs(1, E); 11435 11436 do { 11437 Expr *OriginalE = Exprs.pop_back_val(); 11438 Expr *E = OriginalE->IgnoreParenCasts(); 11439 11440 if (isa<BinaryOperator>(E)) { 11441 E->EvaluateForOverflow(Context); 11442 continue; 11443 } 11444 11445 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11446 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11447 else if (isa<ObjCBoxedExpr>(OriginalE)) 11448 E->EvaluateForOverflow(Context); 11449 else if (auto Call = dyn_cast<CallExpr>(E)) 11450 Exprs.append(Call->arg_begin(), Call->arg_end()); 11451 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11452 Exprs.append(Message->arg_begin(), Message->arg_end()); 11453 } while (!Exprs.empty()); 11454 } 11455 11456 namespace { 11457 11458 /// Visitor for expressions which looks for unsequenced operations on the 11459 /// same object. 11460 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11461 using Base = EvaluatedExprVisitor<SequenceChecker>; 11462 11463 /// A tree of sequenced regions within an expression. Two regions are 11464 /// unsequenced if one is an ancestor or a descendent of the other. When we 11465 /// finish processing an expression with sequencing, such as a comma 11466 /// expression, we fold its tree nodes into its parent, since they are 11467 /// unsequenced with respect to nodes we will visit later. 11468 class SequenceTree { 11469 struct Value { 11470 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11471 unsigned Parent : 31; 11472 unsigned Merged : 1; 11473 }; 11474 SmallVector<Value, 8> Values; 11475 11476 public: 11477 /// A region within an expression which may be sequenced with respect 11478 /// to some other region. 11479 class Seq { 11480 friend class SequenceTree; 11481 11482 unsigned Index = 0; 11483 11484 explicit Seq(unsigned N) : Index(N) {} 11485 11486 public: 11487 Seq() = default; 11488 }; 11489 11490 SequenceTree() { Values.push_back(Value(0)); } 11491 Seq root() const { return Seq(0); } 11492 11493 /// Create a new sequence of operations, which is an unsequenced 11494 /// subset of \p Parent. This sequence of operations is sequenced with 11495 /// respect to other children of \p Parent. 11496 Seq allocate(Seq Parent) { 11497 Values.push_back(Value(Parent.Index)); 11498 return Seq(Values.size() - 1); 11499 } 11500 11501 /// Merge a sequence of operations into its parent. 11502 void merge(Seq S) { 11503 Values[S.Index].Merged = true; 11504 } 11505 11506 /// Determine whether two operations are unsequenced. This operation 11507 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11508 /// should have been merged into its parent as appropriate. 11509 bool isUnsequenced(Seq Cur, Seq Old) { 11510 unsigned C = representative(Cur.Index); 11511 unsigned Target = representative(Old.Index); 11512 while (C >= Target) { 11513 if (C == Target) 11514 return true; 11515 C = Values[C].Parent; 11516 } 11517 return false; 11518 } 11519 11520 private: 11521 /// Pick a representative for a sequence. 11522 unsigned representative(unsigned K) { 11523 if (Values[K].Merged) 11524 // Perform path compression as we go. 11525 return Values[K].Parent = representative(Values[K].Parent); 11526 return K; 11527 } 11528 }; 11529 11530 /// An object for which we can track unsequenced uses. 11531 using Object = NamedDecl *; 11532 11533 /// Different flavors of object usage which we track. We only track the 11534 /// least-sequenced usage of each kind. 11535 enum UsageKind { 11536 /// A read of an object. Multiple unsequenced reads are OK. 11537 UK_Use, 11538 11539 /// A modification of an object which is sequenced before the value 11540 /// computation of the expression, such as ++n in C++. 11541 UK_ModAsValue, 11542 11543 /// A modification of an object which is not sequenced before the value 11544 /// computation of the expression, such as n++. 11545 UK_ModAsSideEffect, 11546 11547 UK_Count = UK_ModAsSideEffect + 1 11548 }; 11549 11550 struct Usage { 11551 Expr *Use = nullptr; 11552 SequenceTree::Seq Seq; 11553 11554 Usage() = default; 11555 }; 11556 11557 struct UsageInfo { 11558 Usage Uses[UK_Count]; 11559 11560 /// Have we issued a diagnostic for this variable already? 11561 bool Diagnosed = false; 11562 11563 UsageInfo() = default; 11564 }; 11565 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11566 11567 Sema &SemaRef; 11568 11569 /// Sequenced regions within the expression. 11570 SequenceTree Tree; 11571 11572 /// Declaration modifications and references which we have seen. 11573 UsageInfoMap UsageMap; 11574 11575 /// The region we are currently within. 11576 SequenceTree::Seq Region; 11577 11578 /// Filled in with declarations which were modified as a side-effect 11579 /// (that is, post-increment operations). 11580 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11581 11582 /// Expressions to check later. We defer checking these to reduce 11583 /// stack usage. 11584 SmallVectorImpl<Expr *> &WorkList; 11585 11586 /// RAII object wrapping the visitation of a sequenced subexpression of an 11587 /// expression. At the end of this process, the side-effects of the evaluation 11588 /// become sequenced with respect to the value computation of the result, so 11589 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11590 /// UK_ModAsValue. 11591 struct SequencedSubexpression { 11592 SequencedSubexpression(SequenceChecker &Self) 11593 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11594 Self.ModAsSideEffect = &ModAsSideEffect; 11595 } 11596 11597 ~SequencedSubexpression() { 11598 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11599 UsageInfo &U = Self.UsageMap[M.first]; 11600 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11601 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11602 SideEffectUsage = M.second; 11603 } 11604 Self.ModAsSideEffect = OldModAsSideEffect; 11605 } 11606 11607 SequenceChecker &Self; 11608 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11609 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11610 }; 11611 11612 /// RAII object wrapping the visitation of a subexpression which we might 11613 /// choose to evaluate as a constant. If any subexpression is evaluated and 11614 /// found to be non-constant, this allows us to suppress the evaluation of 11615 /// the outer expression. 11616 class EvaluationTracker { 11617 public: 11618 EvaluationTracker(SequenceChecker &Self) 11619 : Self(Self), Prev(Self.EvalTracker) { 11620 Self.EvalTracker = this; 11621 } 11622 11623 ~EvaluationTracker() { 11624 Self.EvalTracker = Prev; 11625 if (Prev) 11626 Prev->EvalOK &= EvalOK; 11627 } 11628 11629 bool evaluate(const Expr *E, bool &Result) { 11630 if (!EvalOK || E->isValueDependent()) 11631 return false; 11632 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11633 return EvalOK; 11634 } 11635 11636 private: 11637 SequenceChecker &Self; 11638 EvaluationTracker *Prev; 11639 bool EvalOK = true; 11640 } *EvalTracker = nullptr; 11641 11642 /// Find the object which is produced by the specified expression, 11643 /// if any. 11644 Object getObject(Expr *E, bool Mod) const { 11645 E = E->IgnoreParenCasts(); 11646 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11647 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11648 return getObject(UO->getSubExpr(), Mod); 11649 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11650 if (BO->getOpcode() == BO_Comma) 11651 return getObject(BO->getRHS(), Mod); 11652 if (Mod && BO->isAssignmentOp()) 11653 return getObject(BO->getLHS(), Mod); 11654 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11655 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11656 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11657 return ME->getMemberDecl(); 11658 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11659 // FIXME: If this is a reference, map through to its value. 11660 return DRE->getDecl(); 11661 return nullptr; 11662 } 11663 11664 /// Note that an object was modified or used by an expression. 11665 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11666 Usage &U = UI.Uses[UK]; 11667 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11668 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11669 ModAsSideEffect->push_back(std::make_pair(O, U)); 11670 U.Use = Ref; 11671 U.Seq = Region; 11672 } 11673 } 11674 11675 /// Check whether a modification or use conflicts with a prior usage. 11676 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11677 bool IsModMod) { 11678 if (UI.Diagnosed) 11679 return; 11680 11681 const Usage &U = UI.Uses[OtherKind]; 11682 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11683 return; 11684 11685 Expr *Mod = U.Use; 11686 Expr *ModOrUse = Ref; 11687 if (OtherKind == UK_Use) 11688 std::swap(Mod, ModOrUse); 11689 11690 SemaRef.Diag(Mod->getExprLoc(), 11691 IsModMod ? diag::warn_unsequenced_mod_mod 11692 : diag::warn_unsequenced_mod_use) 11693 << O << SourceRange(ModOrUse->getExprLoc()); 11694 UI.Diagnosed = true; 11695 } 11696 11697 void notePreUse(Object O, Expr *Use) { 11698 UsageInfo &U = UsageMap[O]; 11699 // Uses conflict with other modifications. 11700 checkUsage(O, U, Use, UK_ModAsValue, false); 11701 } 11702 11703 void notePostUse(Object O, Expr *Use) { 11704 UsageInfo &U = UsageMap[O]; 11705 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 11706 addUsage(U, O, Use, UK_Use); 11707 } 11708 11709 void notePreMod(Object O, Expr *Mod) { 11710 UsageInfo &U = UsageMap[O]; 11711 // Modifications conflict with other modifications and with uses. 11712 checkUsage(O, U, Mod, UK_ModAsValue, true); 11713 checkUsage(O, U, Mod, UK_Use, false); 11714 } 11715 11716 void notePostMod(Object O, Expr *Use, UsageKind UK) { 11717 UsageInfo &U = UsageMap[O]; 11718 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 11719 addUsage(U, O, Use, UK); 11720 } 11721 11722 public: 11723 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 11724 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 11725 Visit(E); 11726 } 11727 11728 void VisitStmt(Stmt *S) { 11729 // Skip all statements which aren't expressions for now. 11730 } 11731 11732 void VisitExpr(Expr *E) { 11733 // By default, just recurse to evaluated subexpressions. 11734 Base::VisitStmt(E); 11735 } 11736 11737 void VisitCastExpr(CastExpr *E) { 11738 Object O = Object(); 11739 if (E->getCastKind() == CK_LValueToRValue) 11740 O = getObject(E->getSubExpr(), false); 11741 11742 if (O) 11743 notePreUse(O, E); 11744 VisitExpr(E); 11745 if (O) 11746 notePostUse(O, E); 11747 } 11748 11749 void VisitBinComma(BinaryOperator *BO) { 11750 // C++11 [expr.comma]p1: 11751 // Every value computation and side effect associated with the left 11752 // expression is sequenced before every value computation and side 11753 // effect associated with the right expression. 11754 SequenceTree::Seq LHS = Tree.allocate(Region); 11755 SequenceTree::Seq RHS = Tree.allocate(Region); 11756 SequenceTree::Seq OldRegion = Region; 11757 11758 { 11759 SequencedSubexpression SeqLHS(*this); 11760 Region = LHS; 11761 Visit(BO->getLHS()); 11762 } 11763 11764 Region = RHS; 11765 Visit(BO->getRHS()); 11766 11767 Region = OldRegion; 11768 11769 // Forget that LHS and RHS are sequenced. They are both unsequenced 11770 // with respect to other stuff. 11771 Tree.merge(LHS); 11772 Tree.merge(RHS); 11773 } 11774 11775 void VisitBinAssign(BinaryOperator *BO) { 11776 // The modification is sequenced after the value computation of the LHS 11777 // and RHS, so check it before inspecting the operands and update the 11778 // map afterwards. 11779 Object O = getObject(BO->getLHS(), true); 11780 if (!O) 11781 return VisitExpr(BO); 11782 11783 notePreMod(O, BO); 11784 11785 // C++11 [expr.ass]p7: 11786 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 11787 // only once. 11788 // 11789 // Therefore, for a compound assignment operator, O is considered used 11790 // everywhere except within the evaluation of E1 itself. 11791 if (isa<CompoundAssignOperator>(BO)) 11792 notePreUse(O, BO); 11793 11794 Visit(BO->getLHS()); 11795 11796 if (isa<CompoundAssignOperator>(BO)) 11797 notePostUse(O, BO); 11798 11799 Visit(BO->getRHS()); 11800 11801 // C++11 [expr.ass]p1: 11802 // the assignment is sequenced [...] before the value computation of the 11803 // assignment expression. 11804 // C11 6.5.16/3 has no such rule. 11805 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11806 : UK_ModAsSideEffect); 11807 } 11808 11809 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 11810 VisitBinAssign(CAO); 11811 } 11812 11813 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11814 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 11815 void VisitUnaryPreIncDec(UnaryOperator *UO) { 11816 Object O = getObject(UO->getSubExpr(), true); 11817 if (!O) 11818 return VisitExpr(UO); 11819 11820 notePreMod(O, UO); 11821 Visit(UO->getSubExpr()); 11822 // C++11 [expr.pre.incr]p1: 11823 // the expression ++x is equivalent to x+=1 11824 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 11825 : UK_ModAsSideEffect); 11826 } 11827 11828 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11829 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 11830 void VisitUnaryPostIncDec(UnaryOperator *UO) { 11831 Object O = getObject(UO->getSubExpr(), true); 11832 if (!O) 11833 return VisitExpr(UO); 11834 11835 notePreMod(O, UO); 11836 Visit(UO->getSubExpr()); 11837 notePostMod(O, UO, UK_ModAsSideEffect); 11838 } 11839 11840 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 11841 void VisitBinLOr(BinaryOperator *BO) { 11842 // The side-effects of the LHS of an '&&' are sequenced before the 11843 // value computation of the RHS, and hence before the value computation 11844 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 11845 // as if they were unconditionally sequenced. 11846 EvaluationTracker Eval(*this); 11847 { 11848 SequencedSubexpression Sequenced(*this); 11849 Visit(BO->getLHS()); 11850 } 11851 11852 bool Result; 11853 if (Eval.evaluate(BO->getLHS(), Result)) { 11854 if (!Result) 11855 Visit(BO->getRHS()); 11856 } else { 11857 // Check for unsequenced operations in the RHS, treating it as an 11858 // entirely separate evaluation. 11859 // 11860 // FIXME: If there are operations in the RHS which are unsequenced 11861 // with respect to operations outside the RHS, and those operations 11862 // are unconditionally evaluated, diagnose them. 11863 WorkList.push_back(BO->getRHS()); 11864 } 11865 } 11866 void VisitBinLAnd(BinaryOperator *BO) { 11867 EvaluationTracker Eval(*this); 11868 { 11869 SequencedSubexpression Sequenced(*this); 11870 Visit(BO->getLHS()); 11871 } 11872 11873 bool Result; 11874 if (Eval.evaluate(BO->getLHS(), Result)) { 11875 if (Result) 11876 Visit(BO->getRHS()); 11877 } else { 11878 WorkList.push_back(BO->getRHS()); 11879 } 11880 } 11881 11882 // Only visit the condition, unless we can be sure which subexpression will 11883 // be chosen. 11884 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 11885 EvaluationTracker Eval(*this); 11886 { 11887 SequencedSubexpression Sequenced(*this); 11888 Visit(CO->getCond()); 11889 } 11890 11891 bool Result; 11892 if (Eval.evaluate(CO->getCond(), Result)) 11893 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 11894 else { 11895 WorkList.push_back(CO->getTrueExpr()); 11896 WorkList.push_back(CO->getFalseExpr()); 11897 } 11898 } 11899 11900 void VisitCallExpr(CallExpr *CE) { 11901 // C++11 [intro.execution]p15: 11902 // When calling a function [...], every value computation and side effect 11903 // associated with any argument expression, or with the postfix expression 11904 // designating the called function, is sequenced before execution of every 11905 // expression or statement in the body of the function [and thus before 11906 // the value computation of its result]. 11907 SequencedSubexpression Sequenced(*this); 11908 Base::VisitCallExpr(CE); 11909 11910 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 11911 } 11912 11913 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 11914 // This is a call, so all subexpressions are sequenced before the result. 11915 SequencedSubexpression Sequenced(*this); 11916 11917 if (!CCE->isListInitialization()) 11918 return VisitExpr(CCE); 11919 11920 // In C++11, list initializations are sequenced. 11921 SmallVector<SequenceTree::Seq, 32> Elts; 11922 SequenceTree::Seq Parent = Region; 11923 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 11924 E = CCE->arg_end(); 11925 I != E; ++I) { 11926 Region = Tree.allocate(Parent); 11927 Elts.push_back(Region); 11928 Visit(*I); 11929 } 11930 11931 // Forget that the initializers are sequenced. 11932 Region = Parent; 11933 for (unsigned I = 0; I < Elts.size(); ++I) 11934 Tree.merge(Elts[I]); 11935 } 11936 11937 void VisitInitListExpr(InitListExpr *ILE) { 11938 if (!SemaRef.getLangOpts().CPlusPlus11) 11939 return VisitExpr(ILE); 11940 11941 // In C++11, list initializations are sequenced. 11942 SmallVector<SequenceTree::Seq, 32> Elts; 11943 SequenceTree::Seq Parent = Region; 11944 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 11945 Expr *E = ILE->getInit(I); 11946 if (!E) continue; 11947 Region = Tree.allocate(Parent); 11948 Elts.push_back(Region); 11949 Visit(E); 11950 } 11951 11952 // Forget that the initializers are sequenced. 11953 Region = Parent; 11954 for (unsigned I = 0; I < Elts.size(); ++I) 11955 Tree.merge(Elts[I]); 11956 } 11957 }; 11958 11959 } // namespace 11960 11961 void Sema::CheckUnsequencedOperations(Expr *E) { 11962 SmallVector<Expr *, 8> WorkList; 11963 WorkList.push_back(E); 11964 while (!WorkList.empty()) { 11965 Expr *Item = WorkList.pop_back_val(); 11966 SequenceChecker(*this, Item, WorkList); 11967 } 11968 } 11969 11970 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 11971 bool IsConstexpr) { 11972 CheckImplicitConversions(E, CheckLoc); 11973 if (!E->isInstantiationDependent()) 11974 CheckUnsequencedOperations(E); 11975 if (!IsConstexpr && !E->isValueDependent()) 11976 CheckForIntOverflow(E); 11977 DiagnoseMisalignedMembers(); 11978 } 11979 11980 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 11981 FieldDecl *BitField, 11982 Expr *Init) { 11983 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 11984 } 11985 11986 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 11987 SourceLocation Loc) { 11988 if (!PType->isVariablyModifiedType()) 11989 return; 11990 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 11991 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 11992 return; 11993 } 11994 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 11995 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 11996 return; 11997 } 11998 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 11999 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12000 return; 12001 } 12002 12003 const ArrayType *AT = S.Context.getAsArrayType(PType); 12004 if (!AT) 12005 return; 12006 12007 if (AT->getSizeModifier() != ArrayType::Star) { 12008 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12009 return; 12010 } 12011 12012 S.Diag(Loc, diag::err_array_star_in_function_definition); 12013 } 12014 12015 /// CheckParmsForFunctionDef - Check that the parameters of the given 12016 /// function are appropriate for the definition of a function. This 12017 /// takes care of any checks that cannot be performed on the 12018 /// declaration itself, e.g., that the types of each of the function 12019 /// parameters are complete. 12020 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12021 bool CheckParameterNames) { 12022 bool HasInvalidParm = false; 12023 for (ParmVarDecl *Param : Parameters) { 12024 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12025 // function declarator that is part of a function definition of 12026 // that function shall not have incomplete type. 12027 // 12028 // This is also C++ [dcl.fct]p6. 12029 if (!Param->isInvalidDecl() && 12030 RequireCompleteType(Param->getLocation(), Param->getType(), 12031 diag::err_typecheck_decl_incomplete_type)) { 12032 Param->setInvalidDecl(); 12033 HasInvalidParm = true; 12034 } 12035 12036 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12037 // declaration of each parameter shall include an identifier. 12038 if (CheckParameterNames && 12039 Param->getIdentifier() == nullptr && 12040 !Param->isImplicit() && 12041 !getLangOpts().CPlusPlus) 12042 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12043 12044 // C99 6.7.5.3p12: 12045 // If the function declarator is not part of a definition of that 12046 // function, parameters may have incomplete type and may use the [*] 12047 // notation in their sequences of declarator specifiers to specify 12048 // variable length array types. 12049 QualType PType = Param->getOriginalType(); 12050 // FIXME: This diagnostic should point the '[*]' if source-location 12051 // information is added for it. 12052 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12053 12054 // If the parameter is a c++ class type and it has to be destructed in the 12055 // callee function, declare the destructor so that it can be called by the 12056 // callee function. Do not perform any direct access check on the dtor here. 12057 if (!Param->isInvalidDecl()) { 12058 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12059 if (!ClassDecl->isInvalidDecl() && 12060 !ClassDecl->hasIrrelevantDestructor() && 12061 !ClassDecl->isDependentContext() && 12062 ClassDecl->isParamDestroyedInCallee()) { 12063 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12064 MarkFunctionReferenced(Param->getLocation(), Destructor); 12065 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12066 } 12067 } 12068 } 12069 12070 // Parameters with the pass_object_size attribute only need to be marked 12071 // constant at function definitions. Because we lack information about 12072 // whether we're on a declaration or definition when we're instantiating the 12073 // attribute, we need to check for constness here. 12074 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12075 if (!Param->getType().isConstQualified()) 12076 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12077 << Attr->getSpelling() << 1; 12078 } 12079 12080 return HasInvalidParm; 12081 } 12082 12083 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12084 /// or MemberExpr. 12085 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12086 ASTContext &Context) { 12087 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12088 return Context.getDeclAlign(DRE->getDecl()); 12089 12090 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12091 return Context.getDeclAlign(ME->getMemberDecl()); 12092 12093 return TypeAlign; 12094 } 12095 12096 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12097 /// pointer cast increases the alignment requirements. 12098 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12099 // This is actually a lot of work to potentially be doing on every 12100 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12101 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12102 return; 12103 12104 // Ignore dependent types. 12105 if (T->isDependentType() || Op->getType()->isDependentType()) 12106 return; 12107 12108 // Require that the destination be a pointer type. 12109 const PointerType *DestPtr = T->getAs<PointerType>(); 12110 if (!DestPtr) return; 12111 12112 // If the destination has alignment 1, we're done. 12113 QualType DestPointee = DestPtr->getPointeeType(); 12114 if (DestPointee->isIncompleteType()) return; 12115 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12116 if (DestAlign.isOne()) return; 12117 12118 // Require that the source be a pointer type. 12119 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12120 if (!SrcPtr) return; 12121 QualType SrcPointee = SrcPtr->getPointeeType(); 12122 12123 // Whitelist casts from cv void*. We already implicitly 12124 // whitelisted casts to cv void*, since they have alignment 1. 12125 // Also whitelist casts involving incomplete types, which implicitly 12126 // includes 'void'. 12127 if (SrcPointee->isIncompleteType()) return; 12128 12129 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12130 12131 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12132 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12133 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12134 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12135 if (UO->getOpcode() == UO_AddrOf) 12136 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12137 } 12138 12139 if (SrcAlign >= DestAlign) return; 12140 12141 Diag(TRange.getBegin(), diag::warn_cast_align) 12142 << Op->getType() << T 12143 << static_cast<unsigned>(SrcAlign.getQuantity()) 12144 << static_cast<unsigned>(DestAlign.getQuantity()) 12145 << TRange << Op->getSourceRange(); 12146 } 12147 12148 /// Check whether this array fits the idiom of a size-one tail padded 12149 /// array member of a struct. 12150 /// 12151 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12152 /// commonly used to emulate flexible arrays in C89 code. 12153 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12154 const NamedDecl *ND) { 12155 if (Size != 1 || !ND) return false; 12156 12157 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12158 if (!FD) return false; 12159 12160 // Don't consider sizes resulting from macro expansions or template argument 12161 // substitution to form C89 tail-padded arrays. 12162 12163 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12164 while (TInfo) { 12165 TypeLoc TL = TInfo->getTypeLoc(); 12166 // Look through typedefs. 12167 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12168 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12169 TInfo = TDL->getTypeSourceInfo(); 12170 continue; 12171 } 12172 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12173 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12174 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12175 return false; 12176 } 12177 break; 12178 } 12179 12180 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12181 if (!RD) return false; 12182 if (RD->isUnion()) return false; 12183 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12184 if (!CRD->isStandardLayout()) return false; 12185 } 12186 12187 // See if this is the last field decl in the record. 12188 const Decl *D = FD; 12189 while ((D = D->getNextDeclInContext())) 12190 if (isa<FieldDecl>(D)) 12191 return false; 12192 return true; 12193 } 12194 12195 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12196 const ArraySubscriptExpr *ASE, 12197 bool AllowOnePastEnd, bool IndexNegated) { 12198 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12199 if (IndexExpr->isValueDependent()) 12200 return; 12201 12202 const Type *EffectiveType = 12203 BaseExpr->getType()->getPointeeOrArrayElementType(); 12204 BaseExpr = BaseExpr->IgnoreParenCasts(); 12205 const ConstantArrayType *ArrayTy = 12206 Context.getAsConstantArrayType(BaseExpr->getType()); 12207 if (!ArrayTy) 12208 return; 12209 12210 llvm::APSInt index; 12211 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects)) 12212 return; 12213 if (IndexNegated) 12214 index = -index; 12215 12216 const NamedDecl *ND = nullptr; 12217 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12218 ND = DRE->getDecl(); 12219 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12220 ND = ME->getMemberDecl(); 12221 12222 if (index.isUnsigned() || !index.isNegative()) { 12223 llvm::APInt size = ArrayTy->getSize(); 12224 if (!size.isStrictlyPositive()) 12225 return; 12226 12227 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType(); 12228 if (BaseType != EffectiveType) { 12229 // Make sure we're comparing apples to apples when comparing index to size 12230 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12231 uint64_t array_typesize = Context.getTypeSize(BaseType); 12232 // Handle ptrarith_typesize being zero, such as when casting to void* 12233 if (!ptrarith_typesize) ptrarith_typesize = 1; 12234 if (ptrarith_typesize != array_typesize) { 12235 // There's a cast to a different size type involved 12236 uint64_t ratio = array_typesize / ptrarith_typesize; 12237 // TODO: Be smarter about handling cases where array_typesize is not a 12238 // multiple of ptrarith_typesize 12239 if (ptrarith_typesize * ratio == array_typesize) 12240 size *= llvm::APInt(size.getBitWidth(), ratio); 12241 } 12242 } 12243 12244 if (size.getBitWidth() > index.getBitWidth()) 12245 index = index.zext(size.getBitWidth()); 12246 else if (size.getBitWidth() < index.getBitWidth()) 12247 size = size.zext(index.getBitWidth()); 12248 12249 // For array subscripting the index must be less than size, but for pointer 12250 // arithmetic also allow the index (offset) to be equal to size since 12251 // computing the next address after the end of the array is legal and 12252 // commonly done e.g. in C++ iterators and range-based for loops. 12253 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12254 return; 12255 12256 // Also don't warn for arrays of size 1 which are members of some 12257 // structure. These are often used to approximate flexible arrays in C89 12258 // code. 12259 if (IsTailPaddedMemberArray(*this, size, ND)) 12260 return; 12261 12262 // Suppress the warning if the subscript expression (as identified by the 12263 // ']' location) and the index expression are both from macro expansions 12264 // within a system header. 12265 if (ASE) { 12266 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12267 ASE->getRBracketLoc()); 12268 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12269 SourceLocation IndexLoc = 12270 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12271 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12272 return; 12273 } 12274 } 12275 12276 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12277 if (ASE) 12278 DiagID = diag::warn_array_index_exceeds_bounds; 12279 12280 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12281 PDiag(DiagID) << index.toString(10, true) 12282 << size.toString(10, true) 12283 << (unsigned)size.getLimitedValue(~0U) 12284 << IndexExpr->getSourceRange()); 12285 } else { 12286 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12287 if (!ASE) { 12288 DiagID = diag::warn_ptr_arith_precedes_bounds; 12289 if (index.isNegative()) index = -index; 12290 } 12291 12292 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12293 PDiag(DiagID) << index.toString(10, true) 12294 << IndexExpr->getSourceRange()); 12295 } 12296 12297 if (!ND) { 12298 // Try harder to find a NamedDecl to point at in the note. 12299 while (const ArraySubscriptExpr *ASE = 12300 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12301 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12302 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12303 ND = DRE->getDecl(); 12304 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12305 ND = ME->getMemberDecl(); 12306 } 12307 12308 if (ND) 12309 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12310 PDiag(diag::note_array_index_out_of_bounds) 12311 << ND->getDeclName()); 12312 } 12313 12314 void Sema::CheckArrayAccess(const Expr *expr) { 12315 int AllowOnePastEnd = 0; 12316 while (expr) { 12317 expr = expr->IgnoreParenImpCasts(); 12318 switch (expr->getStmtClass()) { 12319 case Stmt::ArraySubscriptExprClass: { 12320 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12321 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12322 AllowOnePastEnd > 0); 12323 expr = ASE->getBase(); 12324 break; 12325 } 12326 case Stmt::MemberExprClass: { 12327 expr = cast<MemberExpr>(expr)->getBase(); 12328 break; 12329 } 12330 case Stmt::OMPArraySectionExprClass: { 12331 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12332 if (ASE->getLowerBound()) 12333 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12334 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12335 return; 12336 } 12337 case Stmt::UnaryOperatorClass: { 12338 // Only unwrap the * and & unary operators 12339 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12340 expr = UO->getSubExpr(); 12341 switch (UO->getOpcode()) { 12342 case UO_AddrOf: 12343 AllowOnePastEnd++; 12344 break; 12345 case UO_Deref: 12346 AllowOnePastEnd--; 12347 break; 12348 default: 12349 return; 12350 } 12351 break; 12352 } 12353 case Stmt::ConditionalOperatorClass: { 12354 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12355 if (const Expr *lhs = cond->getLHS()) 12356 CheckArrayAccess(lhs); 12357 if (const Expr *rhs = cond->getRHS()) 12358 CheckArrayAccess(rhs); 12359 return; 12360 } 12361 case Stmt::CXXOperatorCallExprClass: { 12362 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12363 for (const auto *Arg : OCE->arguments()) 12364 CheckArrayAccess(Arg); 12365 return; 12366 } 12367 default: 12368 return; 12369 } 12370 } 12371 } 12372 12373 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12374 12375 namespace { 12376 12377 struct RetainCycleOwner { 12378 VarDecl *Variable = nullptr; 12379 SourceRange Range; 12380 SourceLocation Loc; 12381 bool Indirect = false; 12382 12383 RetainCycleOwner() = default; 12384 12385 void setLocsFrom(Expr *e) { 12386 Loc = e->getExprLoc(); 12387 Range = e->getSourceRange(); 12388 } 12389 }; 12390 12391 } // namespace 12392 12393 /// Consider whether capturing the given variable can possibly lead to 12394 /// a retain cycle. 12395 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12396 // In ARC, it's captured strongly iff the variable has __strong 12397 // lifetime. In MRR, it's captured strongly if the variable is 12398 // __block and has an appropriate type. 12399 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12400 return false; 12401 12402 owner.Variable = var; 12403 if (ref) 12404 owner.setLocsFrom(ref); 12405 return true; 12406 } 12407 12408 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12409 while (true) { 12410 e = e->IgnoreParens(); 12411 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12412 switch (cast->getCastKind()) { 12413 case CK_BitCast: 12414 case CK_LValueBitCast: 12415 case CK_LValueToRValue: 12416 case CK_ARCReclaimReturnedObject: 12417 e = cast->getSubExpr(); 12418 continue; 12419 12420 default: 12421 return false; 12422 } 12423 } 12424 12425 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12426 ObjCIvarDecl *ivar = ref->getDecl(); 12427 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12428 return false; 12429 12430 // Try to find a retain cycle in the base. 12431 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12432 return false; 12433 12434 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12435 owner.Indirect = true; 12436 return true; 12437 } 12438 12439 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12440 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12441 if (!var) return false; 12442 return considerVariable(var, ref, owner); 12443 } 12444 12445 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12446 if (member->isArrow()) return false; 12447 12448 // Don't count this as an indirect ownership. 12449 e = member->getBase(); 12450 continue; 12451 } 12452 12453 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12454 // Only pay attention to pseudo-objects on property references. 12455 ObjCPropertyRefExpr *pre 12456 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12457 ->IgnoreParens()); 12458 if (!pre) return false; 12459 if (pre->isImplicitProperty()) return false; 12460 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12461 if (!property->isRetaining() && 12462 !(property->getPropertyIvarDecl() && 12463 property->getPropertyIvarDecl()->getType() 12464 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12465 return false; 12466 12467 owner.Indirect = true; 12468 if (pre->isSuperReceiver()) { 12469 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12470 if (!owner.Variable) 12471 return false; 12472 owner.Loc = pre->getLocation(); 12473 owner.Range = pre->getSourceRange(); 12474 return true; 12475 } 12476 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12477 ->getSourceExpr()); 12478 continue; 12479 } 12480 12481 // Array ivars? 12482 12483 return false; 12484 } 12485 } 12486 12487 namespace { 12488 12489 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12490 ASTContext &Context; 12491 VarDecl *Variable; 12492 Expr *Capturer = nullptr; 12493 bool VarWillBeReased = false; 12494 12495 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12496 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12497 Context(Context), Variable(variable) {} 12498 12499 void VisitDeclRefExpr(DeclRefExpr *ref) { 12500 if (ref->getDecl() == Variable && !Capturer) 12501 Capturer = ref; 12502 } 12503 12504 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12505 if (Capturer) return; 12506 Visit(ref->getBase()); 12507 if (Capturer && ref->isFreeIvar()) 12508 Capturer = ref; 12509 } 12510 12511 void VisitBlockExpr(BlockExpr *block) { 12512 // Look inside nested blocks 12513 if (block->getBlockDecl()->capturesVariable(Variable)) 12514 Visit(block->getBlockDecl()->getBody()); 12515 } 12516 12517 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12518 if (Capturer) return; 12519 if (OVE->getSourceExpr()) 12520 Visit(OVE->getSourceExpr()); 12521 } 12522 12523 void VisitBinaryOperator(BinaryOperator *BinOp) { 12524 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12525 return; 12526 Expr *LHS = BinOp->getLHS(); 12527 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12528 if (DRE->getDecl() != Variable) 12529 return; 12530 if (Expr *RHS = BinOp->getRHS()) { 12531 RHS = RHS->IgnoreParenCasts(); 12532 llvm::APSInt Value; 12533 VarWillBeReased = 12534 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12535 } 12536 } 12537 } 12538 }; 12539 12540 } // namespace 12541 12542 /// Check whether the given argument is a block which captures a 12543 /// variable. 12544 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12545 assert(owner.Variable && owner.Loc.isValid()); 12546 12547 e = e->IgnoreParenCasts(); 12548 12549 // Look through [^{...} copy] and Block_copy(^{...}). 12550 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12551 Selector Cmd = ME->getSelector(); 12552 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12553 e = ME->getInstanceReceiver(); 12554 if (!e) 12555 return nullptr; 12556 e = e->IgnoreParenCasts(); 12557 } 12558 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12559 if (CE->getNumArgs() == 1) { 12560 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12561 if (Fn) { 12562 const IdentifierInfo *FnI = Fn->getIdentifier(); 12563 if (FnI && FnI->isStr("_Block_copy")) { 12564 e = CE->getArg(0)->IgnoreParenCasts(); 12565 } 12566 } 12567 } 12568 } 12569 12570 BlockExpr *block = dyn_cast<BlockExpr>(e); 12571 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12572 return nullptr; 12573 12574 FindCaptureVisitor visitor(S.Context, owner.Variable); 12575 visitor.Visit(block->getBlockDecl()->getBody()); 12576 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12577 } 12578 12579 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12580 RetainCycleOwner &owner) { 12581 assert(capturer); 12582 assert(owner.Variable && owner.Loc.isValid()); 12583 12584 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12585 << owner.Variable << capturer->getSourceRange(); 12586 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12587 << owner.Indirect << owner.Range; 12588 } 12589 12590 /// Check for a keyword selector that starts with the word 'add' or 12591 /// 'set'. 12592 static bool isSetterLikeSelector(Selector sel) { 12593 if (sel.isUnarySelector()) return false; 12594 12595 StringRef str = sel.getNameForSlot(0); 12596 while (!str.empty() && str.front() == '_') str = str.substr(1); 12597 if (str.startswith("set")) 12598 str = str.substr(3); 12599 else if (str.startswith("add")) { 12600 // Specially whitelist 'addOperationWithBlock:'. 12601 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12602 return false; 12603 str = str.substr(3); 12604 } 12605 else 12606 return false; 12607 12608 if (str.empty()) return true; 12609 return !isLowercase(str.front()); 12610 } 12611 12612 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12613 ObjCMessageExpr *Message) { 12614 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12615 Message->getReceiverInterface(), 12616 NSAPI::ClassId_NSMutableArray); 12617 if (!IsMutableArray) { 12618 return None; 12619 } 12620 12621 Selector Sel = Message->getSelector(); 12622 12623 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12624 S.NSAPIObj->getNSArrayMethodKind(Sel); 12625 if (!MKOpt) { 12626 return None; 12627 } 12628 12629 NSAPI::NSArrayMethodKind MK = *MKOpt; 12630 12631 switch (MK) { 12632 case NSAPI::NSMutableArr_addObject: 12633 case NSAPI::NSMutableArr_insertObjectAtIndex: 12634 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12635 return 0; 12636 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12637 return 1; 12638 12639 default: 12640 return None; 12641 } 12642 12643 return None; 12644 } 12645 12646 static 12647 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12648 ObjCMessageExpr *Message) { 12649 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12650 Message->getReceiverInterface(), 12651 NSAPI::ClassId_NSMutableDictionary); 12652 if (!IsMutableDictionary) { 12653 return None; 12654 } 12655 12656 Selector Sel = Message->getSelector(); 12657 12658 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 12659 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 12660 if (!MKOpt) { 12661 return None; 12662 } 12663 12664 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 12665 12666 switch (MK) { 12667 case NSAPI::NSMutableDict_setObjectForKey: 12668 case NSAPI::NSMutableDict_setValueForKey: 12669 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 12670 return 0; 12671 12672 default: 12673 return None; 12674 } 12675 12676 return None; 12677 } 12678 12679 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 12680 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 12681 Message->getReceiverInterface(), 12682 NSAPI::ClassId_NSMutableSet); 12683 12684 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 12685 Message->getReceiverInterface(), 12686 NSAPI::ClassId_NSMutableOrderedSet); 12687 if (!IsMutableSet && !IsMutableOrderedSet) { 12688 return None; 12689 } 12690 12691 Selector Sel = Message->getSelector(); 12692 12693 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 12694 if (!MKOpt) { 12695 return None; 12696 } 12697 12698 NSAPI::NSSetMethodKind MK = *MKOpt; 12699 12700 switch (MK) { 12701 case NSAPI::NSMutableSet_addObject: 12702 case NSAPI::NSOrderedSet_setObjectAtIndex: 12703 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 12704 case NSAPI::NSOrderedSet_insertObjectAtIndex: 12705 return 0; 12706 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 12707 return 1; 12708 } 12709 12710 return None; 12711 } 12712 12713 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 12714 if (!Message->isInstanceMessage()) { 12715 return; 12716 } 12717 12718 Optional<int> ArgOpt; 12719 12720 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 12721 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 12722 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 12723 return; 12724 } 12725 12726 int ArgIndex = *ArgOpt; 12727 12728 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 12729 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 12730 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 12731 } 12732 12733 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 12734 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12735 if (ArgRE->isObjCSelfExpr()) { 12736 Diag(Message->getSourceRange().getBegin(), 12737 diag::warn_objc_circular_container) 12738 << ArgRE->getDecl() << StringRef("'super'"); 12739 } 12740 } 12741 } else { 12742 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 12743 12744 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 12745 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 12746 } 12747 12748 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 12749 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 12750 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 12751 ValueDecl *Decl = ReceiverRE->getDecl(); 12752 Diag(Message->getSourceRange().getBegin(), 12753 diag::warn_objc_circular_container) 12754 << Decl << Decl; 12755 if (!ArgRE->isObjCSelfExpr()) { 12756 Diag(Decl->getLocation(), 12757 diag::note_objc_circular_container_declared_here) 12758 << Decl; 12759 } 12760 } 12761 } 12762 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 12763 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 12764 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 12765 ObjCIvarDecl *Decl = IvarRE->getDecl(); 12766 Diag(Message->getSourceRange().getBegin(), 12767 diag::warn_objc_circular_container) 12768 << Decl << Decl; 12769 Diag(Decl->getLocation(), 12770 diag::note_objc_circular_container_declared_here) 12771 << Decl; 12772 } 12773 } 12774 } 12775 } 12776 } 12777 12778 /// Check a message send to see if it's likely to cause a retain cycle. 12779 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 12780 // Only check instance methods whose selector looks like a setter. 12781 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 12782 return; 12783 12784 // Try to find a variable that the receiver is strongly owned by. 12785 RetainCycleOwner owner; 12786 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 12787 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 12788 return; 12789 } else { 12790 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 12791 owner.Variable = getCurMethodDecl()->getSelfDecl(); 12792 owner.Loc = msg->getSuperLoc(); 12793 owner.Range = msg->getSuperLoc(); 12794 } 12795 12796 // Check whether the receiver is captured by any of the arguments. 12797 const ObjCMethodDecl *MD = msg->getMethodDecl(); 12798 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 12799 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 12800 // noescape blocks should not be retained by the method. 12801 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 12802 continue; 12803 return diagnoseRetainCycle(*this, capturer, owner); 12804 } 12805 } 12806 } 12807 12808 /// Check a property assign to see if it's likely to cause a retain cycle. 12809 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 12810 RetainCycleOwner owner; 12811 if (!findRetainCycleOwner(*this, receiver, owner)) 12812 return; 12813 12814 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 12815 diagnoseRetainCycle(*this, capturer, owner); 12816 } 12817 12818 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 12819 RetainCycleOwner Owner; 12820 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 12821 return; 12822 12823 // Because we don't have an expression for the variable, we have to set the 12824 // location explicitly here. 12825 Owner.Loc = Var->getLocation(); 12826 Owner.Range = Var->getSourceRange(); 12827 12828 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 12829 diagnoseRetainCycle(*this, Capturer, Owner); 12830 } 12831 12832 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 12833 Expr *RHS, bool isProperty) { 12834 // Check if RHS is an Objective-C object literal, which also can get 12835 // immediately zapped in a weak reference. Note that we explicitly 12836 // allow ObjCStringLiterals, since those are designed to never really die. 12837 RHS = RHS->IgnoreParenImpCasts(); 12838 12839 // This enum needs to match with the 'select' in 12840 // warn_objc_arc_literal_assign (off-by-1). 12841 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 12842 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 12843 return false; 12844 12845 S.Diag(Loc, diag::warn_arc_literal_assign) 12846 << (unsigned) Kind 12847 << (isProperty ? 0 : 1) 12848 << RHS->getSourceRange(); 12849 12850 return true; 12851 } 12852 12853 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 12854 Qualifiers::ObjCLifetime LT, 12855 Expr *RHS, bool isProperty) { 12856 // Strip off any implicit cast added to get to the one ARC-specific. 12857 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12858 if (cast->getCastKind() == CK_ARCConsumeObject) { 12859 S.Diag(Loc, diag::warn_arc_retained_assign) 12860 << (LT == Qualifiers::OCL_ExplicitNone) 12861 << (isProperty ? 0 : 1) 12862 << RHS->getSourceRange(); 12863 return true; 12864 } 12865 RHS = cast->getSubExpr(); 12866 } 12867 12868 if (LT == Qualifiers::OCL_Weak && 12869 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 12870 return true; 12871 12872 return false; 12873 } 12874 12875 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 12876 QualType LHS, Expr *RHS) { 12877 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 12878 12879 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 12880 return false; 12881 12882 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 12883 return true; 12884 12885 return false; 12886 } 12887 12888 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 12889 Expr *LHS, Expr *RHS) { 12890 QualType LHSType; 12891 // PropertyRef on LHS type need be directly obtained from 12892 // its declaration as it has a PseudoType. 12893 ObjCPropertyRefExpr *PRE 12894 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 12895 if (PRE && !PRE->isImplicitProperty()) { 12896 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12897 if (PD) 12898 LHSType = PD->getType(); 12899 } 12900 12901 if (LHSType.isNull()) 12902 LHSType = LHS->getType(); 12903 12904 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 12905 12906 if (LT == Qualifiers::OCL_Weak) { 12907 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 12908 getCurFunction()->markSafeWeakUse(LHS); 12909 } 12910 12911 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 12912 return; 12913 12914 // FIXME. Check for other life times. 12915 if (LT != Qualifiers::OCL_None) 12916 return; 12917 12918 if (PRE) { 12919 if (PRE->isImplicitProperty()) 12920 return; 12921 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 12922 if (!PD) 12923 return; 12924 12925 unsigned Attributes = PD->getPropertyAttributes(); 12926 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 12927 // when 'assign' attribute was not explicitly specified 12928 // by user, ignore it and rely on property type itself 12929 // for lifetime info. 12930 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 12931 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 12932 LHSType->isObjCRetainableType()) 12933 return; 12934 12935 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 12936 if (cast->getCastKind() == CK_ARCConsumeObject) { 12937 Diag(Loc, diag::warn_arc_retained_property_assign) 12938 << RHS->getSourceRange(); 12939 return; 12940 } 12941 RHS = cast->getSubExpr(); 12942 } 12943 } 12944 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 12945 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 12946 return; 12947 } 12948 } 12949 } 12950 12951 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 12952 12953 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 12954 SourceLocation StmtLoc, 12955 const NullStmt *Body) { 12956 // Do not warn if the body is a macro that expands to nothing, e.g: 12957 // 12958 // #define CALL(x) 12959 // if (condition) 12960 // CALL(0); 12961 if (Body->hasLeadingEmptyMacro()) 12962 return false; 12963 12964 // Get line numbers of statement and body. 12965 bool StmtLineInvalid; 12966 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 12967 &StmtLineInvalid); 12968 if (StmtLineInvalid) 12969 return false; 12970 12971 bool BodyLineInvalid; 12972 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 12973 &BodyLineInvalid); 12974 if (BodyLineInvalid) 12975 return false; 12976 12977 // Warn if null statement and body are on the same line. 12978 if (StmtLine != BodyLine) 12979 return false; 12980 12981 return true; 12982 } 12983 12984 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 12985 const Stmt *Body, 12986 unsigned DiagID) { 12987 // Since this is a syntactic check, don't emit diagnostic for template 12988 // instantiations, this just adds noise. 12989 if (CurrentInstantiationScope) 12990 return; 12991 12992 // The body should be a null statement. 12993 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 12994 if (!NBody) 12995 return; 12996 12997 // Do the usual checks. 12998 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 12999 return; 13000 13001 Diag(NBody->getSemiLoc(), DiagID); 13002 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13003 } 13004 13005 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13006 const Stmt *PossibleBody) { 13007 assert(!CurrentInstantiationScope); // Ensured by caller 13008 13009 SourceLocation StmtLoc; 13010 const Stmt *Body; 13011 unsigned DiagID; 13012 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13013 StmtLoc = FS->getRParenLoc(); 13014 Body = FS->getBody(); 13015 DiagID = diag::warn_empty_for_body; 13016 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13017 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13018 Body = WS->getBody(); 13019 DiagID = diag::warn_empty_while_body; 13020 } else 13021 return; // Neither `for' nor `while'. 13022 13023 // The body should be a null statement. 13024 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13025 if (!NBody) 13026 return; 13027 13028 // Skip expensive checks if diagnostic is disabled. 13029 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13030 return; 13031 13032 // Do the usual checks. 13033 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13034 return; 13035 13036 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13037 // noise level low, emit diagnostics only if for/while is followed by a 13038 // CompoundStmt, e.g.: 13039 // for (int i = 0; i < n; i++); 13040 // { 13041 // a(i); 13042 // } 13043 // or if for/while is followed by a statement with more indentation 13044 // than for/while itself: 13045 // for (int i = 0; i < n; i++); 13046 // a(i); 13047 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13048 if (!ProbableTypo) { 13049 bool BodyColInvalid; 13050 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13051 PossibleBody->getBeginLoc(), &BodyColInvalid); 13052 if (BodyColInvalid) 13053 return; 13054 13055 bool StmtColInvalid; 13056 unsigned StmtCol = 13057 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13058 if (StmtColInvalid) 13059 return; 13060 13061 if (BodyCol > StmtCol) 13062 ProbableTypo = true; 13063 } 13064 13065 if (ProbableTypo) { 13066 Diag(NBody->getSemiLoc(), DiagID); 13067 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13068 } 13069 } 13070 13071 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13072 13073 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13074 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13075 SourceLocation OpLoc) { 13076 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13077 return; 13078 13079 if (inTemplateInstantiation()) 13080 return; 13081 13082 // Strip parens and casts away. 13083 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13084 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13085 13086 // Check for a call expression 13087 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13088 if (!CE || CE->getNumArgs() != 1) 13089 return; 13090 13091 // Check for a call to std::move 13092 if (!CE->isCallToStdMove()) 13093 return; 13094 13095 // Get argument from std::move 13096 RHSExpr = CE->getArg(0); 13097 13098 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13099 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13100 13101 // Two DeclRefExpr's, check that the decls are the same. 13102 if (LHSDeclRef && RHSDeclRef) { 13103 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13104 return; 13105 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13106 RHSDeclRef->getDecl()->getCanonicalDecl()) 13107 return; 13108 13109 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13110 << LHSExpr->getSourceRange() 13111 << RHSExpr->getSourceRange(); 13112 return; 13113 } 13114 13115 // Member variables require a different approach to check for self moves. 13116 // MemberExpr's are the same if every nested MemberExpr refers to the same 13117 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13118 // the base Expr's are CXXThisExpr's. 13119 const Expr *LHSBase = LHSExpr; 13120 const Expr *RHSBase = RHSExpr; 13121 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13122 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13123 if (!LHSME || !RHSME) 13124 return; 13125 13126 while (LHSME && RHSME) { 13127 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13128 RHSME->getMemberDecl()->getCanonicalDecl()) 13129 return; 13130 13131 LHSBase = LHSME->getBase(); 13132 RHSBase = RHSME->getBase(); 13133 LHSME = dyn_cast<MemberExpr>(LHSBase); 13134 RHSME = dyn_cast<MemberExpr>(RHSBase); 13135 } 13136 13137 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13138 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13139 if (LHSDeclRef && RHSDeclRef) { 13140 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13141 return; 13142 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13143 RHSDeclRef->getDecl()->getCanonicalDecl()) 13144 return; 13145 13146 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13147 << LHSExpr->getSourceRange() 13148 << RHSExpr->getSourceRange(); 13149 return; 13150 } 13151 13152 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13153 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13154 << LHSExpr->getSourceRange() 13155 << RHSExpr->getSourceRange(); 13156 } 13157 13158 //===--- Layout compatibility ----------------------------------------------// 13159 13160 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13161 13162 /// Check if two enumeration types are layout-compatible. 13163 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13164 // C++11 [dcl.enum] p8: 13165 // Two enumeration types are layout-compatible if they have the same 13166 // underlying type. 13167 return ED1->isComplete() && ED2->isComplete() && 13168 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13169 } 13170 13171 /// Check if two fields are layout-compatible. 13172 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13173 FieldDecl *Field2) { 13174 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13175 return false; 13176 13177 if (Field1->isBitField() != Field2->isBitField()) 13178 return false; 13179 13180 if (Field1->isBitField()) { 13181 // Make sure that the bit-fields are the same length. 13182 unsigned Bits1 = Field1->getBitWidthValue(C); 13183 unsigned Bits2 = Field2->getBitWidthValue(C); 13184 13185 if (Bits1 != Bits2) 13186 return false; 13187 } 13188 13189 return true; 13190 } 13191 13192 /// Check if two standard-layout structs are layout-compatible. 13193 /// (C++11 [class.mem] p17) 13194 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13195 RecordDecl *RD2) { 13196 // If both records are C++ classes, check that base classes match. 13197 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13198 // If one of records is a CXXRecordDecl we are in C++ mode, 13199 // thus the other one is a CXXRecordDecl, too. 13200 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13201 // Check number of base classes. 13202 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13203 return false; 13204 13205 // Check the base classes. 13206 for (CXXRecordDecl::base_class_const_iterator 13207 Base1 = D1CXX->bases_begin(), 13208 BaseEnd1 = D1CXX->bases_end(), 13209 Base2 = D2CXX->bases_begin(); 13210 Base1 != BaseEnd1; 13211 ++Base1, ++Base2) { 13212 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13213 return false; 13214 } 13215 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13216 // If only RD2 is a C++ class, it should have zero base classes. 13217 if (D2CXX->getNumBases() > 0) 13218 return false; 13219 } 13220 13221 // Check the fields. 13222 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13223 Field2End = RD2->field_end(), 13224 Field1 = RD1->field_begin(), 13225 Field1End = RD1->field_end(); 13226 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13227 if (!isLayoutCompatible(C, *Field1, *Field2)) 13228 return false; 13229 } 13230 if (Field1 != Field1End || Field2 != Field2End) 13231 return false; 13232 13233 return true; 13234 } 13235 13236 /// Check if two standard-layout unions are layout-compatible. 13237 /// (C++11 [class.mem] p18) 13238 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13239 RecordDecl *RD2) { 13240 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13241 for (auto *Field2 : RD2->fields()) 13242 UnmatchedFields.insert(Field2); 13243 13244 for (auto *Field1 : RD1->fields()) { 13245 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13246 I = UnmatchedFields.begin(), 13247 E = UnmatchedFields.end(); 13248 13249 for ( ; I != E; ++I) { 13250 if (isLayoutCompatible(C, Field1, *I)) { 13251 bool Result = UnmatchedFields.erase(*I); 13252 (void) Result; 13253 assert(Result); 13254 break; 13255 } 13256 } 13257 if (I == E) 13258 return false; 13259 } 13260 13261 return UnmatchedFields.empty(); 13262 } 13263 13264 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13265 RecordDecl *RD2) { 13266 if (RD1->isUnion() != RD2->isUnion()) 13267 return false; 13268 13269 if (RD1->isUnion()) 13270 return isLayoutCompatibleUnion(C, RD1, RD2); 13271 else 13272 return isLayoutCompatibleStruct(C, RD1, RD2); 13273 } 13274 13275 /// Check if two types are layout-compatible in C++11 sense. 13276 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13277 if (T1.isNull() || T2.isNull()) 13278 return false; 13279 13280 // C++11 [basic.types] p11: 13281 // If two types T1 and T2 are the same type, then T1 and T2 are 13282 // layout-compatible types. 13283 if (C.hasSameType(T1, T2)) 13284 return true; 13285 13286 T1 = T1.getCanonicalType().getUnqualifiedType(); 13287 T2 = T2.getCanonicalType().getUnqualifiedType(); 13288 13289 const Type::TypeClass TC1 = T1->getTypeClass(); 13290 const Type::TypeClass TC2 = T2->getTypeClass(); 13291 13292 if (TC1 != TC2) 13293 return false; 13294 13295 if (TC1 == Type::Enum) { 13296 return isLayoutCompatible(C, 13297 cast<EnumType>(T1)->getDecl(), 13298 cast<EnumType>(T2)->getDecl()); 13299 } else if (TC1 == Type::Record) { 13300 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13301 return false; 13302 13303 return isLayoutCompatible(C, 13304 cast<RecordType>(T1)->getDecl(), 13305 cast<RecordType>(T2)->getDecl()); 13306 } 13307 13308 return false; 13309 } 13310 13311 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13312 13313 /// Given a type tag expression find the type tag itself. 13314 /// 13315 /// \param TypeExpr Type tag expression, as it appears in user's code. 13316 /// 13317 /// \param VD Declaration of an identifier that appears in a type tag. 13318 /// 13319 /// \param MagicValue Type tag magic value. 13320 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13321 const ValueDecl **VD, uint64_t *MagicValue) { 13322 while(true) { 13323 if (!TypeExpr) 13324 return false; 13325 13326 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13327 13328 switch (TypeExpr->getStmtClass()) { 13329 case Stmt::UnaryOperatorClass: { 13330 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13331 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13332 TypeExpr = UO->getSubExpr(); 13333 continue; 13334 } 13335 return false; 13336 } 13337 13338 case Stmt::DeclRefExprClass: { 13339 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13340 *VD = DRE->getDecl(); 13341 return true; 13342 } 13343 13344 case Stmt::IntegerLiteralClass: { 13345 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13346 llvm::APInt MagicValueAPInt = IL->getValue(); 13347 if (MagicValueAPInt.getActiveBits() <= 64) { 13348 *MagicValue = MagicValueAPInt.getZExtValue(); 13349 return true; 13350 } else 13351 return false; 13352 } 13353 13354 case Stmt::BinaryConditionalOperatorClass: 13355 case Stmt::ConditionalOperatorClass: { 13356 const AbstractConditionalOperator *ACO = 13357 cast<AbstractConditionalOperator>(TypeExpr); 13358 bool Result; 13359 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13360 if (Result) 13361 TypeExpr = ACO->getTrueExpr(); 13362 else 13363 TypeExpr = ACO->getFalseExpr(); 13364 continue; 13365 } 13366 return false; 13367 } 13368 13369 case Stmt::BinaryOperatorClass: { 13370 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13371 if (BO->getOpcode() == BO_Comma) { 13372 TypeExpr = BO->getRHS(); 13373 continue; 13374 } 13375 return false; 13376 } 13377 13378 default: 13379 return false; 13380 } 13381 } 13382 } 13383 13384 /// Retrieve the C type corresponding to type tag TypeExpr. 13385 /// 13386 /// \param TypeExpr Expression that specifies a type tag. 13387 /// 13388 /// \param MagicValues Registered magic values. 13389 /// 13390 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13391 /// kind. 13392 /// 13393 /// \param TypeInfo Information about the corresponding C type. 13394 /// 13395 /// \returns true if the corresponding C type was found. 13396 static bool GetMatchingCType( 13397 const IdentifierInfo *ArgumentKind, 13398 const Expr *TypeExpr, const ASTContext &Ctx, 13399 const llvm::DenseMap<Sema::TypeTagMagicValue, 13400 Sema::TypeTagData> *MagicValues, 13401 bool &FoundWrongKind, 13402 Sema::TypeTagData &TypeInfo) { 13403 FoundWrongKind = false; 13404 13405 // Variable declaration that has type_tag_for_datatype attribute. 13406 const ValueDecl *VD = nullptr; 13407 13408 uint64_t MagicValue; 13409 13410 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13411 return false; 13412 13413 if (VD) { 13414 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13415 if (I->getArgumentKind() != ArgumentKind) { 13416 FoundWrongKind = true; 13417 return false; 13418 } 13419 TypeInfo.Type = I->getMatchingCType(); 13420 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13421 TypeInfo.MustBeNull = I->getMustBeNull(); 13422 return true; 13423 } 13424 return false; 13425 } 13426 13427 if (!MagicValues) 13428 return false; 13429 13430 llvm::DenseMap<Sema::TypeTagMagicValue, 13431 Sema::TypeTagData>::const_iterator I = 13432 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13433 if (I == MagicValues->end()) 13434 return false; 13435 13436 TypeInfo = I->second; 13437 return true; 13438 } 13439 13440 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13441 uint64_t MagicValue, QualType Type, 13442 bool LayoutCompatible, 13443 bool MustBeNull) { 13444 if (!TypeTagForDatatypeMagicValues) 13445 TypeTagForDatatypeMagicValues.reset( 13446 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13447 13448 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13449 (*TypeTagForDatatypeMagicValues)[Magic] = 13450 TypeTagData(Type, LayoutCompatible, MustBeNull); 13451 } 13452 13453 static bool IsSameCharType(QualType T1, QualType T2) { 13454 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13455 if (!BT1) 13456 return false; 13457 13458 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13459 if (!BT2) 13460 return false; 13461 13462 BuiltinType::Kind T1Kind = BT1->getKind(); 13463 BuiltinType::Kind T2Kind = BT2->getKind(); 13464 13465 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13466 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13467 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13468 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13469 } 13470 13471 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13472 const ArrayRef<const Expr *> ExprArgs, 13473 SourceLocation CallSiteLoc) { 13474 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13475 bool IsPointerAttr = Attr->getIsPointer(); 13476 13477 // Retrieve the argument representing the 'type_tag'. 13478 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13479 if (TypeTagIdxAST >= ExprArgs.size()) { 13480 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13481 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13482 return; 13483 } 13484 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13485 bool FoundWrongKind; 13486 TypeTagData TypeInfo; 13487 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13488 TypeTagForDatatypeMagicValues.get(), 13489 FoundWrongKind, TypeInfo)) { 13490 if (FoundWrongKind) 13491 Diag(TypeTagExpr->getExprLoc(), 13492 diag::warn_type_tag_for_datatype_wrong_kind) 13493 << TypeTagExpr->getSourceRange(); 13494 return; 13495 } 13496 13497 // Retrieve the argument representing the 'arg_idx'. 13498 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13499 if (ArgumentIdxAST >= ExprArgs.size()) { 13500 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13501 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13502 return; 13503 } 13504 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13505 if (IsPointerAttr) { 13506 // Skip implicit cast of pointer to `void *' (as a function argument). 13507 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13508 if (ICE->getType()->isVoidPointerType() && 13509 ICE->getCastKind() == CK_BitCast) 13510 ArgumentExpr = ICE->getSubExpr(); 13511 } 13512 QualType ArgumentType = ArgumentExpr->getType(); 13513 13514 // Passing a `void*' pointer shouldn't trigger a warning. 13515 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13516 return; 13517 13518 if (TypeInfo.MustBeNull) { 13519 // Type tag with matching void type requires a null pointer. 13520 if (!ArgumentExpr->isNullPointerConstant(Context, 13521 Expr::NPC_ValueDependentIsNotNull)) { 13522 Diag(ArgumentExpr->getExprLoc(), 13523 diag::warn_type_safety_null_pointer_required) 13524 << ArgumentKind->getName() 13525 << ArgumentExpr->getSourceRange() 13526 << TypeTagExpr->getSourceRange(); 13527 } 13528 return; 13529 } 13530 13531 QualType RequiredType = TypeInfo.Type; 13532 if (IsPointerAttr) 13533 RequiredType = Context.getPointerType(RequiredType); 13534 13535 bool mismatch = false; 13536 if (!TypeInfo.LayoutCompatible) { 13537 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13538 13539 // C++11 [basic.fundamental] p1: 13540 // Plain char, signed char, and unsigned char are three distinct types. 13541 // 13542 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13543 // char' depending on the current char signedness mode. 13544 if (mismatch) 13545 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13546 RequiredType->getPointeeType())) || 13547 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13548 mismatch = false; 13549 } else 13550 if (IsPointerAttr) 13551 mismatch = !isLayoutCompatible(Context, 13552 ArgumentType->getPointeeType(), 13553 RequiredType->getPointeeType()); 13554 else 13555 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13556 13557 if (mismatch) 13558 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13559 << ArgumentType << ArgumentKind 13560 << TypeInfo.LayoutCompatible << RequiredType 13561 << ArgumentExpr->getSourceRange() 13562 << TypeTagExpr->getSourceRange(); 13563 } 13564 13565 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13566 CharUnits Alignment) { 13567 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13568 } 13569 13570 void Sema::DiagnoseMisalignedMembers() { 13571 for (MisalignedMember &m : MisalignedMembers) { 13572 const NamedDecl *ND = m.RD; 13573 if (ND->getName().empty()) { 13574 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13575 ND = TD; 13576 } 13577 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13578 << m.MD << ND << m.E->getSourceRange(); 13579 } 13580 MisalignedMembers.clear(); 13581 } 13582 13583 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13584 E = E->IgnoreParens(); 13585 if (!T->isPointerType() && !T->isIntegerType()) 13586 return; 13587 if (isa<UnaryOperator>(E) && 13588 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13589 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13590 if (isa<MemberExpr>(Op)) { 13591 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(), 13592 MisalignedMember(Op)); 13593 if (MA != MisalignedMembers.end() && 13594 (T->isIntegerType() || 13595 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13596 Context.getTypeAlignInChars( 13597 T->getPointeeType()) <= MA->Alignment)))) 13598 MisalignedMembers.erase(MA); 13599 } 13600 } 13601 } 13602 13603 void Sema::RefersToMemberWithReducedAlignment( 13604 Expr *E, 13605 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13606 Action) { 13607 const auto *ME = dyn_cast<MemberExpr>(E); 13608 if (!ME) 13609 return; 13610 13611 // No need to check expressions with an __unaligned-qualified type. 13612 if (E->getType().getQualifiers().hasUnaligned()) 13613 return; 13614 13615 // For a chain of MemberExpr like "a.b.c.d" this list 13616 // will keep FieldDecl's like [d, c, b]. 13617 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13618 const MemberExpr *TopME = nullptr; 13619 bool AnyIsPacked = false; 13620 do { 13621 QualType BaseType = ME->getBase()->getType(); 13622 if (ME->isArrow()) 13623 BaseType = BaseType->getPointeeType(); 13624 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13625 if (RD->isInvalidDecl()) 13626 return; 13627 13628 ValueDecl *MD = ME->getMemberDecl(); 13629 auto *FD = dyn_cast<FieldDecl>(MD); 13630 // We do not care about non-data members. 13631 if (!FD || FD->isInvalidDecl()) 13632 return; 13633 13634 AnyIsPacked = 13635 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13636 ReverseMemberChain.push_back(FD); 13637 13638 TopME = ME; 13639 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13640 } while (ME); 13641 assert(TopME && "We did not compute a topmost MemberExpr!"); 13642 13643 // Not the scope of this diagnostic. 13644 if (!AnyIsPacked) 13645 return; 13646 13647 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13648 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13649 // TODO: The innermost base of the member expression may be too complicated. 13650 // For now, just disregard these cases. This is left for future 13651 // improvement. 13652 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13653 return; 13654 13655 // Alignment expected by the whole expression. 13656 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13657 13658 // No need to do anything else with this case. 13659 if (ExpectedAlignment.isOne()) 13660 return; 13661 13662 // Synthesize offset of the whole access. 13663 CharUnits Offset; 13664 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 13665 I++) { 13666 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 13667 } 13668 13669 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 13670 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 13671 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 13672 13673 // The base expression of the innermost MemberExpr may give 13674 // stronger guarantees than the class containing the member. 13675 if (DRE && !TopME->isArrow()) { 13676 const ValueDecl *VD = DRE->getDecl(); 13677 if (!VD->getType()->isReferenceType()) 13678 CompleteObjectAlignment = 13679 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 13680 } 13681 13682 // Check if the synthesized offset fulfills the alignment. 13683 if (Offset % ExpectedAlignment != 0 || 13684 // It may fulfill the offset it but the effective alignment may still be 13685 // lower than the expected expression alignment. 13686 CompleteObjectAlignment < ExpectedAlignment) { 13687 // If this happens, we want to determine a sensible culprit of this. 13688 // Intuitively, watching the chain of member expressions from right to 13689 // left, we start with the required alignment (as required by the field 13690 // type) but some packed attribute in that chain has reduced the alignment. 13691 // It may happen that another packed structure increases it again. But if 13692 // we are here such increase has not been enough. So pointing the first 13693 // FieldDecl that either is packed or else its RecordDecl is, 13694 // seems reasonable. 13695 FieldDecl *FD = nullptr; 13696 CharUnits Alignment; 13697 for (FieldDecl *FDI : ReverseMemberChain) { 13698 if (FDI->hasAttr<PackedAttr>() || 13699 FDI->getParent()->hasAttr<PackedAttr>()) { 13700 FD = FDI; 13701 Alignment = std::min( 13702 Context.getTypeAlignInChars(FD->getType()), 13703 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 13704 break; 13705 } 13706 } 13707 assert(FD && "We did not find a packed FieldDecl!"); 13708 Action(E, FD->getParent(), FD, Alignment); 13709 } 13710 } 13711 13712 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 13713 using namespace std::placeholders; 13714 13715 RefersToMemberWithReducedAlignment( 13716 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 13717 _2, _3, _4)); 13718 } 13719