1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.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/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/SaveAndRestore.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 bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 240 if (checkArgCount(S, BuiltinCall, 2)) 241 return true; 242 243 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 244 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 245 Expr *Call = BuiltinCall->getArg(0); 246 Expr *Chain = BuiltinCall->getArg(1); 247 248 if (Call->getStmtClass() != Stmt::CallExprClass) { 249 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 250 << Call->getSourceRange(); 251 return true; 252 } 253 254 auto CE = cast<CallExpr>(Call); 255 if (CE->getCallee()->getType()->isBlockPointerType()) { 256 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 257 << Call->getSourceRange(); 258 return true; 259 } 260 261 const Decl *TargetDecl = CE->getCalleeDecl(); 262 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 263 if (FD->getBuiltinID()) { 264 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 265 << Call->getSourceRange(); 266 return true; 267 } 268 269 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 270 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 271 << Call->getSourceRange(); 272 return true; 273 } 274 275 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 276 if (ChainResult.isInvalid()) 277 return true; 278 if (!ChainResult.get()->getType()->isPointerType()) { 279 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 280 << Chain->getSourceRange(); 281 return true; 282 } 283 284 QualType ReturnTy = CE->getCallReturnType(S.Context); 285 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 286 QualType BuiltinTy = S.Context.getFunctionType( 287 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 288 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 289 290 Builtin = 291 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 292 293 BuiltinCall->setType(CE->getType()); 294 BuiltinCall->setValueKind(CE->getValueKind()); 295 BuiltinCall->setObjectKind(CE->getObjectKind()); 296 BuiltinCall->setCallee(Builtin); 297 BuiltinCall->setArg(1, ChainResult.get()); 298 299 return false; 300 } 301 302 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 303 /// __builtin_*_chk function, then use the object size argument specified in the 304 /// source. Otherwise, infer the object size using __builtin_object_size. 305 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 306 CallExpr *TheCall) { 307 // FIXME: There are some more useful checks we could be doing here: 308 // - Analyze the format string of sprintf to see how much of buffer is used. 309 // - Evaluate strlen of strcpy arguments, use as object size. 310 311 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 312 isConstantEvaluated()) 313 return; 314 315 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 316 if (!BuiltinID) 317 return; 318 319 unsigned DiagID = 0; 320 bool IsChkVariant = false; 321 unsigned SizeIndex, ObjectIndex; 322 switch (BuiltinID) { 323 default: 324 return; 325 case Builtin::BI__builtin___memcpy_chk: 326 case Builtin::BI__builtin___memmove_chk: 327 case Builtin::BI__builtin___memset_chk: 328 case Builtin::BI__builtin___strlcat_chk: 329 case Builtin::BI__builtin___strlcpy_chk: 330 case Builtin::BI__builtin___strncat_chk: 331 case Builtin::BI__builtin___strncpy_chk: 332 case Builtin::BI__builtin___stpncpy_chk: 333 case Builtin::BI__builtin___memccpy_chk: { 334 DiagID = diag::warn_builtin_chk_overflow; 335 IsChkVariant = true; 336 SizeIndex = TheCall->getNumArgs() - 2; 337 ObjectIndex = TheCall->getNumArgs() - 1; 338 break; 339 } 340 341 case Builtin::BI__builtin___snprintf_chk: 342 case Builtin::BI__builtin___vsnprintf_chk: { 343 DiagID = diag::warn_builtin_chk_overflow; 344 IsChkVariant = true; 345 SizeIndex = 1; 346 ObjectIndex = 3; 347 break; 348 } 349 350 case Builtin::BIstrncat: 351 case Builtin::BI__builtin_strncat: 352 case Builtin::BIstrncpy: 353 case Builtin::BI__builtin_strncpy: 354 case Builtin::BIstpncpy: 355 case Builtin::BI__builtin_stpncpy: { 356 // Whether these functions overflow depends on the runtime strlen of the 357 // string, not just the buffer size, so emitting the "always overflow" 358 // diagnostic isn't quite right. We should still diagnose passing a buffer 359 // size larger than the destination buffer though; this is a runtime abort 360 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 361 DiagID = diag::warn_fortify_source_size_mismatch; 362 SizeIndex = TheCall->getNumArgs() - 1; 363 ObjectIndex = 0; 364 break; 365 } 366 367 case Builtin::BImemcpy: 368 case Builtin::BI__builtin_memcpy: 369 case Builtin::BImemmove: 370 case Builtin::BI__builtin_memmove: 371 case Builtin::BImemset: 372 case Builtin::BI__builtin_memset: { 373 DiagID = diag::warn_fortify_source_overflow; 374 SizeIndex = TheCall->getNumArgs() - 1; 375 ObjectIndex = 0; 376 break; 377 } 378 case Builtin::BIsnprintf: 379 case Builtin::BI__builtin_snprintf: 380 case Builtin::BIvsnprintf: 381 case Builtin::BI__builtin_vsnprintf: { 382 DiagID = diag::warn_fortify_source_size_mismatch; 383 SizeIndex = 1; 384 ObjectIndex = 0; 385 break; 386 } 387 } 388 389 llvm::APSInt ObjectSize; 390 // For __builtin___*_chk, the object size is explicitly provided by the caller 391 // (usually using __builtin_object_size). Use that value to check this call. 392 if (IsChkVariant) { 393 Expr::EvalResult Result; 394 Expr *SizeArg = TheCall->getArg(ObjectIndex); 395 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 396 return; 397 ObjectSize = Result.Val.getInt(); 398 399 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 400 } else { 401 // If the parameter has a pass_object_size attribute, then we should use its 402 // (potentially) more strict checking mode. Otherwise, conservatively assume 403 // type 0. 404 int BOSType = 0; 405 if (const auto *POS = 406 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 407 BOSType = POS->getType(); 408 409 Expr *ObjArg = TheCall->getArg(ObjectIndex); 410 uint64_t Result; 411 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 412 return; 413 // Get the object size in the target's size_t width. 414 const TargetInfo &TI = getASTContext().getTargetInfo(); 415 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 416 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 417 } 418 419 // Evaluate the number of bytes of the object that this call will use. 420 Expr::EvalResult Result; 421 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 422 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 423 return; 424 llvm::APSInt UsedSize = Result.Val.getInt(); 425 426 if (UsedSize.ule(ObjectSize)) 427 return; 428 429 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 430 // Skim off the details of whichever builtin was called to produce a better 431 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 432 if (IsChkVariant) { 433 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 434 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 435 } else if (FunctionName.startswith("__builtin_")) { 436 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 437 } 438 439 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 440 PDiag(DiagID) 441 << FunctionName << ObjectSize.toString(/*Radix=*/10) 442 << UsedSize.toString(/*Radix=*/10)); 443 } 444 445 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 446 Scope::ScopeFlags NeededScopeFlags, 447 unsigned DiagID) { 448 // Scopes aren't available during instantiation. Fortunately, builtin 449 // functions cannot be template args so they cannot be formed through template 450 // instantiation. Therefore checking once during the parse is sufficient. 451 if (SemaRef.inTemplateInstantiation()) 452 return false; 453 454 Scope *S = SemaRef.getCurScope(); 455 while (S && !S->isSEHExceptScope()) 456 S = S->getParent(); 457 if (!S || !(S->getFlags() & NeededScopeFlags)) { 458 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 459 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 460 << DRE->getDecl()->getIdentifier(); 461 return true; 462 } 463 464 return false; 465 } 466 467 static inline bool isBlockPointer(Expr *Arg) { 468 return Arg->getType()->isBlockPointerType(); 469 } 470 471 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 472 /// void*, which is a requirement of device side enqueue. 473 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 474 const BlockPointerType *BPT = 475 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 476 ArrayRef<QualType> Params = 477 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 478 unsigned ArgCounter = 0; 479 bool IllegalParams = false; 480 // Iterate through the block parameters until either one is found that is not 481 // a local void*, or the block is valid. 482 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 483 I != E; ++I, ++ArgCounter) { 484 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 485 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 486 LangAS::opencl_local) { 487 // Get the location of the error. If a block literal has been passed 488 // (BlockExpr) then we can point straight to the offending argument, 489 // else we just point to the variable reference. 490 SourceLocation ErrorLoc; 491 if (isa<BlockExpr>(BlockArg)) { 492 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 493 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 494 } else if (isa<DeclRefExpr>(BlockArg)) { 495 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 496 } 497 S.Diag(ErrorLoc, 498 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 499 IllegalParams = true; 500 } 501 } 502 503 return IllegalParams; 504 } 505 506 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 507 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 508 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 509 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 510 return true; 511 } 512 return false; 513 } 514 515 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 516 if (checkArgCount(S, TheCall, 2)) 517 return true; 518 519 if (checkOpenCLSubgroupExt(S, TheCall)) 520 return true; 521 522 // First argument is an ndrange_t type. 523 Expr *NDRangeArg = TheCall->getArg(0); 524 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 525 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 526 << TheCall->getDirectCallee() << "'ndrange_t'"; 527 return true; 528 } 529 530 Expr *BlockArg = TheCall->getArg(1); 531 if (!isBlockPointer(BlockArg)) { 532 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 533 << TheCall->getDirectCallee() << "block"; 534 return true; 535 } 536 return checkOpenCLBlockArgs(S, BlockArg); 537 } 538 539 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 540 /// get_kernel_work_group_size 541 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 542 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 543 if (checkArgCount(S, TheCall, 1)) 544 return true; 545 546 Expr *BlockArg = TheCall->getArg(0); 547 if (!isBlockPointer(BlockArg)) { 548 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 549 << TheCall->getDirectCallee() << "block"; 550 return true; 551 } 552 return checkOpenCLBlockArgs(S, BlockArg); 553 } 554 555 /// Diagnose integer type and any valid implicit conversion to it. 556 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 557 const QualType &IntType); 558 559 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 560 unsigned Start, unsigned End) { 561 bool IllegalParams = false; 562 for (unsigned I = Start; I <= End; ++I) 563 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 564 S.Context.getSizeType()); 565 return IllegalParams; 566 } 567 568 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 569 /// 'local void*' parameter of passed block. 570 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 571 Expr *BlockArg, 572 unsigned NumNonVarArgs) { 573 const BlockPointerType *BPT = 574 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 575 unsigned NumBlockParams = 576 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 577 unsigned TotalNumArgs = TheCall->getNumArgs(); 578 579 // For each argument passed to the block, a corresponding uint needs to 580 // be passed to describe the size of the local memory. 581 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 582 S.Diag(TheCall->getBeginLoc(), 583 diag::err_opencl_enqueue_kernel_local_size_args); 584 return true; 585 } 586 587 // Check that the sizes of the local memory are specified by integers. 588 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 589 TotalNumArgs - 1); 590 } 591 592 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 593 /// overload formats specified in Table 6.13.17.1. 594 /// int enqueue_kernel(queue_t queue, 595 /// kernel_enqueue_flags_t flags, 596 /// const ndrange_t ndrange, 597 /// void (^block)(void)) 598 /// int enqueue_kernel(queue_t queue, 599 /// kernel_enqueue_flags_t flags, 600 /// const ndrange_t ndrange, 601 /// uint num_events_in_wait_list, 602 /// clk_event_t *event_wait_list, 603 /// clk_event_t *event_ret, 604 /// void (^block)(void)) 605 /// int enqueue_kernel(queue_t queue, 606 /// kernel_enqueue_flags_t flags, 607 /// const ndrange_t ndrange, 608 /// void (^block)(local void*, ...), 609 /// uint size0, ...) 610 /// int enqueue_kernel(queue_t queue, 611 /// kernel_enqueue_flags_t flags, 612 /// const ndrange_t ndrange, 613 /// uint num_events_in_wait_list, 614 /// clk_event_t *event_wait_list, 615 /// clk_event_t *event_ret, 616 /// void (^block)(local void*, ...), 617 /// uint size0, ...) 618 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 619 unsigned NumArgs = TheCall->getNumArgs(); 620 621 if (NumArgs < 4) { 622 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 623 return true; 624 } 625 626 Expr *Arg0 = TheCall->getArg(0); 627 Expr *Arg1 = TheCall->getArg(1); 628 Expr *Arg2 = TheCall->getArg(2); 629 Expr *Arg3 = TheCall->getArg(3); 630 631 // First argument always needs to be a queue_t type. 632 if (!Arg0->getType()->isQueueT()) { 633 S.Diag(TheCall->getArg(0)->getBeginLoc(), 634 diag::err_opencl_builtin_expected_type) 635 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 636 return true; 637 } 638 639 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 640 if (!Arg1->getType()->isIntegerType()) { 641 S.Diag(TheCall->getArg(1)->getBeginLoc(), 642 diag::err_opencl_builtin_expected_type) 643 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 644 return true; 645 } 646 647 // Third argument is always an ndrange_t type. 648 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 649 S.Diag(TheCall->getArg(2)->getBeginLoc(), 650 diag::err_opencl_builtin_expected_type) 651 << TheCall->getDirectCallee() << "'ndrange_t'"; 652 return true; 653 } 654 655 // With four arguments, there is only one form that the function could be 656 // called in: no events and no variable arguments. 657 if (NumArgs == 4) { 658 // check that the last argument is the right block type. 659 if (!isBlockPointer(Arg3)) { 660 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 661 << TheCall->getDirectCallee() << "block"; 662 return true; 663 } 664 // we have a block type, check the prototype 665 const BlockPointerType *BPT = 666 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 667 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 668 S.Diag(Arg3->getBeginLoc(), 669 diag::err_opencl_enqueue_kernel_blocks_no_args); 670 return true; 671 } 672 return false; 673 } 674 // we can have block + varargs. 675 if (isBlockPointer(Arg3)) 676 return (checkOpenCLBlockArgs(S, Arg3) || 677 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 678 // last two cases with either exactly 7 args or 7 args and varargs. 679 if (NumArgs >= 7) { 680 // check common block argument. 681 Expr *Arg6 = TheCall->getArg(6); 682 if (!isBlockPointer(Arg6)) { 683 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 684 << TheCall->getDirectCallee() << "block"; 685 return true; 686 } 687 if (checkOpenCLBlockArgs(S, Arg6)) 688 return true; 689 690 // Forth argument has to be any integer type. 691 if (!Arg3->getType()->isIntegerType()) { 692 S.Diag(TheCall->getArg(3)->getBeginLoc(), 693 diag::err_opencl_builtin_expected_type) 694 << TheCall->getDirectCallee() << "integer"; 695 return true; 696 } 697 // check remaining common arguments. 698 Expr *Arg4 = TheCall->getArg(4); 699 Expr *Arg5 = TheCall->getArg(5); 700 701 // Fifth argument is always passed as a pointer to clk_event_t. 702 if (!Arg4->isNullPointerConstant(S.Context, 703 Expr::NPC_ValueDependentIsNotNull) && 704 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 705 S.Diag(TheCall->getArg(4)->getBeginLoc(), 706 diag::err_opencl_builtin_expected_type) 707 << TheCall->getDirectCallee() 708 << S.Context.getPointerType(S.Context.OCLClkEventTy); 709 return true; 710 } 711 712 // Sixth argument is always passed as a pointer to clk_event_t. 713 if (!Arg5->isNullPointerConstant(S.Context, 714 Expr::NPC_ValueDependentIsNotNull) && 715 !(Arg5->getType()->isPointerType() && 716 Arg5->getType()->getPointeeType()->isClkEventT())) { 717 S.Diag(TheCall->getArg(5)->getBeginLoc(), 718 diag::err_opencl_builtin_expected_type) 719 << TheCall->getDirectCallee() 720 << S.Context.getPointerType(S.Context.OCLClkEventTy); 721 return true; 722 } 723 724 if (NumArgs == 7) 725 return false; 726 727 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 728 } 729 730 // None of the specific case has been detected, give generic error 731 S.Diag(TheCall->getBeginLoc(), 732 diag::err_opencl_enqueue_kernel_incorrect_args); 733 return true; 734 } 735 736 /// Returns OpenCL access qual. 737 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 738 return D->getAttr<OpenCLAccessAttr>(); 739 } 740 741 /// Returns true if pipe element type is different from the pointer. 742 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 743 const Expr *Arg0 = Call->getArg(0); 744 // First argument type should always be pipe. 745 if (!Arg0->getType()->isPipeType()) { 746 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 747 << Call->getDirectCallee() << Arg0->getSourceRange(); 748 return true; 749 } 750 OpenCLAccessAttr *AccessQual = 751 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 752 // Validates the access qualifier is compatible with the call. 753 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 754 // read_only and write_only, and assumed to be read_only if no qualifier is 755 // specified. 756 switch (Call->getDirectCallee()->getBuiltinID()) { 757 case Builtin::BIread_pipe: 758 case Builtin::BIreserve_read_pipe: 759 case Builtin::BIcommit_read_pipe: 760 case Builtin::BIwork_group_reserve_read_pipe: 761 case Builtin::BIsub_group_reserve_read_pipe: 762 case Builtin::BIwork_group_commit_read_pipe: 763 case Builtin::BIsub_group_commit_read_pipe: 764 if (!(!AccessQual || AccessQual->isReadOnly())) { 765 S.Diag(Arg0->getBeginLoc(), 766 diag::err_opencl_builtin_pipe_invalid_access_modifier) 767 << "read_only" << Arg0->getSourceRange(); 768 return true; 769 } 770 break; 771 case Builtin::BIwrite_pipe: 772 case Builtin::BIreserve_write_pipe: 773 case Builtin::BIcommit_write_pipe: 774 case Builtin::BIwork_group_reserve_write_pipe: 775 case Builtin::BIsub_group_reserve_write_pipe: 776 case Builtin::BIwork_group_commit_write_pipe: 777 case Builtin::BIsub_group_commit_write_pipe: 778 if (!(AccessQual && AccessQual->isWriteOnly())) { 779 S.Diag(Arg0->getBeginLoc(), 780 diag::err_opencl_builtin_pipe_invalid_access_modifier) 781 << "write_only" << Arg0->getSourceRange(); 782 return true; 783 } 784 break; 785 default: 786 break; 787 } 788 return false; 789 } 790 791 /// Returns true if pipe element type is different from the pointer. 792 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 793 const Expr *Arg0 = Call->getArg(0); 794 const Expr *ArgIdx = Call->getArg(Idx); 795 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 796 const QualType EltTy = PipeTy->getElementType(); 797 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 798 // The Idx argument should be a pointer and the type of the pointer and 799 // the type of pipe element should also be the same. 800 if (!ArgTy || 801 !S.Context.hasSameType( 802 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 803 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 804 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 805 << ArgIdx->getType() << ArgIdx->getSourceRange(); 806 return true; 807 } 808 return false; 809 } 810 811 // Performs semantic analysis for the read/write_pipe call. 812 // \param S Reference to the semantic analyzer. 813 // \param Call A pointer to the builtin call. 814 // \return True if a semantic error has been found, false otherwise. 815 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 816 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 817 // functions have two forms. 818 switch (Call->getNumArgs()) { 819 case 2: 820 if (checkOpenCLPipeArg(S, Call)) 821 return true; 822 // The call with 2 arguments should be 823 // read/write_pipe(pipe T, T*). 824 // Check packet type T. 825 if (checkOpenCLPipePacketType(S, Call, 1)) 826 return true; 827 break; 828 829 case 4: { 830 if (checkOpenCLPipeArg(S, Call)) 831 return true; 832 // The call with 4 arguments should be 833 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 834 // Check reserve_id_t. 835 if (!Call->getArg(1)->getType()->isReserveIDT()) { 836 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 837 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 838 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 839 return true; 840 } 841 842 // Check the index. 843 const Expr *Arg2 = Call->getArg(2); 844 if (!Arg2->getType()->isIntegerType() && 845 !Arg2->getType()->isUnsignedIntegerType()) { 846 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 847 << Call->getDirectCallee() << S.Context.UnsignedIntTy 848 << Arg2->getType() << Arg2->getSourceRange(); 849 return true; 850 } 851 852 // Check packet type T. 853 if (checkOpenCLPipePacketType(S, Call, 3)) 854 return true; 855 } break; 856 default: 857 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 858 << Call->getDirectCallee() << Call->getSourceRange(); 859 return true; 860 } 861 862 return false; 863 } 864 865 // Performs a semantic analysis on the {work_group_/sub_group_ 866 // /_}reserve_{read/write}_pipe 867 // \param S Reference to the semantic analyzer. 868 // \param Call The call to the builtin function to be analyzed. 869 // \return True if a semantic error was found, false otherwise. 870 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 871 if (checkArgCount(S, Call, 2)) 872 return true; 873 874 if (checkOpenCLPipeArg(S, Call)) 875 return true; 876 877 // Check the reserve size. 878 if (!Call->getArg(1)->getType()->isIntegerType() && 879 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 880 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 881 << Call->getDirectCallee() << S.Context.UnsignedIntTy 882 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 883 return true; 884 } 885 886 // Since return type of reserve_read/write_pipe built-in function is 887 // reserve_id_t, which is not defined in the builtin def file , we used int 888 // as return type and need to override the return type of these functions. 889 Call->setType(S.Context.OCLReserveIDTy); 890 891 return false; 892 } 893 894 // Performs a semantic analysis on {work_group_/sub_group_ 895 // /_}commit_{read/write}_pipe 896 // \param S Reference to the semantic analyzer. 897 // \param Call The call to the builtin function to be analyzed. 898 // \return True if a semantic error was found, false otherwise. 899 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 900 if (checkArgCount(S, Call, 2)) 901 return true; 902 903 if (checkOpenCLPipeArg(S, Call)) 904 return true; 905 906 // Check reserve_id_t. 907 if (!Call->getArg(1)->getType()->isReserveIDT()) { 908 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 909 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 910 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 911 return true; 912 } 913 914 return false; 915 } 916 917 // Performs a semantic analysis on the call to built-in Pipe 918 // Query Functions. 919 // \param S Reference to the semantic analyzer. 920 // \param Call The call to the builtin function to be analyzed. 921 // \return True if a semantic error was found, false otherwise. 922 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 923 if (checkArgCount(S, Call, 1)) 924 return true; 925 926 if (!Call->getArg(0)->getType()->isPipeType()) { 927 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 928 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 929 return true; 930 } 931 932 return false; 933 } 934 935 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 936 // Performs semantic analysis for the to_global/local/private call. 937 // \param S Reference to the semantic analyzer. 938 // \param BuiltinID ID of the builtin function. 939 // \param Call A pointer to the builtin call. 940 // \return True if a semantic error has been found, false otherwise. 941 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 942 CallExpr *Call) { 943 if (Call->getNumArgs() != 1) { 944 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 945 << Call->getDirectCallee() << Call->getSourceRange(); 946 return true; 947 } 948 949 auto RT = Call->getArg(0)->getType(); 950 if (!RT->isPointerType() || RT->getPointeeType() 951 .getAddressSpace() == LangAS::opencl_constant) { 952 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 953 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 954 return true; 955 } 956 957 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 958 S.Diag(Call->getArg(0)->getBeginLoc(), 959 diag::warn_opencl_generic_address_space_arg) 960 << Call->getDirectCallee()->getNameInfo().getAsString() 961 << Call->getArg(0)->getSourceRange(); 962 } 963 964 RT = RT->getPointeeType(); 965 auto Qual = RT.getQualifiers(); 966 switch (BuiltinID) { 967 case Builtin::BIto_global: 968 Qual.setAddressSpace(LangAS::opencl_global); 969 break; 970 case Builtin::BIto_local: 971 Qual.setAddressSpace(LangAS::opencl_local); 972 break; 973 case Builtin::BIto_private: 974 Qual.setAddressSpace(LangAS::opencl_private); 975 break; 976 default: 977 llvm_unreachable("Invalid builtin function"); 978 } 979 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 980 RT.getUnqualifiedType(), Qual))); 981 982 return false; 983 } 984 985 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 986 if (checkArgCount(S, TheCall, 1)) 987 return ExprError(); 988 989 // Compute __builtin_launder's parameter type from the argument. 990 // The parameter type is: 991 // * The type of the argument if it's not an array or function type, 992 // Otherwise, 993 // * The decayed argument type. 994 QualType ParamTy = [&]() { 995 QualType ArgTy = TheCall->getArg(0)->getType(); 996 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 997 return S.Context.getPointerType(Ty->getElementType()); 998 if (ArgTy->isFunctionType()) { 999 return S.Context.getPointerType(ArgTy); 1000 } 1001 return ArgTy; 1002 }(); 1003 1004 TheCall->setType(ParamTy); 1005 1006 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1007 if (!ParamTy->isPointerType()) 1008 return 0; 1009 if (ParamTy->isFunctionPointerType()) 1010 return 1; 1011 if (ParamTy->isVoidPointerType()) 1012 return 2; 1013 return llvm::Optional<unsigned>{}; 1014 }(); 1015 if (DiagSelect.hasValue()) { 1016 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1017 << DiagSelect.getValue() << TheCall->getSourceRange(); 1018 return ExprError(); 1019 } 1020 1021 // We either have an incomplete class type, or we have a class template 1022 // whose instantiation has not been forced. Example: 1023 // 1024 // template <class T> struct Foo { T value; }; 1025 // Foo<int> *p = nullptr; 1026 // auto *d = __builtin_launder(p); 1027 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1028 diag::err_incomplete_type)) 1029 return ExprError(); 1030 1031 assert(ParamTy->getPointeeType()->isObjectType() && 1032 "Unhandled non-object pointer case"); 1033 1034 InitializedEntity Entity = 1035 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1036 ExprResult Arg = 1037 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1038 if (Arg.isInvalid()) 1039 return ExprError(); 1040 TheCall->setArg(0, Arg.get()); 1041 1042 return TheCall; 1043 } 1044 1045 // Emit an error and return true if the current architecture is not in the list 1046 // of supported architectures. 1047 static bool 1048 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1049 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1050 llvm::Triple::ArchType CurArch = 1051 S.getASTContext().getTargetInfo().getTriple().getArch(); 1052 if (llvm::is_contained(SupportedArchs, CurArch)) 1053 return false; 1054 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1055 << TheCall->getSourceRange(); 1056 return true; 1057 } 1058 1059 ExprResult 1060 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1061 CallExpr *TheCall) { 1062 ExprResult TheCallResult(TheCall); 1063 1064 // Find out if any arguments are required to be integer constant expressions. 1065 unsigned ICEArguments = 0; 1066 ASTContext::GetBuiltinTypeError Error; 1067 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1068 if (Error != ASTContext::GE_None) 1069 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1070 1071 // If any arguments are required to be ICE's, check and diagnose. 1072 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1073 // Skip arguments not required to be ICE's. 1074 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1075 1076 llvm::APSInt Result; 1077 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1078 return true; 1079 ICEArguments &= ~(1 << ArgNo); 1080 } 1081 1082 switch (BuiltinID) { 1083 case Builtin::BI__builtin___CFStringMakeConstantString: 1084 assert(TheCall->getNumArgs() == 1 && 1085 "Wrong # arguments to builtin CFStringMakeConstantString"); 1086 if (CheckObjCString(TheCall->getArg(0))) 1087 return ExprError(); 1088 break; 1089 case Builtin::BI__builtin_ms_va_start: 1090 case Builtin::BI__builtin_stdarg_start: 1091 case Builtin::BI__builtin_va_start: 1092 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1093 return ExprError(); 1094 break; 1095 case Builtin::BI__va_start: { 1096 switch (Context.getTargetInfo().getTriple().getArch()) { 1097 case llvm::Triple::aarch64: 1098 case llvm::Triple::arm: 1099 case llvm::Triple::thumb: 1100 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1101 return ExprError(); 1102 break; 1103 default: 1104 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1105 return ExprError(); 1106 break; 1107 } 1108 break; 1109 } 1110 1111 // The acquire, release, and no fence variants are ARM and AArch64 only. 1112 case Builtin::BI_interlockedbittestandset_acq: 1113 case Builtin::BI_interlockedbittestandset_rel: 1114 case Builtin::BI_interlockedbittestandset_nf: 1115 case Builtin::BI_interlockedbittestandreset_acq: 1116 case Builtin::BI_interlockedbittestandreset_rel: 1117 case Builtin::BI_interlockedbittestandreset_nf: 1118 if (CheckBuiltinTargetSupport( 1119 *this, BuiltinID, TheCall, 1120 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1121 return ExprError(); 1122 break; 1123 1124 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1125 case Builtin::BI_bittest64: 1126 case Builtin::BI_bittestandcomplement64: 1127 case Builtin::BI_bittestandreset64: 1128 case Builtin::BI_bittestandset64: 1129 case Builtin::BI_interlockedbittestandreset64: 1130 case Builtin::BI_interlockedbittestandset64: 1131 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1132 {llvm::Triple::x86_64, llvm::Triple::arm, 1133 llvm::Triple::thumb, llvm::Triple::aarch64})) 1134 return ExprError(); 1135 break; 1136 1137 case Builtin::BI__builtin_isgreater: 1138 case Builtin::BI__builtin_isgreaterequal: 1139 case Builtin::BI__builtin_isless: 1140 case Builtin::BI__builtin_islessequal: 1141 case Builtin::BI__builtin_islessgreater: 1142 case Builtin::BI__builtin_isunordered: 1143 if (SemaBuiltinUnorderedCompare(TheCall)) 1144 return ExprError(); 1145 break; 1146 case Builtin::BI__builtin_fpclassify: 1147 if (SemaBuiltinFPClassification(TheCall, 6)) 1148 return ExprError(); 1149 break; 1150 case Builtin::BI__builtin_isfinite: 1151 case Builtin::BI__builtin_isinf: 1152 case Builtin::BI__builtin_isinf_sign: 1153 case Builtin::BI__builtin_isnan: 1154 case Builtin::BI__builtin_isnormal: 1155 case Builtin::BI__builtin_signbit: 1156 case Builtin::BI__builtin_signbitf: 1157 case Builtin::BI__builtin_signbitl: 1158 if (SemaBuiltinFPClassification(TheCall, 1)) 1159 return ExprError(); 1160 break; 1161 case Builtin::BI__builtin_shufflevector: 1162 return SemaBuiltinShuffleVector(TheCall); 1163 // TheCall will be freed by the smart pointer here, but that's fine, since 1164 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1165 case Builtin::BI__builtin_prefetch: 1166 if (SemaBuiltinPrefetch(TheCall)) 1167 return ExprError(); 1168 break; 1169 case Builtin::BI__builtin_alloca_with_align: 1170 if (SemaBuiltinAllocaWithAlign(TheCall)) 1171 return ExprError(); 1172 break; 1173 case Builtin::BI__assume: 1174 case Builtin::BI__builtin_assume: 1175 if (SemaBuiltinAssume(TheCall)) 1176 return ExprError(); 1177 break; 1178 case Builtin::BI__builtin_assume_aligned: 1179 if (SemaBuiltinAssumeAligned(TheCall)) 1180 return ExprError(); 1181 break; 1182 case Builtin::BI__builtin_dynamic_object_size: 1183 case Builtin::BI__builtin_object_size: 1184 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1185 return ExprError(); 1186 break; 1187 case Builtin::BI__builtin_longjmp: 1188 if (SemaBuiltinLongjmp(TheCall)) 1189 return ExprError(); 1190 break; 1191 case Builtin::BI__builtin_setjmp: 1192 if (SemaBuiltinSetjmp(TheCall)) 1193 return ExprError(); 1194 break; 1195 case Builtin::BI_setjmp: 1196 case Builtin::BI_setjmpex: 1197 if (checkArgCount(*this, TheCall, 1)) 1198 return true; 1199 break; 1200 case Builtin::BI__builtin_classify_type: 1201 if (checkArgCount(*this, TheCall, 1)) return true; 1202 TheCall->setType(Context.IntTy); 1203 break; 1204 case Builtin::BI__builtin_constant_p: { 1205 if (checkArgCount(*this, TheCall, 1)) return true; 1206 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1207 if (Arg.isInvalid()) return true; 1208 TheCall->setArg(0, Arg.get()); 1209 TheCall->setType(Context.IntTy); 1210 break; 1211 } 1212 case Builtin::BI__builtin_launder: 1213 return SemaBuiltinLaunder(*this, TheCall); 1214 case Builtin::BI__sync_fetch_and_add: 1215 case Builtin::BI__sync_fetch_and_add_1: 1216 case Builtin::BI__sync_fetch_and_add_2: 1217 case Builtin::BI__sync_fetch_and_add_4: 1218 case Builtin::BI__sync_fetch_and_add_8: 1219 case Builtin::BI__sync_fetch_and_add_16: 1220 case Builtin::BI__sync_fetch_and_sub: 1221 case Builtin::BI__sync_fetch_and_sub_1: 1222 case Builtin::BI__sync_fetch_and_sub_2: 1223 case Builtin::BI__sync_fetch_and_sub_4: 1224 case Builtin::BI__sync_fetch_and_sub_8: 1225 case Builtin::BI__sync_fetch_and_sub_16: 1226 case Builtin::BI__sync_fetch_and_or: 1227 case Builtin::BI__sync_fetch_and_or_1: 1228 case Builtin::BI__sync_fetch_and_or_2: 1229 case Builtin::BI__sync_fetch_and_or_4: 1230 case Builtin::BI__sync_fetch_and_or_8: 1231 case Builtin::BI__sync_fetch_and_or_16: 1232 case Builtin::BI__sync_fetch_and_and: 1233 case Builtin::BI__sync_fetch_and_and_1: 1234 case Builtin::BI__sync_fetch_and_and_2: 1235 case Builtin::BI__sync_fetch_and_and_4: 1236 case Builtin::BI__sync_fetch_and_and_8: 1237 case Builtin::BI__sync_fetch_and_and_16: 1238 case Builtin::BI__sync_fetch_and_xor: 1239 case Builtin::BI__sync_fetch_and_xor_1: 1240 case Builtin::BI__sync_fetch_and_xor_2: 1241 case Builtin::BI__sync_fetch_and_xor_4: 1242 case Builtin::BI__sync_fetch_and_xor_8: 1243 case Builtin::BI__sync_fetch_and_xor_16: 1244 case Builtin::BI__sync_fetch_and_nand: 1245 case Builtin::BI__sync_fetch_and_nand_1: 1246 case Builtin::BI__sync_fetch_and_nand_2: 1247 case Builtin::BI__sync_fetch_and_nand_4: 1248 case Builtin::BI__sync_fetch_and_nand_8: 1249 case Builtin::BI__sync_fetch_and_nand_16: 1250 case Builtin::BI__sync_add_and_fetch: 1251 case Builtin::BI__sync_add_and_fetch_1: 1252 case Builtin::BI__sync_add_and_fetch_2: 1253 case Builtin::BI__sync_add_and_fetch_4: 1254 case Builtin::BI__sync_add_and_fetch_8: 1255 case Builtin::BI__sync_add_and_fetch_16: 1256 case Builtin::BI__sync_sub_and_fetch: 1257 case Builtin::BI__sync_sub_and_fetch_1: 1258 case Builtin::BI__sync_sub_and_fetch_2: 1259 case Builtin::BI__sync_sub_and_fetch_4: 1260 case Builtin::BI__sync_sub_and_fetch_8: 1261 case Builtin::BI__sync_sub_and_fetch_16: 1262 case Builtin::BI__sync_and_and_fetch: 1263 case Builtin::BI__sync_and_and_fetch_1: 1264 case Builtin::BI__sync_and_and_fetch_2: 1265 case Builtin::BI__sync_and_and_fetch_4: 1266 case Builtin::BI__sync_and_and_fetch_8: 1267 case Builtin::BI__sync_and_and_fetch_16: 1268 case Builtin::BI__sync_or_and_fetch: 1269 case Builtin::BI__sync_or_and_fetch_1: 1270 case Builtin::BI__sync_or_and_fetch_2: 1271 case Builtin::BI__sync_or_and_fetch_4: 1272 case Builtin::BI__sync_or_and_fetch_8: 1273 case Builtin::BI__sync_or_and_fetch_16: 1274 case Builtin::BI__sync_xor_and_fetch: 1275 case Builtin::BI__sync_xor_and_fetch_1: 1276 case Builtin::BI__sync_xor_and_fetch_2: 1277 case Builtin::BI__sync_xor_and_fetch_4: 1278 case Builtin::BI__sync_xor_and_fetch_8: 1279 case Builtin::BI__sync_xor_and_fetch_16: 1280 case Builtin::BI__sync_nand_and_fetch: 1281 case Builtin::BI__sync_nand_and_fetch_1: 1282 case Builtin::BI__sync_nand_and_fetch_2: 1283 case Builtin::BI__sync_nand_and_fetch_4: 1284 case Builtin::BI__sync_nand_and_fetch_8: 1285 case Builtin::BI__sync_nand_and_fetch_16: 1286 case Builtin::BI__sync_val_compare_and_swap: 1287 case Builtin::BI__sync_val_compare_and_swap_1: 1288 case Builtin::BI__sync_val_compare_and_swap_2: 1289 case Builtin::BI__sync_val_compare_and_swap_4: 1290 case Builtin::BI__sync_val_compare_and_swap_8: 1291 case Builtin::BI__sync_val_compare_and_swap_16: 1292 case Builtin::BI__sync_bool_compare_and_swap: 1293 case Builtin::BI__sync_bool_compare_and_swap_1: 1294 case Builtin::BI__sync_bool_compare_and_swap_2: 1295 case Builtin::BI__sync_bool_compare_and_swap_4: 1296 case Builtin::BI__sync_bool_compare_and_swap_8: 1297 case Builtin::BI__sync_bool_compare_and_swap_16: 1298 case Builtin::BI__sync_lock_test_and_set: 1299 case Builtin::BI__sync_lock_test_and_set_1: 1300 case Builtin::BI__sync_lock_test_and_set_2: 1301 case Builtin::BI__sync_lock_test_and_set_4: 1302 case Builtin::BI__sync_lock_test_and_set_8: 1303 case Builtin::BI__sync_lock_test_and_set_16: 1304 case Builtin::BI__sync_lock_release: 1305 case Builtin::BI__sync_lock_release_1: 1306 case Builtin::BI__sync_lock_release_2: 1307 case Builtin::BI__sync_lock_release_4: 1308 case Builtin::BI__sync_lock_release_8: 1309 case Builtin::BI__sync_lock_release_16: 1310 case Builtin::BI__sync_swap: 1311 case Builtin::BI__sync_swap_1: 1312 case Builtin::BI__sync_swap_2: 1313 case Builtin::BI__sync_swap_4: 1314 case Builtin::BI__sync_swap_8: 1315 case Builtin::BI__sync_swap_16: 1316 return SemaBuiltinAtomicOverloaded(TheCallResult); 1317 case Builtin::BI__sync_synchronize: 1318 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1319 << TheCall->getCallee()->getSourceRange(); 1320 break; 1321 case Builtin::BI__builtin_nontemporal_load: 1322 case Builtin::BI__builtin_nontemporal_store: 1323 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1324 #define BUILTIN(ID, TYPE, ATTRS) 1325 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1326 case Builtin::BI##ID: \ 1327 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1328 #include "clang/Basic/Builtins.def" 1329 case Builtin::BI__annotation: 1330 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1331 return ExprError(); 1332 break; 1333 case Builtin::BI__builtin_annotation: 1334 if (SemaBuiltinAnnotation(*this, TheCall)) 1335 return ExprError(); 1336 break; 1337 case Builtin::BI__builtin_addressof: 1338 if (SemaBuiltinAddressof(*this, TheCall)) 1339 return ExprError(); 1340 break; 1341 case Builtin::BI__builtin_add_overflow: 1342 case Builtin::BI__builtin_sub_overflow: 1343 case Builtin::BI__builtin_mul_overflow: 1344 if (SemaBuiltinOverflow(*this, TheCall)) 1345 return ExprError(); 1346 break; 1347 case Builtin::BI__builtin_operator_new: 1348 case Builtin::BI__builtin_operator_delete: { 1349 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1350 ExprResult Res = 1351 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1352 if (Res.isInvalid()) 1353 CorrectDelayedTyposInExpr(TheCallResult.get()); 1354 return Res; 1355 } 1356 case Builtin::BI__builtin_dump_struct: { 1357 // We first want to ensure we are called with 2 arguments 1358 if (checkArgCount(*this, TheCall, 2)) 1359 return ExprError(); 1360 // Ensure that the first argument is of type 'struct XX *' 1361 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1362 const QualType PtrArgType = PtrArg->getType(); 1363 if (!PtrArgType->isPointerType() || 1364 !PtrArgType->getPointeeType()->isRecordType()) { 1365 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1366 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1367 << "structure pointer"; 1368 return ExprError(); 1369 } 1370 1371 // Ensure that the second argument is of type 'FunctionType' 1372 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1373 const QualType FnPtrArgType = FnPtrArg->getType(); 1374 if (!FnPtrArgType->isPointerType()) { 1375 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1376 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1377 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1378 return ExprError(); 1379 } 1380 1381 const auto *FuncType = 1382 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1383 1384 if (!FuncType) { 1385 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1386 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1387 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1388 return ExprError(); 1389 } 1390 1391 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1392 if (!FT->getNumParams()) { 1393 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1394 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1395 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1396 return ExprError(); 1397 } 1398 QualType PT = FT->getParamType(0); 1399 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1400 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1401 !PT->getPointeeType().isConstQualified()) { 1402 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1403 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1404 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1405 return ExprError(); 1406 } 1407 } 1408 1409 TheCall->setType(Context.IntTy); 1410 break; 1411 } 1412 case Builtin::BI__builtin_call_with_static_chain: 1413 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1414 return ExprError(); 1415 break; 1416 case Builtin::BI__exception_code: 1417 case Builtin::BI_exception_code: 1418 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1419 diag::err_seh___except_block)) 1420 return ExprError(); 1421 break; 1422 case Builtin::BI__exception_info: 1423 case Builtin::BI_exception_info: 1424 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1425 diag::err_seh___except_filter)) 1426 return ExprError(); 1427 break; 1428 case Builtin::BI__GetExceptionInfo: 1429 if (checkArgCount(*this, TheCall, 1)) 1430 return ExprError(); 1431 1432 if (CheckCXXThrowOperand( 1433 TheCall->getBeginLoc(), 1434 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1435 TheCall)) 1436 return ExprError(); 1437 1438 TheCall->setType(Context.VoidPtrTy); 1439 break; 1440 // OpenCL v2.0, s6.13.16 - Pipe functions 1441 case Builtin::BIread_pipe: 1442 case Builtin::BIwrite_pipe: 1443 // Since those two functions are declared with var args, we need a semantic 1444 // check for the argument. 1445 if (SemaBuiltinRWPipe(*this, TheCall)) 1446 return ExprError(); 1447 break; 1448 case Builtin::BIreserve_read_pipe: 1449 case Builtin::BIreserve_write_pipe: 1450 case Builtin::BIwork_group_reserve_read_pipe: 1451 case Builtin::BIwork_group_reserve_write_pipe: 1452 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1453 return ExprError(); 1454 break; 1455 case Builtin::BIsub_group_reserve_read_pipe: 1456 case Builtin::BIsub_group_reserve_write_pipe: 1457 if (checkOpenCLSubgroupExt(*this, TheCall) || 1458 SemaBuiltinReserveRWPipe(*this, TheCall)) 1459 return ExprError(); 1460 break; 1461 case Builtin::BIcommit_read_pipe: 1462 case Builtin::BIcommit_write_pipe: 1463 case Builtin::BIwork_group_commit_read_pipe: 1464 case Builtin::BIwork_group_commit_write_pipe: 1465 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1466 return ExprError(); 1467 break; 1468 case Builtin::BIsub_group_commit_read_pipe: 1469 case Builtin::BIsub_group_commit_write_pipe: 1470 if (checkOpenCLSubgroupExt(*this, TheCall) || 1471 SemaBuiltinCommitRWPipe(*this, TheCall)) 1472 return ExprError(); 1473 break; 1474 case Builtin::BIget_pipe_num_packets: 1475 case Builtin::BIget_pipe_max_packets: 1476 if (SemaBuiltinPipePackets(*this, TheCall)) 1477 return ExprError(); 1478 break; 1479 case Builtin::BIto_global: 1480 case Builtin::BIto_local: 1481 case Builtin::BIto_private: 1482 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1483 return ExprError(); 1484 break; 1485 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1486 case Builtin::BIenqueue_kernel: 1487 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1488 return ExprError(); 1489 break; 1490 case Builtin::BIget_kernel_work_group_size: 1491 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1492 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1493 return ExprError(); 1494 break; 1495 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1496 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1497 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1498 return ExprError(); 1499 break; 1500 case Builtin::BI__builtin_os_log_format: 1501 case Builtin::BI__builtin_os_log_format_buffer_size: 1502 if (SemaBuiltinOSLogFormat(TheCall)) 1503 return ExprError(); 1504 break; 1505 } 1506 1507 // Since the target specific builtins for each arch overlap, only check those 1508 // of the arch we are compiling for. 1509 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1510 switch (Context.getTargetInfo().getTriple().getArch()) { 1511 case llvm::Triple::arm: 1512 case llvm::Triple::armeb: 1513 case llvm::Triple::thumb: 1514 case llvm::Triple::thumbeb: 1515 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1516 return ExprError(); 1517 break; 1518 case llvm::Triple::aarch64: 1519 case llvm::Triple::aarch64_be: 1520 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1521 return ExprError(); 1522 break; 1523 case llvm::Triple::hexagon: 1524 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1525 return ExprError(); 1526 break; 1527 case llvm::Triple::mips: 1528 case llvm::Triple::mipsel: 1529 case llvm::Triple::mips64: 1530 case llvm::Triple::mips64el: 1531 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1532 return ExprError(); 1533 break; 1534 case llvm::Triple::systemz: 1535 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1536 return ExprError(); 1537 break; 1538 case llvm::Triple::x86: 1539 case llvm::Triple::x86_64: 1540 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1541 return ExprError(); 1542 break; 1543 case llvm::Triple::ppc: 1544 case llvm::Triple::ppc64: 1545 case llvm::Triple::ppc64le: 1546 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1547 return ExprError(); 1548 break; 1549 default: 1550 break; 1551 } 1552 } 1553 1554 return TheCallResult; 1555 } 1556 1557 // Get the valid immediate range for the specified NEON type code. 1558 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1559 NeonTypeFlags Type(t); 1560 int IsQuad = ForceQuad ? true : Type.isQuad(); 1561 switch (Type.getEltType()) { 1562 case NeonTypeFlags::Int8: 1563 case NeonTypeFlags::Poly8: 1564 return shift ? 7 : (8 << IsQuad) - 1; 1565 case NeonTypeFlags::Int16: 1566 case NeonTypeFlags::Poly16: 1567 return shift ? 15 : (4 << IsQuad) - 1; 1568 case NeonTypeFlags::Int32: 1569 return shift ? 31 : (2 << IsQuad) - 1; 1570 case NeonTypeFlags::Int64: 1571 case NeonTypeFlags::Poly64: 1572 return shift ? 63 : (1 << IsQuad) - 1; 1573 case NeonTypeFlags::Poly128: 1574 return shift ? 127 : (1 << IsQuad) - 1; 1575 case NeonTypeFlags::Float16: 1576 assert(!shift && "cannot shift float types!"); 1577 return (4 << IsQuad) - 1; 1578 case NeonTypeFlags::Float32: 1579 assert(!shift && "cannot shift float types!"); 1580 return (2 << IsQuad) - 1; 1581 case NeonTypeFlags::Float64: 1582 assert(!shift && "cannot shift float types!"); 1583 return (1 << IsQuad) - 1; 1584 } 1585 llvm_unreachable("Invalid NeonTypeFlag!"); 1586 } 1587 1588 /// getNeonEltType - Return the QualType corresponding to the elements of 1589 /// the vector type specified by the NeonTypeFlags. This is used to check 1590 /// the pointer arguments for Neon load/store intrinsics. 1591 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1592 bool IsPolyUnsigned, bool IsInt64Long) { 1593 switch (Flags.getEltType()) { 1594 case NeonTypeFlags::Int8: 1595 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1596 case NeonTypeFlags::Int16: 1597 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1598 case NeonTypeFlags::Int32: 1599 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1600 case NeonTypeFlags::Int64: 1601 if (IsInt64Long) 1602 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1603 else 1604 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1605 : Context.LongLongTy; 1606 case NeonTypeFlags::Poly8: 1607 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1608 case NeonTypeFlags::Poly16: 1609 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1610 case NeonTypeFlags::Poly64: 1611 if (IsInt64Long) 1612 return Context.UnsignedLongTy; 1613 else 1614 return Context.UnsignedLongLongTy; 1615 case NeonTypeFlags::Poly128: 1616 break; 1617 case NeonTypeFlags::Float16: 1618 return Context.HalfTy; 1619 case NeonTypeFlags::Float32: 1620 return Context.FloatTy; 1621 case NeonTypeFlags::Float64: 1622 return Context.DoubleTy; 1623 } 1624 llvm_unreachable("Invalid NeonTypeFlag!"); 1625 } 1626 1627 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1628 llvm::APSInt Result; 1629 uint64_t mask = 0; 1630 unsigned TV = 0; 1631 int PtrArgNum = -1; 1632 bool HasConstPtr = false; 1633 switch (BuiltinID) { 1634 #define GET_NEON_OVERLOAD_CHECK 1635 #include "clang/Basic/arm_neon.inc" 1636 #include "clang/Basic/arm_fp16.inc" 1637 #undef GET_NEON_OVERLOAD_CHECK 1638 } 1639 1640 // For NEON intrinsics which are overloaded on vector element type, validate 1641 // the immediate which specifies which variant to emit. 1642 unsigned ImmArg = TheCall->getNumArgs()-1; 1643 if (mask) { 1644 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1645 return true; 1646 1647 TV = Result.getLimitedValue(64); 1648 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1649 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1650 << TheCall->getArg(ImmArg)->getSourceRange(); 1651 } 1652 1653 if (PtrArgNum >= 0) { 1654 // Check that pointer arguments have the specified type. 1655 Expr *Arg = TheCall->getArg(PtrArgNum); 1656 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1657 Arg = ICE->getSubExpr(); 1658 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1659 QualType RHSTy = RHS.get()->getType(); 1660 1661 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1662 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1663 Arch == llvm::Triple::aarch64_be; 1664 bool IsInt64Long = 1665 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1666 QualType EltTy = 1667 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1668 if (HasConstPtr) 1669 EltTy = EltTy.withConst(); 1670 QualType LHSTy = Context.getPointerType(EltTy); 1671 AssignConvertType ConvTy; 1672 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1673 if (RHS.isInvalid()) 1674 return true; 1675 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1676 RHS.get(), AA_Assigning)) 1677 return true; 1678 } 1679 1680 // For NEON intrinsics which take an immediate value as part of the 1681 // instruction, range check them here. 1682 unsigned i = 0, l = 0, u = 0; 1683 switch (BuiltinID) { 1684 default: 1685 return false; 1686 #define GET_NEON_IMMEDIATE_CHECK 1687 #include "clang/Basic/arm_neon.inc" 1688 #include "clang/Basic/arm_fp16.inc" 1689 #undef GET_NEON_IMMEDIATE_CHECK 1690 } 1691 1692 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1693 } 1694 1695 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1696 unsigned MaxWidth) { 1697 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1698 BuiltinID == ARM::BI__builtin_arm_ldaex || 1699 BuiltinID == ARM::BI__builtin_arm_strex || 1700 BuiltinID == ARM::BI__builtin_arm_stlex || 1701 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1702 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1703 BuiltinID == AArch64::BI__builtin_arm_strex || 1704 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1705 "unexpected ARM builtin"); 1706 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1707 BuiltinID == ARM::BI__builtin_arm_ldaex || 1708 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1709 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1710 1711 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1712 1713 // Ensure that we have the proper number of arguments. 1714 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1715 return true; 1716 1717 // Inspect the pointer argument of the atomic builtin. This should always be 1718 // a pointer type, whose element is an integral scalar or pointer type. 1719 // Because it is a pointer type, we don't have to worry about any implicit 1720 // casts here. 1721 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1722 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1723 if (PointerArgRes.isInvalid()) 1724 return true; 1725 PointerArg = PointerArgRes.get(); 1726 1727 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1728 if (!pointerType) { 1729 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1730 << PointerArg->getType() << PointerArg->getSourceRange(); 1731 return true; 1732 } 1733 1734 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1735 // task is to insert the appropriate casts into the AST. First work out just 1736 // what the appropriate type is. 1737 QualType ValType = pointerType->getPointeeType(); 1738 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1739 if (IsLdrex) 1740 AddrType.addConst(); 1741 1742 // Issue a warning if the cast is dodgy. 1743 CastKind CastNeeded = CK_NoOp; 1744 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1745 CastNeeded = CK_BitCast; 1746 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1747 << PointerArg->getType() << Context.getPointerType(AddrType) 1748 << AA_Passing << PointerArg->getSourceRange(); 1749 } 1750 1751 // Finally, do the cast and replace the argument with the corrected version. 1752 AddrType = Context.getPointerType(AddrType); 1753 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1754 if (PointerArgRes.isInvalid()) 1755 return true; 1756 PointerArg = PointerArgRes.get(); 1757 1758 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1759 1760 // In general, we allow ints, floats and pointers to be loaded and stored. 1761 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1762 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1763 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1764 << PointerArg->getType() << PointerArg->getSourceRange(); 1765 return true; 1766 } 1767 1768 // But ARM doesn't have instructions to deal with 128-bit versions. 1769 if (Context.getTypeSize(ValType) > MaxWidth) { 1770 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1771 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1772 << PointerArg->getType() << PointerArg->getSourceRange(); 1773 return true; 1774 } 1775 1776 switch (ValType.getObjCLifetime()) { 1777 case Qualifiers::OCL_None: 1778 case Qualifiers::OCL_ExplicitNone: 1779 // okay 1780 break; 1781 1782 case Qualifiers::OCL_Weak: 1783 case Qualifiers::OCL_Strong: 1784 case Qualifiers::OCL_Autoreleasing: 1785 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1786 << ValType << PointerArg->getSourceRange(); 1787 return true; 1788 } 1789 1790 if (IsLdrex) { 1791 TheCall->setType(ValType); 1792 return false; 1793 } 1794 1795 // Initialize the argument to be stored. 1796 ExprResult ValArg = TheCall->getArg(0); 1797 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1798 Context, ValType, /*consume*/ false); 1799 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1800 if (ValArg.isInvalid()) 1801 return true; 1802 TheCall->setArg(0, ValArg.get()); 1803 1804 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1805 // but the custom checker bypasses all default analysis. 1806 TheCall->setType(Context.IntTy); 1807 return false; 1808 } 1809 1810 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1811 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1812 BuiltinID == ARM::BI__builtin_arm_ldaex || 1813 BuiltinID == ARM::BI__builtin_arm_strex || 1814 BuiltinID == ARM::BI__builtin_arm_stlex) { 1815 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1816 } 1817 1818 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1819 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1820 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1821 } 1822 1823 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1824 BuiltinID == ARM::BI__builtin_arm_wsr64) 1825 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1826 1827 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1828 BuiltinID == ARM::BI__builtin_arm_rsrp || 1829 BuiltinID == ARM::BI__builtin_arm_wsr || 1830 BuiltinID == ARM::BI__builtin_arm_wsrp) 1831 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1832 1833 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1834 return true; 1835 1836 // For intrinsics which take an immediate value as part of the instruction, 1837 // range check them here. 1838 // FIXME: VFP Intrinsics should error if VFP not present. 1839 switch (BuiltinID) { 1840 default: return false; 1841 case ARM::BI__builtin_arm_ssat: 1842 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1843 case ARM::BI__builtin_arm_usat: 1844 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1845 case ARM::BI__builtin_arm_ssat16: 1846 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1847 case ARM::BI__builtin_arm_usat16: 1848 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1849 case ARM::BI__builtin_arm_vcvtr_f: 1850 case ARM::BI__builtin_arm_vcvtr_d: 1851 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1852 case ARM::BI__builtin_arm_dmb: 1853 case ARM::BI__builtin_arm_dsb: 1854 case ARM::BI__builtin_arm_isb: 1855 case ARM::BI__builtin_arm_dbg: 1856 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1857 } 1858 } 1859 1860 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1861 CallExpr *TheCall) { 1862 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1863 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1864 BuiltinID == AArch64::BI__builtin_arm_strex || 1865 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1866 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1867 } 1868 1869 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1870 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1871 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1872 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1873 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1874 } 1875 1876 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1877 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1878 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1879 1880 // Memory Tagging Extensions (MTE) Intrinsics 1881 if (BuiltinID == AArch64::BI__builtin_arm_irg || 1882 BuiltinID == AArch64::BI__builtin_arm_addg || 1883 BuiltinID == AArch64::BI__builtin_arm_gmi || 1884 BuiltinID == AArch64::BI__builtin_arm_ldg || 1885 BuiltinID == AArch64::BI__builtin_arm_stg || 1886 BuiltinID == AArch64::BI__builtin_arm_subp) { 1887 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 1888 } 1889 1890 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1891 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1892 BuiltinID == AArch64::BI__builtin_arm_wsr || 1893 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1894 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1895 1896 // Only check the valid encoding range. Any constant in this range would be 1897 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1898 // an exception for incorrect registers. This matches MSVC behavior. 1899 if (BuiltinID == AArch64::BI_ReadStatusReg || 1900 BuiltinID == AArch64::BI_WriteStatusReg) 1901 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1902 1903 if (BuiltinID == AArch64::BI__getReg) 1904 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1905 1906 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1907 return true; 1908 1909 // For intrinsics which take an immediate value as part of the instruction, 1910 // range check them here. 1911 unsigned i = 0, l = 0, u = 0; 1912 switch (BuiltinID) { 1913 default: return false; 1914 case AArch64::BI__builtin_arm_dmb: 1915 case AArch64::BI__builtin_arm_dsb: 1916 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1917 } 1918 1919 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1920 } 1921 1922 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1923 struct BuiltinAndString { 1924 unsigned BuiltinID; 1925 const char *Str; 1926 }; 1927 1928 static BuiltinAndString ValidCPU[] = { 1929 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 1930 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 1931 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 1932 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 1933 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 1934 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 1935 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 1936 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 1937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 1938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 1939 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 1940 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 1941 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 1942 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 1943 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 1944 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 1945 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 1946 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 1947 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 1948 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 1949 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 1950 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 1951 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 1952 }; 1953 1954 static BuiltinAndString ValidHVX[] = { 1955 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2605 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2606 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2607 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2608 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2609 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2610 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2611 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2612 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2613 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2614 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2615 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2616 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2617 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2618 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2619 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2620 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2621 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2622 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2623 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2624 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2625 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2626 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2627 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2628 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2629 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2630 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2631 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2632 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2633 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2634 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2635 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2636 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2637 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2638 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2639 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2640 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2641 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2642 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2643 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2644 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2645 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2646 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2647 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2648 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2649 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2650 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2651 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2652 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2653 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2654 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2655 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2656 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2657 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2658 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2659 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2660 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2661 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2662 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2663 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2664 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2665 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2666 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2667 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2668 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2669 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2670 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2671 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2672 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2673 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2674 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2675 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2676 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2677 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2678 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2679 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2680 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2681 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2682 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2683 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2684 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2685 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2686 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2687 }; 2688 2689 // Sort the tables on first execution so we can binary search them. 2690 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2691 return LHS.BuiltinID < RHS.BuiltinID; 2692 }; 2693 static const bool SortOnce = 2694 (llvm::sort(ValidCPU, SortCmp), 2695 llvm::sort(ValidHVX, SortCmp), true); 2696 (void)SortOnce; 2697 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2698 return BI.BuiltinID < BuiltinID; 2699 }; 2700 2701 const TargetInfo &TI = Context.getTargetInfo(); 2702 2703 const BuiltinAndString *FC = 2704 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID, 2705 LowerBoundCmp); 2706 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2707 const TargetOptions &Opts = TI.getTargetOpts(); 2708 StringRef CPU = Opts.CPU; 2709 if (!CPU.empty()) { 2710 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2711 CPU.consume_front("hexagon"); 2712 SmallVector<StringRef, 3> CPUs; 2713 StringRef(FC->Str).split(CPUs, ','); 2714 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2715 return Diag(TheCall->getBeginLoc(), 2716 diag::err_hexagon_builtin_unsupported_cpu); 2717 } 2718 } 2719 2720 const BuiltinAndString *FH = 2721 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID, 2722 LowerBoundCmp); 2723 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2724 if (!TI.hasFeature("hvx")) 2725 return Diag(TheCall->getBeginLoc(), 2726 diag::err_hexagon_builtin_requires_hvx); 2727 2728 SmallVector<StringRef, 3> HVXs; 2729 StringRef(FH->Str).split(HVXs, ','); 2730 bool IsValid = llvm::any_of(HVXs, 2731 [&TI] (StringRef V) { 2732 std::string F = "hvx" + V.str(); 2733 return TI.hasFeature(F); 2734 }); 2735 if (!IsValid) 2736 return Diag(TheCall->getBeginLoc(), 2737 diag::err_hexagon_builtin_unsupported_hvx); 2738 } 2739 2740 return false; 2741 } 2742 2743 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2744 struct ArgInfo { 2745 uint8_t OpNum; 2746 bool IsSigned; 2747 uint8_t BitWidth; 2748 uint8_t Align; 2749 }; 2750 struct BuiltinInfo { 2751 unsigned BuiltinID; 2752 ArgInfo Infos[2]; 2753 }; 2754 2755 static BuiltinInfo Infos[] = { 2756 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2757 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2758 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2759 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2760 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2761 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2762 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2763 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2764 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2765 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2766 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2767 2768 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2779 2780 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2832 {{ 1, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2840 {{ 1, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2847 { 2, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2849 { 2, false, 6, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2851 { 3, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2853 { 3, false, 6, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2870 {{ 2, false, 4, 0 }, 2871 { 3, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2873 {{ 2, false, 4, 0 }, 2874 { 3, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2876 {{ 2, false, 4, 0 }, 2877 { 3, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2879 {{ 2, false, 4, 0 }, 2880 { 3, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2892 { 2, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2894 { 2, false, 6, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2904 {{ 1, false, 4, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2907 {{ 1, false, 4, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2928 {{ 3, false, 1, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2933 {{ 3, false, 1, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2938 {{ 3, false, 1, 0 }} }, 2939 }; 2940 2941 // Use a dynamically initialized static to sort the table exactly once on 2942 // first run. 2943 static const bool SortOnce = 2944 (llvm::sort(Infos, 2945 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2946 return LHS.BuiltinID < RHS.BuiltinID; 2947 }), 2948 true); 2949 (void)SortOnce; 2950 2951 const BuiltinInfo *F = 2952 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID, 2953 [](const BuiltinInfo &BI, unsigned BuiltinID) { 2954 return BI.BuiltinID < BuiltinID; 2955 }); 2956 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2957 return false; 2958 2959 bool Error = false; 2960 2961 for (const ArgInfo &A : F->Infos) { 2962 // Ignore empty ArgInfo elements. 2963 if (A.BitWidth == 0) 2964 continue; 2965 2966 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2967 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2968 if (!A.Align) { 2969 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2970 } else { 2971 unsigned M = 1 << A.Align; 2972 Min *= M; 2973 Max *= M; 2974 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2975 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2976 } 2977 } 2978 return Error; 2979 } 2980 2981 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2982 CallExpr *TheCall) { 2983 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2984 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2985 } 2986 2987 2988 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2989 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2990 // ordering for DSP is unspecified. MSA is ordered by the data format used 2991 // by the underlying instruction i.e., df/m, df/n and then by size. 2992 // 2993 // FIXME: The size tests here should instead be tablegen'd along with the 2994 // definitions from include/clang/Basic/BuiltinsMips.def. 2995 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2996 // be too. 2997 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2998 unsigned i = 0, l = 0, u = 0, m = 0; 2999 switch (BuiltinID) { 3000 default: return false; 3001 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3002 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3003 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3004 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3005 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3006 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3007 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3008 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3009 // df/m field. 3010 // These intrinsics take an unsigned 3 bit immediate. 3011 case Mips::BI__builtin_msa_bclri_b: 3012 case Mips::BI__builtin_msa_bnegi_b: 3013 case Mips::BI__builtin_msa_bseti_b: 3014 case Mips::BI__builtin_msa_sat_s_b: 3015 case Mips::BI__builtin_msa_sat_u_b: 3016 case Mips::BI__builtin_msa_slli_b: 3017 case Mips::BI__builtin_msa_srai_b: 3018 case Mips::BI__builtin_msa_srari_b: 3019 case Mips::BI__builtin_msa_srli_b: 3020 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3021 case Mips::BI__builtin_msa_binsli_b: 3022 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3023 // These intrinsics take an unsigned 4 bit immediate. 3024 case Mips::BI__builtin_msa_bclri_h: 3025 case Mips::BI__builtin_msa_bnegi_h: 3026 case Mips::BI__builtin_msa_bseti_h: 3027 case Mips::BI__builtin_msa_sat_s_h: 3028 case Mips::BI__builtin_msa_sat_u_h: 3029 case Mips::BI__builtin_msa_slli_h: 3030 case Mips::BI__builtin_msa_srai_h: 3031 case Mips::BI__builtin_msa_srari_h: 3032 case Mips::BI__builtin_msa_srli_h: 3033 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3034 case Mips::BI__builtin_msa_binsli_h: 3035 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3036 // These intrinsics take an unsigned 5 bit immediate. 3037 // The first block of intrinsics actually have an unsigned 5 bit field, 3038 // not a df/n field. 3039 case Mips::BI__builtin_msa_cfcmsa: 3040 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3041 case Mips::BI__builtin_msa_clei_u_b: 3042 case Mips::BI__builtin_msa_clei_u_h: 3043 case Mips::BI__builtin_msa_clei_u_w: 3044 case Mips::BI__builtin_msa_clei_u_d: 3045 case Mips::BI__builtin_msa_clti_u_b: 3046 case Mips::BI__builtin_msa_clti_u_h: 3047 case Mips::BI__builtin_msa_clti_u_w: 3048 case Mips::BI__builtin_msa_clti_u_d: 3049 case Mips::BI__builtin_msa_maxi_u_b: 3050 case Mips::BI__builtin_msa_maxi_u_h: 3051 case Mips::BI__builtin_msa_maxi_u_w: 3052 case Mips::BI__builtin_msa_maxi_u_d: 3053 case Mips::BI__builtin_msa_mini_u_b: 3054 case Mips::BI__builtin_msa_mini_u_h: 3055 case Mips::BI__builtin_msa_mini_u_w: 3056 case Mips::BI__builtin_msa_mini_u_d: 3057 case Mips::BI__builtin_msa_addvi_b: 3058 case Mips::BI__builtin_msa_addvi_h: 3059 case Mips::BI__builtin_msa_addvi_w: 3060 case Mips::BI__builtin_msa_addvi_d: 3061 case Mips::BI__builtin_msa_bclri_w: 3062 case Mips::BI__builtin_msa_bnegi_w: 3063 case Mips::BI__builtin_msa_bseti_w: 3064 case Mips::BI__builtin_msa_sat_s_w: 3065 case Mips::BI__builtin_msa_sat_u_w: 3066 case Mips::BI__builtin_msa_slli_w: 3067 case Mips::BI__builtin_msa_srai_w: 3068 case Mips::BI__builtin_msa_srari_w: 3069 case Mips::BI__builtin_msa_srli_w: 3070 case Mips::BI__builtin_msa_srlri_w: 3071 case Mips::BI__builtin_msa_subvi_b: 3072 case Mips::BI__builtin_msa_subvi_h: 3073 case Mips::BI__builtin_msa_subvi_w: 3074 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3075 case Mips::BI__builtin_msa_binsli_w: 3076 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3077 // These intrinsics take an unsigned 6 bit immediate. 3078 case Mips::BI__builtin_msa_bclri_d: 3079 case Mips::BI__builtin_msa_bnegi_d: 3080 case Mips::BI__builtin_msa_bseti_d: 3081 case Mips::BI__builtin_msa_sat_s_d: 3082 case Mips::BI__builtin_msa_sat_u_d: 3083 case Mips::BI__builtin_msa_slli_d: 3084 case Mips::BI__builtin_msa_srai_d: 3085 case Mips::BI__builtin_msa_srari_d: 3086 case Mips::BI__builtin_msa_srli_d: 3087 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3088 case Mips::BI__builtin_msa_binsli_d: 3089 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3090 // These intrinsics take a signed 5 bit immediate. 3091 case Mips::BI__builtin_msa_ceqi_b: 3092 case Mips::BI__builtin_msa_ceqi_h: 3093 case Mips::BI__builtin_msa_ceqi_w: 3094 case Mips::BI__builtin_msa_ceqi_d: 3095 case Mips::BI__builtin_msa_clti_s_b: 3096 case Mips::BI__builtin_msa_clti_s_h: 3097 case Mips::BI__builtin_msa_clti_s_w: 3098 case Mips::BI__builtin_msa_clti_s_d: 3099 case Mips::BI__builtin_msa_clei_s_b: 3100 case Mips::BI__builtin_msa_clei_s_h: 3101 case Mips::BI__builtin_msa_clei_s_w: 3102 case Mips::BI__builtin_msa_clei_s_d: 3103 case Mips::BI__builtin_msa_maxi_s_b: 3104 case Mips::BI__builtin_msa_maxi_s_h: 3105 case Mips::BI__builtin_msa_maxi_s_w: 3106 case Mips::BI__builtin_msa_maxi_s_d: 3107 case Mips::BI__builtin_msa_mini_s_b: 3108 case Mips::BI__builtin_msa_mini_s_h: 3109 case Mips::BI__builtin_msa_mini_s_w: 3110 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3111 // These intrinsics take an unsigned 8 bit immediate. 3112 case Mips::BI__builtin_msa_andi_b: 3113 case Mips::BI__builtin_msa_nori_b: 3114 case Mips::BI__builtin_msa_ori_b: 3115 case Mips::BI__builtin_msa_shf_b: 3116 case Mips::BI__builtin_msa_shf_h: 3117 case Mips::BI__builtin_msa_shf_w: 3118 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3119 case Mips::BI__builtin_msa_bseli_b: 3120 case Mips::BI__builtin_msa_bmnzi_b: 3121 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3122 // df/n format 3123 // These intrinsics take an unsigned 4 bit immediate. 3124 case Mips::BI__builtin_msa_copy_s_b: 3125 case Mips::BI__builtin_msa_copy_u_b: 3126 case Mips::BI__builtin_msa_insve_b: 3127 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3128 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3129 // These intrinsics take an unsigned 3 bit immediate. 3130 case Mips::BI__builtin_msa_copy_s_h: 3131 case Mips::BI__builtin_msa_copy_u_h: 3132 case Mips::BI__builtin_msa_insve_h: 3133 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3134 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3135 // These intrinsics take an unsigned 2 bit immediate. 3136 case Mips::BI__builtin_msa_copy_s_w: 3137 case Mips::BI__builtin_msa_copy_u_w: 3138 case Mips::BI__builtin_msa_insve_w: 3139 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3140 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3141 // These intrinsics take an unsigned 1 bit immediate. 3142 case Mips::BI__builtin_msa_copy_s_d: 3143 case Mips::BI__builtin_msa_copy_u_d: 3144 case Mips::BI__builtin_msa_insve_d: 3145 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3146 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3147 // Memory offsets and immediate loads. 3148 // These intrinsics take a signed 10 bit immediate. 3149 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3150 case Mips::BI__builtin_msa_ldi_h: 3151 case Mips::BI__builtin_msa_ldi_w: 3152 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3153 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3154 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3155 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3156 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3157 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3158 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3159 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3160 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3161 } 3162 3163 if (!m) 3164 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3165 3166 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3167 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3168 } 3169 3170 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3171 unsigned i = 0, l = 0, u = 0; 3172 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3173 BuiltinID == PPC::BI__builtin_divdeu || 3174 BuiltinID == PPC::BI__builtin_bpermd; 3175 bool IsTarget64Bit = Context.getTargetInfo() 3176 .getTypeWidth(Context 3177 .getTargetInfo() 3178 .getIntPtrType()) == 64; 3179 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3180 BuiltinID == PPC::BI__builtin_divweu || 3181 BuiltinID == PPC::BI__builtin_divde || 3182 BuiltinID == PPC::BI__builtin_divdeu; 3183 3184 if (Is64BitBltin && !IsTarget64Bit) 3185 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3186 << TheCall->getSourceRange(); 3187 3188 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3189 (BuiltinID == PPC::BI__builtin_bpermd && 3190 !Context.getTargetInfo().hasFeature("bpermd"))) 3191 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3192 << TheCall->getSourceRange(); 3193 3194 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3195 if (!Context.getTargetInfo().hasFeature("vsx")) 3196 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3197 << TheCall->getSourceRange(); 3198 return false; 3199 }; 3200 3201 switch (BuiltinID) { 3202 default: return false; 3203 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3204 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3205 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3206 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3207 case PPC::BI__builtin_tbegin: 3208 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3209 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3210 case PPC::BI__builtin_tabortwc: 3211 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3212 case PPC::BI__builtin_tabortwci: 3213 case PPC::BI__builtin_tabortdci: 3214 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3215 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3216 case PPC::BI__builtin_vsx_xxpermdi: 3217 case PPC::BI__builtin_vsx_xxsldwi: 3218 return SemaBuiltinVSX(TheCall); 3219 case PPC::BI__builtin_unpack_vector_int128: 3220 return SemaVSXCheck(TheCall) || 3221 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3222 case PPC::BI__builtin_pack_vector_int128: 3223 return SemaVSXCheck(TheCall); 3224 } 3225 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3226 } 3227 3228 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3229 CallExpr *TheCall) { 3230 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3231 Expr *Arg = TheCall->getArg(0); 3232 llvm::APSInt AbortCode(32); 3233 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3234 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3235 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3236 << Arg->getSourceRange(); 3237 } 3238 3239 // For intrinsics which take an immediate value as part of the instruction, 3240 // range check them here. 3241 unsigned i = 0, l = 0, u = 0; 3242 switch (BuiltinID) { 3243 default: return false; 3244 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3245 case SystemZ::BI__builtin_s390_verimb: 3246 case SystemZ::BI__builtin_s390_verimh: 3247 case SystemZ::BI__builtin_s390_verimf: 3248 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3249 case SystemZ::BI__builtin_s390_vfaeb: 3250 case SystemZ::BI__builtin_s390_vfaeh: 3251 case SystemZ::BI__builtin_s390_vfaef: 3252 case SystemZ::BI__builtin_s390_vfaebs: 3253 case SystemZ::BI__builtin_s390_vfaehs: 3254 case SystemZ::BI__builtin_s390_vfaefs: 3255 case SystemZ::BI__builtin_s390_vfaezb: 3256 case SystemZ::BI__builtin_s390_vfaezh: 3257 case SystemZ::BI__builtin_s390_vfaezf: 3258 case SystemZ::BI__builtin_s390_vfaezbs: 3259 case SystemZ::BI__builtin_s390_vfaezhs: 3260 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3261 case SystemZ::BI__builtin_s390_vfisb: 3262 case SystemZ::BI__builtin_s390_vfidb: 3263 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3264 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3265 case SystemZ::BI__builtin_s390_vftcisb: 3266 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3267 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3268 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3269 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3270 case SystemZ::BI__builtin_s390_vstrcb: 3271 case SystemZ::BI__builtin_s390_vstrch: 3272 case SystemZ::BI__builtin_s390_vstrcf: 3273 case SystemZ::BI__builtin_s390_vstrczb: 3274 case SystemZ::BI__builtin_s390_vstrczh: 3275 case SystemZ::BI__builtin_s390_vstrczf: 3276 case SystemZ::BI__builtin_s390_vstrcbs: 3277 case SystemZ::BI__builtin_s390_vstrchs: 3278 case SystemZ::BI__builtin_s390_vstrcfs: 3279 case SystemZ::BI__builtin_s390_vstrczbs: 3280 case SystemZ::BI__builtin_s390_vstrczhs: 3281 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3282 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3283 case SystemZ::BI__builtin_s390_vfminsb: 3284 case SystemZ::BI__builtin_s390_vfmaxsb: 3285 case SystemZ::BI__builtin_s390_vfmindb: 3286 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3287 } 3288 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3289 } 3290 3291 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3292 /// This checks that the target supports __builtin_cpu_supports and 3293 /// that the string argument is constant and valid. 3294 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3295 Expr *Arg = TheCall->getArg(0); 3296 3297 // Check if the argument is a string literal. 3298 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3299 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3300 << Arg->getSourceRange(); 3301 3302 // Check the contents of the string. 3303 StringRef Feature = 3304 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3305 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3306 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3307 << Arg->getSourceRange(); 3308 return false; 3309 } 3310 3311 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3312 /// This checks that the target supports __builtin_cpu_is and 3313 /// that the string argument is constant and valid. 3314 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3315 Expr *Arg = TheCall->getArg(0); 3316 3317 // Check if the argument is a string literal. 3318 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3319 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3320 << Arg->getSourceRange(); 3321 3322 // Check the contents of the string. 3323 StringRef Feature = 3324 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3325 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3326 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3327 << Arg->getSourceRange(); 3328 return false; 3329 } 3330 3331 // Check if the rounding mode is legal. 3332 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3333 // Indicates if this instruction has rounding control or just SAE. 3334 bool HasRC = false; 3335 3336 unsigned ArgNum = 0; 3337 switch (BuiltinID) { 3338 default: 3339 return false; 3340 case X86::BI__builtin_ia32_vcvttsd2si32: 3341 case X86::BI__builtin_ia32_vcvttsd2si64: 3342 case X86::BI__builtin_ia32_vcvttsd2usi32: 3343 case X86::BI__builtin_ia32_vcvttsd2usi64: 3344 case X86::BI__builtin_ia32_vcvttss2si32: 3345 case X86::BI__builtin_ia32_vcvttss2si64: 3346 case X86::BI__builtin_ia32_vcvttss2usi32: 3347 case X86::BI__builtin_ia32_vcvttss2usi64: 3348 ArgNum = 1; 3349 break; 3350 case X86::BI__builtin_ia32_maxpd512: 3351 case X86::BI__builtin_ia32_maxps512: 3352 case X86::BI__builtin_ia32_minpd512: 3353 case X86::BI__builtin_ia32_minps512: 3354 ArgNum = 2; 3355 break; 3356 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3357 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3358 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3359 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3360 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3361 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3362 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3363 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3364 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3365 case X86::BI__builtin_ia32_exp2pd_mask: 3366 case X86::BI__builtin_ia32_exp2ps_mask: 3367 case X86::BI__builtin_ia32_getexppd512_mask: 3368 case X86::BI__builtin_ia32_getexpps512_mask: 3369 case X86::BI__builtin_ia32_rcp28pd_mask: 3370 case X86::BI__builtin_ia32_rcp28ps_mask: 3371 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3372 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3373 case X86::BI__builtin_ia32_vcomisd: 3374 case X86::BI__builtin_ia32_vcomiss: 3375 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3376 ArgNum = 3; 3377 break; 3378 case X86::BI__builtin_ia32_cmppd512_mask: 3379 case X86::BI__builtin_ia32_cmpps512_mask: 3380 case X86::BI__builtin_ia32_cmpsd_mask: 3381 case X86::BI__builtin_ia32_cmpss_mask: 3382 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3383 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3384 case X86::BI__builtin_ia32_getexpss128_round_mask: 3385 case X86::BI__builtin_ia32_getmantpd512_mask: 3386 case X86::BI__builtin_ia32_getmantps512_mask: 3387 case X86::BI__builtin_ia32_maxsd_round_mask: 3388 case X86::BI__builtin_ia32_maxss_round_mask: 3389 case X86::BI__builtin_ia32_minsd_round_mask: 3390 case X86::BI__builtin_ia32_minss_round_mask: 3391 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3392 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3393 case X86::BI__builtin_ia32_reducepd512_mask: 3394 case X86::BI__builtin_ia32_reduceps512_mask: 3395 case X86::BI__builtin_ia32_rndscalepd_mask: 3396 case X86::BI__builtin_ia32_rndscaleps_mask: 3397 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3398 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3399 ArgNum = 4; 3400 break; 3401 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3402 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3403 case X86::BI__builtin_ia32_fixupimmps512_mask: 3404 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3405 case X86::BI__builtin_ia32_fixupimmsd_mask: 3406 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3407 case X86::BI__builtin_ia32_fixupimmss_mask: 3408 case X86::BI__builtin_ia32_fixupimmss_maskz: 3409 case X86::BI__builtin_ia32_getmantsd_round_mask: 3410 case X86::BI__builtin_ia32_getmantss_round_mask: 3411 case X86::BI__builtin_ia32_rangepd512_mask: 3412 case X86::BI__builtin_ia32_rangeps512_mask: 3413 case X86::BI__builtin_ia32_rangesd128_round_mask: 3414 case X86::BI__builtin_ia32_rangess128_round_mask: 3415 case X86::BI__builtin_ia32_reducesd_mask: 3416 case X86::BI__builtin_ia32_reducess_mask: 3417 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3418 case X86::BI__builtin_ia32_rndscaless_round_mask: 3419 ArgNum = 5; 3420 break; 3421 case X86::BI__builtin_ia32_vcvtsd2si64: 3422 case X86::BI__builtin_ia32_vcvtsd2si32: 3423 case X86::BI__builtin_ia32_vcvtsd2usi32: 3424 case X86::BI__builtin_ia32_vcvtsd2usi64: 3425 case X86::BI__builtin_ia32_vcvtss2si32: 3426 case X86::BI__builtin_ia32_vcvtss2si64: 3427 case X86::BI__builtin_ia32_vcvtss2usi32: 3428 case X86::BI__builtin_ia32_vcvtss2usi64: 3429 case X86::BI__builtin_ia32_sqrtpd512: 3430 case X86::BI__builtin_ia32_sqrtps512: 3431 ArgNum = 1; 3432 HasRC = true; 3433 break; 3434 case X86::BI__builtin_ia32_addpd512: 3435 case X86::BI__builtin_ia32_addps512: 3436 case X86::BI__builtin_ia32_divpd512: 3437 case X86::BI__builtin_ia32_divps512: 3438 case X86::BI__builtin_ia32_mulpd512: 3439 case X86::BI__builtin_ia32_mulps512: 3440 case X86::BI__builtin_ia32_subpd512: 3441 case X86::BI__builtin_ia32_subps512: 3442 case X86::BI__builtin_ia32_cvtsi2sd64: 3443 case X86::BI__builtin_ia32_cvtsi2ss32: 3444 case X86::BI__builtin_ia32_cvtsi2ss64: 3445 case X86::BI__builtin_ia32_cvtusi2sd64: 3446 case X86::BI__builtin_ia32_cvtusi2ss32: 3447 case X86::BI__builtin_ia32_cvtusi2ss64: 3448 ArgNum = 2; 3449 HasRC = true; 3450 break; 3451 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3452 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3453 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3454 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3455 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3456 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3457 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3458 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3459 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3460 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3461 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3462 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3463 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3464 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3465 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3466 ArgNum = 3; 3467 HasRC = true; 3468 break; 3469 case X86::BI__builtin_ia32_addss_round_mask: 3470 case X86::BI__builtin_ia32_addsd_round_mask: 3471 case X86::BI__builtin_ia32_divss_round_mask: 3472 case X86::BI__builtin_ia32_divsd_round_mask: 3473 case X86::BI__builtin_ia32_mulss_round_mask: 3474 case X86::BI__builtin_ia32_mulsd_round_mask: 3475 case X86::BI__builtin_ia32_subss_round_mask: 3476 case X86::BI__builtin_ia32_subsd_round_mask: 3477 case X86::BI__builtin_ia32_scalefpd512_mask: 3478 case X86::BI__builtin_ia32_scalefps512_mask: 3479 case X86::BI__builtin_ia32_scalefsd_round_mask: 3480 case X86::BI__builtin_ia32_scalefss_round_mask: 3481 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3482 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3483 case X86::BI__builtin_ia32_sqrtss_round_mask: 3484 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3485 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3486 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3487 case X86::BI__builtin_ia32_vfmaddss3_mask: 3488 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3489 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3490 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3491 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3492 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3493 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3494 case X86::BI__builtin_ia32_vfmaddps512_mask: 3495 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3496 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3497 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3498 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3499 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3500 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3501 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3502 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3503 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3504 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3505 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3506 ArgNum = 4; 3507 HasRC = true; 3508 break; 3509 } 3510 3511 llvm::APSInt Result; 3512 3513 // We can't check the value of a dependent argument. 3514 Expr *Arg = TheCall->getArg(ArgNum); 3515 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3516 return false; 3517 3518 // Check constant-ness first. 3519 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3520 return true; 3521 3522 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3523 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3524 // combined with ROUND_NO_EXC. 3525 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3526 Result == 8/*ROUND_NO_EXC*/ || 3527 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3528 return false; 3529 3530 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3531 << Arg->getSourceRange(); 3532 } 3533 3534 // Check if the gather/scatter scale is legal. 3535 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3536 CallExpr *TheCall) { 3537 unsigned ArgNum = 0; 3538 switch (BuiltinID) { 3539 default: 3540 return false; 3541 case X86::BI__builtin_ia32_gatherpfdpd: 3542 case X86::BI__builtin_ia32_gatherpfdps: 3543 case X86::BI__builtin_ia32_gatherpfqpd: 3544 case X86::BI__builtin_ia32_gatherpfqps: 3545 case X86::BI__builtin_ia32_scatterpfdpd: 3546 case X86::BI__builtin_ia32_scatterpfdps: 3547 case X86::BI__builtin_ia32_scatterpfqpd: 3548 case X86::BI__builtin_ia32_scatterpfqps: 3549 ArgNum = 3; 3550 break; 3551 case X86::BI__builtin_ia32_gatherd_pd: 3552 case X86::BI__builtin_ia32_gatherd_pd256: 3553 case X86::BI__builtin_ia32_gatherq_pd: 3554 case X86::BI__builtin_ia32_gatherq_pd256: 3555 case X86::BI__builtin_ia32_gatherd_ps: 3556 case X86::BI__builtin_ia32_gatherd_ps256: 3557 case X86::BI__builtin_ia32_gatherq_ps: 3558 case X86::BI__builtin_ia32_gatherq_ps256: 3559 case X86::BI__builtin_ia32_gatherd_q: 3560 case X86::BI__builtin_ia32_gatherd_q256: 3561 case X86::BI__builtin_ia32_gatherq_q: 3562 case X86::BI__builtin_ia32_gatherq_q256: 3563 case X86::BI__builtin_ia32_gatherd_d: 3564 case X86::BI__builtin_ia32_gatherd_d256: 3565 case X86::BI__builtin_ia32_gatherq_d: 3566 case X86::BI__builtin_ia32_gatherq_d256: 3567 case X86::BI__builtin_ia32_gather3div2df: 3568 case X86::BI__builtin_ia32_gather3div2di: 3569 case X86::BI__builtin_ia32_gather3div4df: 3570 case X86::BI__builtin_ia32_gather3div4di: 3571 case X86::BI__builtin_ia32_gather3div4sf: 3572 case X86::BI__builtin_ia32_gather3div4si: 3573 case X86::BI__builtin_ia32_gather3div8sf: 3574 case X86::BI__builtin_ia32_gather3div8si: 3575 case X86::BI__builtin_ia32_gather3siv2df: 3576 case X86::BI__builtin_ia32_gather3siv2di: 3577 case X86::BI__builtin_ia32_gather3siv4df: 3578 case X86::BI__builtin_ia32_gather3siv4di: 3579 case X86::BI__builtin_ia32_gather3siv4sf: 3580 case X86::BI__builtin_ia32_gather3siv4si: 3581 case X86::BI__builtin_ia32_gather3siv8sf: 3582 case X86::BI__builtin_ia32_gather3siv8si: 3583 case X86::BI__builtin_ia32_gathersiv8df: 3584 case X86::BI__builtin_ia32_gathersiv16sf: 3585 case X86::BI__builtin_ia32_gatherdiv8df: 3586 case X86::BI__builtin_ia32_gatherdiv16sf: 3587 case X86::BI__builtin_ia32_gathersiv8di: 3588 case X86::BI__builtin_ia32_gathersiv16si: 3589 case X86::BI__builtin_ia32_gatherdiv8di: 3590 case X86::BI__builtin_ia32_gatherdiv16si: 3591 case X86::BI__builtin_ia32_scatterdiv2df: 3592 case X86::BI__builtin_ia32_scatterdiv2di: 3593 case X86::BI__builtin_ia32_scatterdiv4df: 3594 case X86::BI__builtin_ia32_scatterdiv4di: 3595 case X86::BI__builtin_ia32_scatterdiv4sf: 3596 case X86::BI__builtin_ia32_scatterdiv4si: 3597 case X86::BI__builtin_ia32_scatterdiv8sf: 3598 case X86::BI__builtin_ia32_scatterdiv8si: 3599 case X86::BI__builtin_ia32_scattersiv2df: 3600 case X86::BI__builtin_ia32_scattersiv2di: 3601 case X86::BI__builtin_ia32_scattersiv4df: 3602 case X86::BI__builtin_ia32_scattersiv4di: 3603 case X86::BI__builtin_ia32_scattersiv4sf: 3604 case X86::BI__builtin_ia32_scattersiv4si: 3605 case X86::BI__builtin_ia32_scattersiv8sf: 3606 case X86::BI__builtin_ia32_scattersiv8si: 3607 case X86::BI__builtin_ia32_scattersiv8df: 3608 case X86::BI__builtin_ia32_scattersiv16sf: 3609 case X86::BI__builtin_ia32_scatterdiv8df: 3610 case X86::BI__builtin_ia32_scatterdiv16sf: 3611 case X86::BI__builtin_ia32_scattersiv8di: 3612 case X86::BI__builtin_ia32_scattersiv16si: 3613 case X86::BI__builtin_ia32_scatterdiv8di: 3614 case X86::BI__builtin_ia32_scatterdiv16si: 3615 ArgNum = 4; 3616 break; 3617 } 3618 3619 llvm::APSInt Result; 3620 3621 // We can't check the value of a dependent argument. 3622 Expr *Arg = TheCall->getArg(ArgNum); 3623 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3624 return false; 3625 3626 // Check constant-ness first. 3627 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3628 return true; 3629 3630 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3631 return false; 3632 3633 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3634 << Arg->getSourceRange(); 3635 } 3636 3637 static bool isX86_32Builtin(unsigned BuiltinID) { 3638 // These builtins only work on x86-32 targets. 3639 switch (BuiltinID) { 3640 case X86::BI__builtin_ia32_readeflags_u32: 3641 case X86::BI__builtin_ia32_writeeflags_u32: 3642 return true; 3643 } 3644 3645 return false; 3646 } 3647 3648 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3649 if (BuiltinID == X86::BI__builtin_cpu_supports) 3650 return SemaBuiltinCpuSupports(*this, TheCall); 3651 3652 if (BuiltinID == X86::BI__builtin_cpu_is) 3653 return SemaBuiltinCpuIs(*this, TheCall); 3654 3655 // Check for 32-bit only builtins on a 64-bit target. 3656 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3657 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3658 return Diag(TheCall->getCallee()->getBeginLoc(), 3659 diag::err_32_bit_builtin_64_bit_tgt); 3660 3661 // If the intrinsic has rounding or SAE make sure its valid. 3662 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3663 return true; 3664 3665 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3666 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3667 return true; 3668 3669 // For intrinsics which take an immediate value as part of the instruction, 3670 // range check them here. 3671 int i = 0, l = 0, u = 0; 3672 switch (BuiltinID) { 3673 default: 3674 return false; 3675 case X86::BI__builtin_ia32_vec_ext_v2si: 3676 case X86::BI__builtin_ia32_vec_ext_v2di: 3677 case X86::BI__builtin_ia32_vextractf128_pd256: 3678 case X86::BI__builtin_ia32_vextractf128_ps256: 3679 case X86::BI__builtin_ia32_vextractf128_si256: 3680 case X86::BI__builtin_ia32_extract128i256: 3681 case X86::BI__builtin_ia32_extractf64x4_mask: 3682 case X86::BI__builtin_ia32_extracti64x4_mask: 3683 case X86::BI__builtin_ia32_extractf32x8_mask: 3684 case X86::BI__builtin_ia32_extracti32x8_mask: 3685 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3686 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3687 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3688 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3689 i = 1; l = 0; u = 1; 3690 break; 3691 case X86::BI__builtin_ia32_vec_set_v2di: 3692 case X86::BI__builtin_ia32_vinsertf128_pd256: 3693 case X86::BI__builtin_ia32_vinsertf128_ps256: 3694 case X86::BI__builtin_ia32_vinsertf128_si256: 3695 case X86::BI__builtin_ia32_insert128i256: 3696 case X86::BI__builtin_ia32_insertf32x8: 3697 case X86::BI__builtin_ia32_inserti32x8: 3698 case X86::BI__builtin_ia32_insertf64x4: 3699 case X86::BI__builtin_ia32_inserti64x4: 3700 case X86::BI__builtin_ia32_insertf64x2_256: 3701 case X86::BI__builtin_ia32_inserti64x2_256: 3702 case X86::BI__builtin_ia32_insertf32x4_256: 3703 case X86::BI__builtin_ia32_inserti32x4_256: 3704 i = 2; l = 0; u = 1; 3705 break; 3706 case X86::BI__builtin_ia32_vpermilpd: 3707 case X86::BI__builtin_ia32_vec_ext_v4hi: 3708 case X86::BI__builtin_ia32_vec_ext_v4si: 3709 case X86::BI__builtin_ia32_vec_ext_v4sf: 3710 case X86::BI__builtin_ia32_vec_ext_v4di: 3711 case X86::BI__builtin_ia32_extractf32x4_mask: 3712 case X86::BI__builtin_ia32_extracti32x4_mask: 3713 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3714 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3715 i = 1; l = 0; u = 3; 3716 break; 3717 case X86::BI_mm_prefetch: 3718 case X86::BI__builtin_ia32_vec_ext_v8hi: 3719 case X86::BI__builtin_ia32_vec_ext_v8si: 3720 i = 1; l = 0; u = 7; 3721 break; 3722 case X86::BI__builtin_ia32_sha1rnds4: 3723 case X86::BI__builtin_ia32_blendpd: 3724 case X86::BI__builtin_ia32_shufpd: 3725 case X86::BI__builtin_ia32_vec_set_v4hi: 3726 case X86::BI__builtin_ia32_vec_set_v4si: 3727 case X86::BI__builtin_ia32_vec_set_v4di: 3728 case X86::BI__builtin_ia32_shuf_f32x4_256: 3729 case X86::BI__builtin_ia32_shuf_f64x2_256: 3730 case X86::BI__builtin_ia32_shuf_i32x4_256: 3731 case X86::BI__builtin_ia32_shuf_i64x2_256: 3732 case X86::BI__builtin_ia32_insertf64x2_512: 3733 case X86::BI__builtin_ia32_inserti64x2_512: 3734 case X86::BI__builtin_ia32_insertf32x4: 3735 case X86::BI__builtin_ia32_inserti32x4: 3736 i = 2; l = 0; u = 3; 3737 break; 3738 case X86::BI__builtin_ia32_vpermil2pd: 3739 case X86::BI__builtin_ia32_vpermil2pd256: 3740 case X86::BI__builtin_ia32_vpermil2ps: 3741 case X86::BI__builtin_ia32_vpermil2ps256: 3742 i = 3; l = 0; u = 3; 3743 break; 3744 case X86::BI__builtin_ia32_cmpb128_mask: 3745 case X86::BI__builtin_ia32_cmpw128_mask: 3746 case X86::BI__builtin_ia32_cmpd128_mask: 3747 case X86::BI__builtin_ia32_cmpq128_mask: 3748 case X86::BI__builtin_ia32_cmpb256_mask: 3749 case X86::BI__builtin_ia32_cmpw256_mask: 3750 case X86::BI__builtin_ia32_cmpd256_mask: 3751 case X86::BI__builtin_ia32_cmpq256_mask: 3752 case X86::BI__builtin_ia32_cmpb512_mask: 3753 case X86::BI__builtin_ia32_cmpw512_mask: 3754 case X86::BI__builtin_ia32_cmpd512_mask: 3755 case X86::BI__builtin_ia32_cmpq512_mask: 3756 case X86::BI__builtin_ia32_ucmpb128_mask: 3757 case X86::BI__builtin_ia32_ucmpw128_mask: 3758 case X86::BI__builtin_ia32_ucmpd128_mask: 3759 case X86::BI__builtin_ia32_ucmpq128_mask: 3760 case X86::BI__builtin_ia32_ucmpb256_mask: 3761 case X86::BI__builtin_ia32_ucmpw256_mask: 3762 case X86::BI__builtin_ia32_ucmpd256_mask: 3763 case X86::BI__builtin_ia32_ucmpq256_mask: 3764 case X86::BI__builtin_ia32_ucmpb512_mask: 3765 case X86::BI__builtin_ia32_ucmpw512_mask: 3766 case X86::BI__builtin_ia32_ucmpd512_mask: 3767 case X86::BI__builtin_ia32_ucmpq512_mask: 3768 case X86::BI__builtin_ia32_vpcomub: 3769 case X86::BI__builtin_ia32_vpcomuw: 3770 case X86::BI__builtin_ia32_vpcomud: 3771 case X86::BI__builtin_ia32_vpcomuq: 3772 case X86::BI__builtin_ia32_vpcomb: 3773 case X86::BI__builtin_ia32_vpcomw: 3774 case X86::BI__builtin_ia32_vpcomd: 3775 case X86::BI__builtin_ia32_vpcomq: 3776 case X86::BI__builtin_ia32_vec_set_v8hi: 3777 case X86::BI__builtin_ia32_vec_set_v8si: 3778 i = 2; l = 0; u = 7; 3779 break; 3780 case X86::BI__builtin_ia32_vpermilpd256: 3781 case X86::BI__builtin_ia32_roundps: 3782 case X86::BI__builtin_ia32_roundpd: 3783 case X86::BI__builtin_ia32_roundps256: 3784 case X86::BI__builtin_ia32_roundpd256: 3785 case X86::BI__builtin_ia32_getmantpd128_mask: 3786 case X86::BI__builtin_ia32_getmantpd256_mask: 3787 case X86::BI__builtin_ia32_getmantps128_mask: 3788 case X86::BI__builtin_ia32_getmantps256_mask: 3789 case X86::BI__builtin_ia32_getmantpd512_mask: 3790 case X86::BI__builtin_ia32_getmantps512_mask: 3791 case X86::BI__builtin_ia32_vec_ext_v16qi: 3792 case X86::BI__builtin_ia32_vec_ext_v16hi: 3793 i = 1; l = 0; u = 15; 3794 break; 3795 case X86::BI__builtin_ia32_pblendd128: 3796 case X86::BI__builtin_ia32_blendps: 3797 case X86::BI__builtin_ia32_blendpd256: 3798 case X86::BI__builtin_ia32_shufpd256: 3799 case X86::BI__builtin_ia32_roundss: 3800 case X86::BI__builtin_ia32_roundsd: 3801 case X86::BI__builtin_ia32_rangepd128_mask: 3802 case X86::BI__builtin_ia32_rangepd256_mask: 3803 case X86::BI__builtin_ia32_rangepd512_mask: 3804 case X86::BI__builtin_ia32_rangeps128_mask: 3805 case X86::BI__builtin_ia32_rangeps256_mask: 3806 case X86::BI__builtin_ia32_rangeps512_mask: 3807 case X86::BI__builtin_ia32_getmantsd_round_mask: 3808 case X86::BI__builtin_ia32_getmantss_round_mask: 3809 case X86::BI__builtin_ia32_vec_set_v16qi: 3810 case X86::BI__builtin_ia32_vec_set_v16hi: 3811 i = 2; l = 0; u = 15; 3812 break; 3813 case X86::BI__builtin_ia32_vec_ext_v32qi: 3814 i = 1; l = 0; u = 31; 3815 break; 3816 case X86::BI__builtin_ia32_cmpps: 3817 case X86::BI__builtin_ia32_cmpss: 3818 case X86::BI__builtin_ia32_cmppd: 3819 case X86::BI__builtin_ia32_cmpsd: 3820 case X86::BI__builtin_ia32_cmpps256: 3821 case X86::BI__builtin_ia32_cmppd256: 3822 case X86::BI__builtin_ia32_cmpps128_mask: 3823 case X86::BI__builtin_ia32_cmppd128_mask: 3824 case X86::BI__builtin_ia32_cmpps256_mask: 3825 case X86::BI__builtin_ia32_cmppd256_mask: 3826 case X86::BI__builtin_ia32_cmpps512_mask: 3827 case X86::BI__builtin_ia32_cmppd512_mask: 3828 case X86::BI__builtin_ia32_cmpsd_mask: 3829 case X86::BI__builtin_ia32_cmpss_mask: 3830 case X86::BI__builtin_ia32_vec_set_v32qi: 3831 i = 2; l = 0; u = 31; 3832 break; 3833 case X86::BI__builtin_ia32_permdf256: 3834 case X86::BI__builtin_ia32_permdi256: 3835 case X86::BI__builtin_ia32_permdf512: 3836 case X86::BI__builtin_ia32_permdi512: 3837 case X86::BI__builtin_ia32_vpermilps: 3838 case X86::BI__builtin_ia32_vpermilps256: 3839 case X86::BI__builtin_ia32_vpermilpd512: 3840 case X86::BI__builtin_ia32_vpermilps512: 3841 case X86::BI__builtin_ia32_pshufd: 3842 case X86::BI__builtin_ia32_pshufd256: 3843 case X86::BI__builtin_ia32_pshufd512: 3844 case X86::BI__builtin_ia32_pshufhw: 3845 case X86::BI__builtin_ia32_pshufhw256: 3846 case X86::BI__builtin_ia32_pshufhw512: 3847 case X86::BI__builtin_ia32_pshuflw: 3848 case X86::BI__builtin_ia32_pshuflw256: 3849 case X86::BI__builtin_ia32_pshuflw512: 3850 case X86::BI__builtin_ia32_vcvtps2ph: 3851 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3852 case X86::BI__builtin_ia32_vcvtps2ph256: 3853 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3854 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3855 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3856 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3857 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3858 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3859 case X86::BI__builtin_ia32_rndscaleps_mask: 3860 case X86::BI__builtin_ia32_rndscalepd_mask: 3861 case X86::BI__builtin_ia32_reducepd128_mask: 3862 case X86::BI__builtin_ia32_reducepd256_mask: 3863 case X86::BI__builtin_ia32_reducepd512_mask: 3864 case X86::BI__builtin_ia32_reduceps128_mask: 3865 case X86::BI__builtin_ia32_reduceps256_mask: 3866 case X86::BI__builtin_ia32_reduceps512_mask: 3867 case X86::BI__builtin_ia32_prold512: 3868 case X86::BI__builtin_ia32_prolq512: 3869 case X86::BI__builtin_ia32_prold128: 3870 case X86::BI__builtin_ia32_prold256: 3871 case X86::BI__builtin_ia32_prolq128: 3872 case X86::BI__builtin_ia32_prolq256: 3873 case X86::BI__builtin_ia32_prord512: 3874 case X86::BI__builtin_ia32_prorq512: 3875 case X86::BI__builtin_ia32_prord128: 3876 case X86::BI__builtin_ia32_prord256: 3877 case X86::BI__builtin_ia32_prorq128: 3878 case X86::BI__builtin_ia32_prorq256: 3879 case X86::BI__builtin_ia32_fpclasspd128_mask: 3880 case X86::BI__builtin_ia32_fpclasspd256_mask: 3881 case X86::BI__builtin_ia32_fpclassps128_mask: 3882 case X86::BI__builtin_ia32_fpclassps256_mask: 3883 case X86::BI__builtin_ia32_fpclassps512_mask: 3884 case X86::BI__builtin_ia32_fpclasspd512_mask: 3885 case X86::BI__builtin_ia32_fpclasssd_mask: 3886 case X86::BI__builtin_ia32_fpclassss_mask: 3887 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3888 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3889 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3890 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3891 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3892 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3893 case X86::BI__builtin_ia32_kshiftliqi: 3894 case X86::BI__builtin_ia32_kshiftlihi: 3895 case X86::BI__builtin_ia32_kshiftlisi: 3896 case X86::BI__builtin_ia32_kshiftlidi: 3897 case X86::BI__builtin_ia32_kshiftriqi: 3898 case X86::BI__builtin_ia32_kshiftrihi: 3899 case X86::BI__builtin_ia32_kshiftrisi: 3900 case X86::BI__builtin_ia32_kshiftridi: 3901 i = 1; l = 0; u = 255; 3902 break; 3903 case X86::BI__builtin_ia32_vperm2f128_pd256: 3904 case X86::BI__builtin_ia32_vperm2f128_ps256: 3905 case X86::BI__builtin_ia32_vperm2f128_si256: 3906 case X86::BI__builtin_ia32_permti256: 3907 case X86::BI__builtin_ia32_pblendw128: 3908 case X86::BI__builtin_ia32_pblendw256: 3909 case X86::BI__builtin_ia32_blendps256: 3910 case X86::BI__builtin_ia32_pblendd256: 3911 case X86::BI__builtin_ia32_palignr128: 3912 case X86::BI__builtin_ia32_palignr256: 3913 case X86::BI__builtin_ia32_palignr512: 3914 case X86::BI__builtin_ia32_alignq512: 3915 case X86::BI__builtin_ia32_alignd512: 3916 case X86::BI__builtin_ia32_alignd128: 3917 case X86::BI__builtin_ia32_alignd256: 3918 case X86::BI__builtin_ia32_alignq128: 3919 case X86::BI__builtin_ia32_alignq256: 3920 case X86::BI__builtin_ia32_vcomisd: 3921 case X86::BI__builtin_ia32_vcomiss: 3922 case X86::BI__builtin_ia32_shuf_f32x4: 3923 case X86::BI__builtin_ia32_shuf_f64x2: 3924 case X86::BI__builtin_ia32_shuf_i32x4: 3925 case X86::BI__builtin_ia32_shuf_i64x2: 3926 case X86::BI__builtin_ia32_shufpd512: 3927 case X86::BI__builtin_ia32_shufps: 3928 case X86::BI__builtin_ia32_shufps256: 3929 case X86::BI__builtin_ia32_shufps512: 3930 case X86::BI__builtin_ia32_dbpsadbw128: 3931 case X86::BI__builtin_ia32_dbpsadbw256: 3932 case X86::BI__builtin_ia32_dbpsadbw512: 3933 case X86::BI__builtin_ia32_vpshldd128: 3934 case X86::BI__builtin_ia32_vpshldd256: 3935 case X86::BI__builtin_ia32_vpshldd512: 3936 case X86::BI__builtin_ia32_vpshldq128: 3937 case X86::BI__builtin_ia32_vpshldq256: 3938 case X86::BI__builtin_ia32_vpshldq512: 3939 case X86::BI__builtin_ia32_vpshldw128: 3940 case X86::BI__builtin_ia32_vpshldw256: 3941 case X86::BI__builtin_ia32_vpshldw512: 3942 case X86::BI__builtin_ia32_vpshrdd128: 3943 case X86::BI__builtin_ia32_vpshrdd256: 3944 case X86::BI__builtin_ia32_vpshrdd512: 3945 case X86::BI__builtin_ia32_vpshrdq128: 3946 case X86::BI__builtin_ia32_vpshrdq256: 3947 case X86::BI__builtin_ia32_vpshrdq512: 3948 case X86::BI__builtin_ia32_vpshrdw128: 3949 case X86::BI__builtin_ia32_vpshrdw256: 3950 case X86::BI__builtin_ia32_vpshrdw512: 3951 i = 2; l = 0; u = 255; 3952 break; 3953 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3954 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3955 case X86::BI__builtin_ia32_fixupimmps512_mask: 3956 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3957 case X86::BI__builtin_ia32_fixupimmsd_mask: 3958 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3959 case X86::BI__builtin_ia32_fixupimmss_mask: 3960 case X86::BI__builtin_ia32_fixupimmss_maskz: 3961 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3962 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3963 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3964 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3965 case X86::BI__builtin_ia32_fixupimmps128_mask: 3966 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3967 case X86::BI__builtin_ia32_fixupimmps256_mask: 3968 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3969 case X86::BI__builtin_ia32_pternlogd512_mask: 3970 case X86::BI__builtin_ia32_pternlogd512_maskz: 3971 case X86::BI__builtin_ia32_pternlogq512_mask: 3972 case X86::BI__builtin_ia32_pternlogq512_maskz: 3973 case X86::BI__builtin_ia32_pternlogd128_mask: 3974 case X86::BI__builtin_ia32_pternlogd128_maskz: 3975 case X86::BI__builtin_ia32_pternlogd256_mask: 3976 case X86::BI__builtin_ia32_pternlogd256_maskz: 3977 case X86::BI__builtin_ia32_pternlogq128_mask: 3978 case X86::BI__builtin_ia32_pternlogq128_maskz: 3979 case X86::BI__builtin_ia32_pternlogq256_mask: 3980 case X86::BI__builtin_ia32_pternlogq256_maskz: 3981 i = 3; l = 0; u = 255; 3982 break; 3983 case X86::BI__builtin_ia32_gatherpfdpd: 3984 case X86::BI__builtin_ia32_gatherpfdps: 3985 case X86::BI__builtin_ia32_gatherpfqpd: 3986 case X86::BI__builtin_ia32_gatherpfqps: 3987 case X86::BI__builtin_ia32_scatterpfdpd: 3988 case X86::BI__builtin_ia32_scatterpfdps: 3989 case X86::BI__builtin_ia32_scatterpfqpd: 3990 case X86::BI__builtin_ia32_scatterpfqps: 3991 i = 4; l = 2; u = 3; 3992 break; 3993 case X86::BI__builtin_ia32_reducesd_mask: 3994 case X86::BI__builtin_ia32_reducess_mask: 3995 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3996 case X86::BI__builtin_ia32_rndscaless_round_mask: 3997 i = 4; l = 0; u = 255; 3998 break; 3999 } 4000 4001 // Note that we don't force a hard error on the range check here, allowing 4002 // template-generated or macro-generated dead code to potentially have out-of- 4003 // range values. These need to code generate, but don't need to necessarily 4004 // make any sense. We use a warning that defaults to an error. 4005 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4006 } 4007 4008 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4009 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4010 /// Returns true when the format fits the function and the FormatStringInfo has 4011 /// been populated. 4012 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4013 FormatStringInfo *FSI) { 4014 FSI->HasVAListArg = Format->getFirstArg() == 0; 4015 FSI->FormatIdx = Format->getFormatIdx() - 1; 4016 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4017 4018 // The way the format attribute works in GCC, the implicit this argument 4019 // of member functions is counted. However, it doesn't appear in our own 4020 // lists, so decrement format_idx in that case. 4021 if (IsCXXMember) { 4022 if(FSI->FormatIdx == 0) 4023 return false; 4024 --FSI->FormatIdx; 4025 if (FSI->FirstDataArg != 0) 4026 --FSI->FirstDataArg; 4027 } 4028 return true; 4029 } 4030 4031 /// Checks if a the given expression evaluates to null. 4032 /// 4033 /// Returns true if the value evaluates to null. 4034 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4035 // If the expression has non-null type, it doesn't evaluate to null. 4036 if (auto nullability 4037 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4038 if (*nullability == NullabilityKind::NonNull) 4039 return false; 4040 } 4041 4042 // As a special case, transparent unions initialized with zero are 4043 // considered null for the purposes of the nonnull attribute. 4044 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4045 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4046 if (const CompoundLiteralExpr *CLE = 4047 dyn_cast<CompoundLiteralExpr>(Expr)) 4048 if (const InitListExpr *ILE = 4049 dyn_cast<InitListExpr>(CLE->getInitializer())) 4050 Expr = ILE->getInit(0); 4051 } 4052 4053 bool Result; 4054 return (!Expr->isValueDependent() && 4055 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4056 !Result); 4057 } 4058 4059 static void CheckNonNullArgument(Sema &S, 4060 const Expr *ArgExpr, 4061 SourceLocation CallSiteLoc) { 4062 if (CheckNonNullExpr(S, ArgExpr)) 4063 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4064 S.PDiag(diag::warn_null_arg) 4065 << ArgExpr->getSourceRange()); 4066 } 4067 4068 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4069 FormatStringInfo FSI; 4070 if ((GetFormatStringType(Format) == FST_NSString) && 4071 getFormatStringInfo(Format, false, &FSI)) { 4072 Idx = FSI.FormatIdx; 4073 return true; 4074 } 4075 return false; 4076 } 4077 4078 /// Diagnose use of %s directive in an NSString which is being passed 4079 /// as formatting string to formatting method. 4080 static void 4081 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4082 const NamedDecl *FDecl, 4083 Expr **Args, 4084 unsigned NumArgs) { 4085 unsigned Idx = 0; 4086 bool Format = false; 4087 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4088 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4089 Idx = 2; 4090 Format = true; 4091 } 4092 else 4093 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4094 if (S.GetFormatNSStringIdx(I, Idx)) { 4095 Format = true; 4096 break; 4097 } 4098 } 4099 if (!Format || NumArgs <= Idx) 4100 return; 4101 const Expr *FormatExpr = Args[Idx]; 4102 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4103 FormatExpr = CSCE->getSubExpr(); 4104 const StringLiteral *FormatString; 4105 if (const ObjCStringLiteral *OSL = 4106 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4107 FormatString = OSL->getString(); 4108 else 4109 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4110 if (!FormatString) 4111 return; 4112 if (S.FormatStringHasSArg(FormatString)) { 4113 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4114 << "%s" << 1 << 1; 4115 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4116 << FDecl->getDeclName(); 4117 } 4118 } 4119 4120 /// Determine whether the given type has a non-null nullability annotation. 4121 static bool isNonNullType(ASTContext &ctx, QualType type) { 4122 if (auto nullability = type->getNullability(ctx)) 4123 return *nullability == NullabilityKind::NonNull; 4124 4125 return false; 4126 } 4127 4128 static void CheckNonNullArguments(Sema &S, 4129 const NamedDecl *FDecl, 4130 const FunctionProtoType *Proto, 4131 ArrayRef<const Expr *> Args, 4132 SourceLocation CallSiteLoc) { 4133 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4134 4135 // Already checked by by constant evaluator. 4136 if (S.isConstantEvaluated()) 4137 return; 4138 // Check the attributes attached to the method/function itself. 4139 llvm::SmallBitVector NonNullArgs; 4140 if (FDecl) { 4141 // Handle the nonnull attribute on the function/method declaration itself. 4142 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4143 if (!NonNull->args_size()) { 4144 // Easy case: all pointer arguments are nonnull. 4145 for (const auto *Arg : Args) 4146 if (S.isValidPointerAttrType(Arg->getType())) 4147 CheckNonNullArgument(S, Arg, CallSiteLoc); 4148 return; 4149 } 4150 4151 for (const ParamIdx &Idx : NonNull->args()) { 4152 unsigned IdxAST = Idx.getASTIndex(); 4153 if (IdxAST >= Args.size()) 4154 continue; 4155 if (NonNullArgs.empty()) 4156 NonNullArgs.resize(Args.size()); 4157 NonNullArgs.set(IdxAST); 4158 } 4159 } 4160 } 4161 4162 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4163 // Handle the nonnull attribute on the parameters of the 4164 // function/method. 4165 ArrayRef<ParmVarDecl*> parms; 4166 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4167 parms = FD->parameters(); 4168 else 4169 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4170 4171 unsigned ParamIndex = 0; 4172 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4173 I != E; ++I, ++ParamIndex) { 4174 const ParmVarDecl *PVD = *I; 4175 if (PVD->hasAttr<NonNullAttr>() || 4176 isNonNullType(S.Context, PVD->getType())) { 4177 if (NonNullArgs.empty()) 4178 NonNullArgs.resize(Args.size()); 4179 4180 NonNullArgs.set(ParamIndex); 4181 } 4182 } 4183 } else { 4184 // If we have a non-function, non-method declaration but no 4185 // function prototype, try to dig out the function prototype. 4186 if (!Proto) { 4187 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4188 QualType type = VD->getType().getNonReferenceType(); 4189 if (auto pointerType = type->getAs<PointerType>()) 4190 type = pointerType->getPointeeType(); 4191 else if (auto blockType = type->getAs<BlockPointerType>()) 4192 type = blockType->getPointeeType(); 4193 // FIXME: data member pointers? 4194 4195 // Dig out the function prototype, if there is one. 4196 Proto = type->getAs<FunctionProtoType>(); 4197 } 4198 } 4199 4200 // Fill in non-null argument information from the nullability 4201 // information on the parameter types (if we have them). 4202 if (Proto) { 4203 unsigned Index = 0; 4204 for (auto paramType : Proto->getParamTypes()) { 4205 if (isNonNullType(S.Context, paramType)) { 4206 if (NonNullArgs.empty()) 4207 NonNullArgs.resize(Args.size()); 4208 4209 NonNullArgs.set(Index); 4210 } 4211 4212 ++Index; 4213 } 4214 } 4215 } 4216 4217 // Check for non-null arguments. 4218 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4219 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4220 if (NonNullArgs[ArgIndex]) 4221 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4222 } 4223 } 4224 4225 /// Handles the checks for format strings, non-POD arguments to vararg 4226 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4227 /// attributes. 4228 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4229 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4230 bool IsMemberFunction, SourceLocation Loc, 4231 SourceRange Range, VariadicCallType CallType) { 4232 // FIXME: We should check as much as we can in the template definition. 4233 if (CurContext->isDependentContext()) 4234 return; 4235 4236 // Printf and scanf checking. 4237 llvm::SmallBitVector CheckedVarArgs; 4238 if (FDecl) { 4239 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4240 // Only create vector if there are format attributes. 4241 CheckedVarArgs.resize(Args.size()); 4242 4243 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4244 CheckedVarArgs); 4245 } 4246 } 4247 4248 // Refuse POD arguments that weren't caught by the format string 4249 // checks above. 4250 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4251 if (CallType != VariadicDoesNotApply && 4252 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4253 unsigned NumParams = Proto ? Proto->getNumParams() 4254 : FDecl && isa<FunctionDecl>(FDecl) 4255 ? cast<FunctionDecl>(FDecl)->getNumParams() 4256 : FDecl && isa<ObjCMethodDecl>(FDecl) 4257 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4258 : 0; 4259 4260 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4261 // Args[ArgIdx] can be null in malformed code. 4262 if (const Expr *Arg = Args[ArgIdx]) { 4263 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4264 checkVariadicArgument(Arg, CallType); 4265 } 4266 } 4267 } 4268 4269 if (FDecl || Proto) { 4270 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4271 4272 // Type safety checking. 4273 if (FDecl) { 4274 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4275 CheckArgumentWithTypeTag(I, Args, Loc); 4276 } 4277 } 4278 4279 if (FD) 4280 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4281 } 4282 4283 /// CheckConstructorCall - Check a constructor call for correctness and safety 4284 /// properties not enforced by the C type system. 4285 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4286 ArrayRef<const Expr *> Args, 4287 const FunctionProtoType *Proto, 4288 SourceLocation Loc) { 4289 VariadicCallType CallType = 4290 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4291 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4292 Loc, SourceRange(), CallType); 4293 } 4294 4295 /// CheckFunctionCall - Check a direct function call for various correctness 4296 /// and safety properties not strictly enforced by the C type system. 4297 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4298 const FunctionProtoType *Proto) { 4299 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4300 isa<CXXMethodDecl>(FDecl); 4301 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4302 IsMemberOperatorCall; 4303 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4304 TheCall->getCallee()); 4305 Expr** Args = TheCall->getArgs(); 4306 unsigned NumArgs = TheCall->getNumArgs(); 4307 4308 Expr *ImplicitThis = nullptr; 4309 if (IsMemberOperatorCall) { 4310 // If this is a call to a member operator, hide the first argument 4311 // from checkCall. 4312 // FIXME: Our choice of AST representation here is less than ideal. 4313 ImplicitThis = Args[0]; 4314 ++Args; 4315 --NumArgs; 4316 } else if (IsMemberFunction) 4317 ImplicitThis = 4318 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4319 4320 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4321 IsMemberFunction, TheCall->getRParenLoc(), 4322 TheCall->getCallee()->getSourceRange(), CallType); 4323 4324 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4325 // None of the checks below are needed for functions that don't have 4326 // simple names (e.g., C++ conversion functions). 4327 if (!FnInfo) 4328 return false; 4329 4330 CheckAbsoluteValueFunction(TheCall, FDecl); 4331 CheckMaxUnsignedZero(TheCall, FDecl); 4332 4333 if (getLangOpts().ObjC) 4334 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4335 4336 unsigned CMId = FDecl->getMemoryFunctionKind(); 4337 if (CMId == 0) 4338 return false; 4339 4340 // Handle memory setting and copying functions. 4341 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4342 CheckStrlcpycatArguments(TheCall, FnInfo); 4343 else if (CMId == Builtin::BIstrncat) 4344 CheckStrncatArguments(TheCall, FnInfo); 4345 else 4346 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4347 4348 return false; 4349 } 4350 4351 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4352 ArrayRef<const Expr *> Args) { 4353 VariadicCallType CallType = 4354 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4355 4356 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4357 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4358 CallType); 4359 4360 return false; 4361 } 4362 4363 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4364 const FunctionProtoType *Proto) { 4365 QualType Ty; 4366 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4367 Ty = V->getType().getNonReferenceType(); 4368 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4369 Ty = F->getType().getNonReferenceType(); 4370 else 4371 return false; 4372 4373 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4374 !Ty->isFunctionProtoType()) 4375 return false; 4376 4377 VariadicCallType CallType; 4378 if (!Proto || !Proto->isVariadic()) { 4379 CallType = VariadicDoesNotApply; 4380 } else if (Ty->isBlockPointerType()) { 4381 CallType = VariadicBlock; 4382 } else { // Ty->isFunctionPointerType() 4383 CallType = VariadicFunction; 4384 } 4385 4386 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4387 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4388 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4389 TheCall->getCallee()->getSourceRange(), CallType); 4390 4391 return false; 4392 } 4393 4394 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4395 /// such as function pointers returned from functions. 4396 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4397 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4398 TheCall->getCallee()); 4399 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4400 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4401 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4402 TheCall->getCallee()->getSourceRange(), CallType); 4403 4404 return false; 4405 } 4406 4407 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4408 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4409 return false; 4410 4411 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4412 switch (Op) { 4413 case AtomicExpr::AO__c11_atomic_init: 4414 case AtomicExpr::AO__opencl_atomic_init: 4415 llvm_unreachable("There is no ordering argument for an init"); 4416 4417 case AtomicExpr::AO__c11_atomic_load: 4418 case AtomicExpr::AO__opencl_atomic_load: 4419 case AtomicExpr::AO__atomic_load_n: 4420 case AtomicExpr::AO__atomic_load: 4421 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4422 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4423 4424 case AtomicExpr::AO__c11_atomic_store: 4425 case AtomicExpr::AO__opencl_atomic_store: 4426 case AtomicExpr::AO__atomic_store: 4427 case AtomicExpr::AO__atomic_store_n: 4428 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4429 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4430 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4431 4432 default: 4433 return true; 4434 } 4435 } 4436 4437 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4438 AtomicExpr::AtomicOp Op) { 4439 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4440 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4441 4442 // All the non-OpenCL operations take one of the following forms. 4443 // The OpenCL operations take the __c11 forms with one extra argument for 4444 // synchronization scope. 4445 enum { 4446 // C __c11_atomic_init(A *, C) 4447 Init, 4448 4449 // C __c11_atomic_load(A *, int) 4450 Load, 4451 4452 // void __atomic_load(A *, CP, int) 4453 LoadCopy, 4454 4455 // void __atomic_store(A *, CP, int) 4456 Copy, 4457 4458 // C __c11_atomic_add(A *, M, int) 4459 Arithmetic, 4460 4461 // C __atomic_exchange_n(A *, CP, int) 4462 Xchg, 4463 4464 // void __atomic_exchange(A *, C *, CP, int) 4465 GNUXchg, 4466 4467 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4468 C11CmpXchg, 4469 4470 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4471 GNUCmpXchg 4472 } Form = Init; 4473 4474 const unsigned NumForm = GNUCmpXchg + 1; 4475 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4476 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4477 // where: 4478 // C is an appropriate type, 4479 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4480 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4481 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4482 // the int parameters are for orderings. 4483 4484 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4485 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4486 "need to update code for modified forms"); 4487 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4488 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4489 AtomicExpr::AO__atomic_load, 4490 "need to update code for modified C11 atomics"); 4491 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4492 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4493 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4494 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4495 IsOpenCL; 4496 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4497 Op == AtomicExpr::AO__atomic_store_n || 4498 Op == AtomicExpr::AO__atomic_exchange_n || 4499 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4500 bool IsAddSub = false; 4501 bool IsMinMax = false; 4502 4503 switch (Op) { 4504 case AtomicExpr::AO__c11_atomic_init: 4505 case AtomicExpr::AO__opencl_atomic_init: 4506 Form = Init; 4507 break; 4508 4509 case AtomicExpr::AO__c11_atomic_load: 4510 case AtomicExpr::AO__opencl_atomic_load: 4511 case AtomicExpr::AO__atomic_load_n: 4512 Form = Load; 4513 break; 4514 4515 case AtomicExpr::AO__atomic_load: 4516 Form = LoadCopy; 4517 break; 4518 4519 case AtomicExpr::AO__c11_atomic_store: 4520 case AtomicExpr::AO__opencl_atomic_store: 4521 case AtomicExpr::AO__atomic_store: 4522 case AtomicExpr::AO__atomic_store_n: 4523 Form = Copy; 4524 break; 4525 4526 case AtomicExpr::AO__c11_atomic_fetch_add: 4527 case AtomicExpr::AO__c11_atomic_fetch_sub: 4528 case AtomicExpr::AO__opencl_atomic_fetch_add: 4529 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4530 case AtomicExpr::AO__opencl_atomic_fetch_min: 4531 case AtomicExpr::AO__opencl_atomic_fetch_max: 4532 case AtomicExpr::AO__atomic_fetch_add: 4533 case AtomicExpr::AO__atomic_fetch_sub: 4534 case AtomicExpr::AO__atomic_add_fetch: 4535 case AtomicExpr::AO__atomic_sub_fetch: 4536 IsAddSub = true; 4537 LLVM_FALLTHROUGH; 4538 case AtomicExpr::AO__c11_atomic_fetch_and: 4539 case AtomicExpr::AO__c11_atomic_fetch_or: 4540 case AtomicExpr::AO__c11_atomic_fetch_xor: 4541 case AtomicExpr::AO__opencl_atomic_fetch_and: 4542 case AtomicExpr::AO__opencl_atomic_fetch_or: 4543 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4544 case AtomicExpr::AO__atomic_fetch_and: 4545 case AtomicExpr::AO__atomic_fetch_or: 4546 case AtomicExpr::AO__atomic_fetch_xor: 4547 case AtomicExpr::AO__atomic_fetch_nand: 4548 case AtomicExpr::AO__atomic_and_fetch: 4549 case AtomicExpr::AO__atomic_or_fetch: 4550 case AtomicExpr::AO__atomic_xor_fetch: 4551 case AtomicExpr::AO__atomic_nand_fetch: 4552 Form = Arithmetic; 4553 break; 4554 4555 case AtomicExpr::AO__atomic_fetch_min: 4556 case AtomicExpr::AO__atomic_fetch_max: 4557 IsMinMax = true; 4558 Form = Arithmetic; 4559 break; 4560 4561 case AtomicExpr::AO__c11_atomic_exchange: 4562 case AtomicExpr::AO__opencl_atomic_exchange: 4563 case AtomicExpr::AO__atomic_exchange_n: 4564 Form = Xchg; 4565 break; 4566 4567 case AtomicExpr::AO__atomic_exchange: 4568 Form = GNUXchg; 4569 break; 4570 4571 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4572 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4573 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4574 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4575 Form = C11CmpXchg; 4576 break; 4577 4578 case AtomicExpr::AO__atomic_compare_exchange: 4579 case AtomicExpr::AO__atomic_compare_exchange_n: 4580 Form = GNUCmpXchg; 4581 break; 4582 } 4583 4584 unsigned AdjustedNumArgs = NumArgs[Form]; 4585 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4586 ++AdjustedNumArgs; 4587 // Check we have the right number of arguments. 4588 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4589 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4590 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4591 << TheCall->getCallee()->getSourceRange(); 4592 return ExprError(); 4593 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4594 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4595 diag::err_typecheck_call_too_many_args) 4596 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4597 << TheCall->getCallee()->getSourceRange(); 4598 return ExprError(); 4599 } 4600 4601 // Inspect the first argument of the atomic operation. 4602 Expr *Ptr = TheCall->getArg(0); 4603 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4604 if (ConvertedPtr.isInvalid()) 4605 return ExprError(); 4606 4607 Ptr = ConvertedPtr.get(); 4608 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4609 if (!pointerType) { 4610 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4611 << Ptr->getType() << Ptr->getSourceRange(); 4612 return ExprError(); 4613 } 4614 4615 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4616 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4617 QualType ValType = AtomTy; // 'C' 4618 if (IsC11) { 4619 if (!AtomTy->isAtomicType()) { 4620 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4621 << Ptr->getType() << Ptr->getSourceRange(); 4622 return ExprError(); 4623 } 4624 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4625 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4626 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4627 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4628 << Ptr->getSourceRange(); 4629 return ExprError(); 4630 } 4631 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4632 } else if (Form != Load && Form != LoadCopy) { 4633 if (ValType.isConstQualified()) { 4634 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4635 << Ptr->getType() << Ptr->getSourceRange(); 4636 return ExprError(); 4637 } 4638 } 4639 4640 // For an arithmetic operation, the implied arithmetic must be well-formed. 4641 if (Form == Arithmetic) { 4642 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4643 if (IsAddSub && !ValType->isIntegerType() 4644 && !ValType->isPointerType()) { 4645 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4646 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4647 return ExprError(); 4648 } 4649 if (IsMinMax) { 4650 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4651 if (!BT || (BT->getKind() != BuiltinType::Int && 4652 BT->getKind() != BuiltinType::UInt)) { 4653 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4654 return ExprError(); 4655 } 4656 } 4657 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4658 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4659 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4660 return ExprError(); 4661 } 4662 if (IsC11 && ValType->isPointerType() && 4663 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4664 diag::err_incomplete_type)) { 4665 return ExprError(); 4666 } 4667 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4668 // For __atomic_*_n operations, the value type must be a scalar integral or 4669 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4670 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4671 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4672 return ExprError(); 4673 } 4674 4675 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4676 !AtomTy->isScalarType()) { 4677 // For GNU atomics, require a trivially-copyable type. This is not part of 4678 // the GNU atomics specification, but we enforce it for sanity. 4679 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4680 << Ptr->getType() << Ptr->getSourceRange(); 4681 return ExprError(); 4682 } 4683 4684 switch (ValType.getObjCLifetime()) { 4685 case Qualifiers::OCL_None: 4686 case Qualifiers::OCL_ExplicitNone: 4687 // okay 4688 break; 4689 4690 case Qualifiers::OCL_Weak: 4691 case Qualifiers::OCL_Strong: 4692 case Qualifiers::OCL_Autoreleasing: 4693 // FIXME: Can this happen? By this point, ValType should be known 4694 // to be trivially copyable. 4695 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4696 << ValType << Ptr->getSourceRange(); 4697 return ExprError(); 4698 } 4699 4700 // All atomic operations have an overload which takes a pointer to a volatile 4701 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4702 // into the result or the other operands. Similarly atomic_load takes a 4703 // pointer to a const 'A'. 4704 ValType.removeLocalVolatile(); 4705 ValType.removeLocalConst(); 4706 QualType ResultType = ValType; 4707 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4708 Form == Init) 4709 ResultType = Context.VoidTy; 4710 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4711 ResultType = Context.BoolTy; 4712 4713 // The type of a parameter passed 'by value'. In the GNU atomics, such 4714 // arguments are actually passed as pointers. 4715 QualType ByValType = ValType; // 'CP' 4716 bool IsPassedByAddress = false; 4717 if (!IsC11 && !IsN) { 4718 ByValType = Ptr->getType(); 4719 IsPassedByAddress = true; 4720 } 4721 4722 // The first argument's non-CV pointer type is used to deduce the type of 4723 // subsequent arguments, except for: 4724 // - weak flag (always converted to bool) 4725 // - memory order (always converted to int) 4726 // - scope (always converted to int) 4727 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4728 QualType Ty; 4729 if (i < NumVals[Form] + 1) { 4730 switch (i) { 4731 case 0: 4732 // The first argument is always a pointer. It has a fixed type. 4733 // It is always dereferenced, a nullptr is undefined. 4734 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4735 // Nothing else to do: we already know all we want about this pointer. 4736 continue; 4737 case 1: 4738 // The second argument is the non-atomic operand. For arithmetic, this 4739 // is always passed by value, and for a compare_exchange it is always 4740 // passed by address. For the rest, GNU uses by-address and C11 uses 4741 // by-value. 4742 assert(Form != Load); 4743 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4744 Ty = ValType; 4745 else if (Form == Copy || Form == Xchg) { 4746 if (IsPassedByAddress) 4747 // The value pointer is always dereferenced, a nullptr is undefined. 4748 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4749 Ty = ByValType; 4750 } else if (Form == Arithmetic) 4751 Ty = Context.getPointerDiffType(); 4752 else { 4753 Expr *ValArg = TheCall->getArg(i); 4754 // The value pointer is always dereferenced, a nullptr is undefined. 4755 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4756 LangAS AS = LangAS::Default; 4757 // Keep address space of non-atomic pointer type. 4758 if (const PointerType *PtrTy = 4759 ValArg->getType()->getAs<PointerType>()) { 4760 AS = PtrTy->getPointeeType().getAddressSpace(); 4761 } 4762 Ty = Context.getPointerType( 4763 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4764 } 4765 break; 4766 case 2: 4767 // The third argument to compare_exchange / GNU exchange is the desired 4768 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4769 if (IsPassedByAddress) 4770 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4771 Ty = ByValType; 4772 break; 4773 case 3: 4774 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4775 Ty = Context.BoolTy; 4776 break; 4777 } 4778 } else { 4779 // The order(s) and scope are always converted to int. 4780 Ty = Context.IntTy; 4781 } 4782 4783 InitializedEntity Entity = 4784 InitializedEntity::InitializeParameter(Context, Ty, false); 4785 ExprResult Arg = TheCall->getArg(i); 4786 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4787 if (Arg.isInvalid()) 4788 return true; 4789 TheCall->setArg(i, Arg.get()); 4790 } 4791 4792 // Permute the arguments into a 'consistent' order. 4793 SmallVector<Expr*, 5> SubExprs; 4794 SubExprs.push_back(Ptr); 4795 switch (Form) { 4796 case Init: 4797 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4798 SubExprs.push_back(TheCall->getArg(1)); // Val1 4799 break; 4800 case Load: 4801 SubExprs.push_back(TheCall->getArg(1)); // Order 4802 break; 4803 case LoadCopy: 4804 case Copy: 4805 case Arithmetic: 4806 case Xchg: 4807 SubExprs.push_back(TheCall->getArg(2)); // Order 4808 SubExprs.push_back(TheCall->getArg(1)); // Val1 4809 break; 4810 case GNUXchg: 4811 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4812 SubExprs.push_back(TheCall->getArg(3)); // Order 4813 SubExprs.push_back(TheCall->getArg(1)); // Val1 4814 SubExprs.push_back(TheCall->getArg(2)); // Val2 4815 break; 4816 case C11CmpXchg: 4817 SubExprs.push_back(TheCall->getArg(3)); // Order 4818 SubExprs.push_back(TheCall->getArg(1)); // Val1 4819 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4820 SubExprs.push_back(TheCall->getArg(2)); // Val2 4821 break; 4822 case GNUCmpXchg: 4823 SubExprs.push_back(TheCall->getArg(4)); // Order 4824 SubExprs.push_back(TheCall->getArg(1)); // Val1 4825 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4826 SubExprs.push_back(TheCall->getArg(2)); // Val2 4827 SubExprs.push_back(TheCall->getArg(3)); // Weak 4828 break; 4829 } 4830 4831 if (SubExprs.size() >= 2 && Form != Init) { 4832 llvm::APSInt Result(32); 4833 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4834 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4835 Diag(SubExprs[1]->getBeginLoc(), 4836 diag::warn_atomic_op_has_invalid_memory_order) 4837 << SubExprs[1]->getSourceRange(); 4838 } 4839 4840 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4841 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4842 llvm::APSInt Result(32); 4843 if (Scope->isIntegerConstantExpr(Result, Context) && 4844 !ScopeModel->isValid(Result.getZExtValue())) { 4845 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4846 << Scope->getSourceRange(); 4847 } 4848 SubExprs.push_back(Scope); 4849 } 4850 4851 AtomicExpr *AE = 4852 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4853 ResultType, Op, TheCall->getRParenLoc()); 4854 4855 if ((Op == AtomicExpr::AO__c11_atomic_load || 4856 Op == AtomicExpr::AO__c11_atomic_store || 4857 Op == AtomicExpr::AO__opencl_atomic_load || 4858 Op == AtomicExpr::AO__opencl_atomic_store ) && 4859 Context.AtomicUsesUnsupportedLibcall(AE)) 4860 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4861 << ((Op == AtomicExpr::AO__c11_atomic_load || 4862 Op == AtomicExpr::AO__opencl_atomic_load) 4863 ? 0 4864 : 1); 4865 4866 return AE; 4867 } 4868 4869 /// checkBuiltinArgument - Given a call to a builtin function, perform 4870 /// normal type-checking on the given argument, updating the call in 4871 /// place. This is useful when a builtin function requires custom 4872 /// type-checking for some of its arguments but not necessarily all of 4873 /// them. 4874 /// 4875 /// Returns true on error. 4876 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4877 FunctionDecl *Fn = E->getDirectCallee(); 4878 assert(Fn && "builtin call without direct callee!"); 4879 4880 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4881 InitializedEntity Entity = 4882 InitializedEntity::InitializeParameter(S.Context, Param); 4883 4884 ExprResult Arg = E->getArg(0); 4885 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4886 if (Arg.isInvalid()) 4887 return true; 4888 4889 E->setArg(ArgIndex, Arg.get()); 4890 return false; 4891 } 4892 4893 /// We have a call to a function like __sync_fetch_and_add, which is an 4894 /// overloaded function based on the pointer type of its first argument. 4895 /// The main BuildCallExpr routines have already promoted the types of 4896 /// arguments because all of these calls are prototyped as void(...). 4897 /// 4898 /// This function goes through and does final semantic checking for these 4899 /// builtins, as well as generating any warnings. 4900 ExprResult 4901 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4902 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4903 Expr *Callee = TheCall->getCallee(); 4904 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4905 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4906 4907 // Ensure that we have at least one argument to do type inference from. 4908 if (TheCall->getNumArgs() < 1) { 4909 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4910 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4911 return ExprError(); 4912 } 4913 4914 // Inspect the first argument of the atomic builtin. This should always be 4915 // a pointer type, whose element is an integral scalar or pointer type. 4916 // Because it is a pointer type, we don't have to worry about any implicit 4917 // casts here. 4918 // FIXME: We don't allow floating point scalars as input. 4919 Expr *FirstArg = TheCall->getArg(0); 4920 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4921 if (FirstArgResult.isInvalid()) 4922 return ExprError(); 4923 FirstArg = FirstArgResult.get(); 4924 TheCall->setArg(0, FirstArg); 4925 4926 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4927 if (!pointerType) { 4928 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4929 << FirstArg->getType() << FirstArg->getSourceRange(); 4930 return ExprError(); 4931 } 4932 4933 QualType ValType = pointerType->getPointeeType(); 4934 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4935 !ValType->isBlockPointerType()) { 4936 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4937 << FirstArg->getType() << FirstArg->getSourceRange(); 4938 return ExprError(); 4939 } 4940 4941 if (ValType.isConstQualified()) { 4942 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4943 << FirstArg->getType() << FirstArg->getSourceRange(); 4944 return ExprError(); 4945 } 4946 4947 switch (ValType.getObjCLifetime()) { 4948 case Qualifiers::OCL_None: 4949 case Qualifiers::OCL_ExplicitNone: 4950 // okay 4951 break; 4952 4953 case Qualifiers::OCL_Weak: 4954 case Qualifiers::OCL_Strong: 4955 case Qualifiers::OCL_Autoreleasing: 4956 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4957 << ValType << FirstArg->getSourceRange(); 4958 return ExprError(); 4959 } 4960 4961 // Strip any qualifiers off ValType. 4962 ValType = ValType.getUnqualifiedType(); 4963 4964 // The majority of builtins return a value, but a few have special return 4965 // types, so allow them to override appropriately below. 4966 QualType ResultType = ValType; 4967 4968 // We need to figure out which concrete builtin this maps onto. For example, 4969 // __sync_fetch_and_add with a 2 byte object turns into 4970 // __sync_fetch_and_add_2. 4971 #define BUILTIN_ROW(x) \ 4972 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4973 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4974 4975 static const unsigned BuiltinIndices[][5] = { 4976 BUILTIN_ROW(__sync_fetch_and_add), 4977 BUILTIN_ROW(__sync_fetch_and_sub), 4978 BUILTIN_ROW(__sync_fetch_and_or), 4979 BUILTIN_ROW(__sync_fetch_and_and), 4980 BUILTIN_ROW(__sync_fetch_and_xor), 4981 BUILTIN_ROW(__sync_fetch_and_nand), 4982 4983 BUILTIN_ROW(__sync_add_and_fetch), 4984 BUILTIN_ROW(__sync_sub_and_fetch), 4985 BUILTIN_ROW(__sync_and_and_fetch), 4986 BUILTIN_ROW(__sync_or_and_fetch), 4987 BUILTIN_ROW(__sync_xor_and_fetch), 4988 BUILTIN_ROW(__sync_nand_and_fetch), 4989 4990 BUILTIN_ROW(__sync_val_compare_and_swap), 4991 BUILTIN_ROW(__sync_bool_compare_and_swap), 4992 BUILTIN_ROW(__sync_lock_test_and_set), 4993 BUILTIN_ROW(__sync_lock_release), 4994 BUILTIN_ROW(__sync_swap) 4995 }; 4996 #undef BUILTIN_ROW 4997 4998 // Determine the index of the size. 4999 unsigned SizeIndex; 5000 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5001 case 1: SizeIndex = 0; break; 5002 case 2: SizeIndex = 1; break; 5003 case 4: SizeIndex = 2; break; 5004 case 8: SizeIndex = 3; break; 5005 case 16: SizeIndex = 4; break; 5006 default: 5007 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5008 << FirstArg->getType() << FirstArg->getSourceRange(); 5009 return ExprError(); 5010 } 5011 5012 // Each of these builtins has one pointer argument, followed by some number of 5013 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5014 // that we ignore. Find out which row of BuiltinIndices to read from as well 5015 // as the number of fixed args. 5016 unsigned BuiltinID = FDecl->getBuiltinID(); 5017 unsigned BuiltinIndex, NumFixed = 1; 5018 bool WarnAboutSemanticsChange = false; 5019 switch (BuiltinID) { 5020 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5021 case Builtin::BI__sync_fetch_and_add: 5022 case Builtin::BI__sync_fetch_and_add_1: 5023 case Builtin::BI__sync_fetch_and_add_2: 5024 case Builtin::BI__sync_fetch_and_add_4: 5025 case Builtin::BI__sync_fetch_and_add_8: 5026 case Builtin::BI__sync_fetch_and_add_16: 5027 BuiltinIndex = 0; 5028 break; 5029 5030 case Builtin::BI__sync_fetch_and_sub: 5031 case Builtin::BI__sync_fetch_and_sub_1: 5032 case Builtin::BI__sync_fetch_and_sub_2: 5033 case Builtin::BI__sync_fetch_and_sub_4: 5034 case Builtin::BI__sync_fetch_and_sub_8: 5035 case Builtin::BI__sync_fetch_and_sub_16: 5036 BuiltinIndex = 1; 5037 break; 5038 5039 case Builtin::BI__sync_fetch_and_or: 5040 case Builtin::BI__sync_fetch_and_or_1: 5041 case Builtin::BI__sync_fetch_and_or_2: 5042 case Builtin::BI__sync_fetch_and_or_4: 5043 case Builtin::BI__sync_fetch_and_or_8: 5044 case Builtin::BI__sync_fetch_and_or_16: 5045 BuiltinIndex = 2; 5046 break; 5047 5048 case Builtin::BI__sync_fetch_and_and: 5049 case Builtin::BI__sync_fetch_and_and_1: 5050 case Builtin::BI__sync_fetch_and_and_2: 5051 case Builtin::BI__sync_fetch_and_and_4: 5052 case Builtin::BI__sync_fetch_and_and_8: 5053 case Builtin::BI__sync_fetch_and_and_16: 5054 BuiltinIndex = 3; 5055 break; 5056 5057 case Builtin::BI__sync_fetch_and_xor: 5058 case Builtin::BI__sync_fetch_and_xor_1: 5059 case Builtin::BI__sync_fetch_and_xor_2: 5060 case Builtin::BI__sync_fetch_and_xor_4: 5061 case Builtin::BI__sync_fetch_and_xor_8: 5062 case Builtin::BI__sync_fetch_and_xor_16: 5063 BuiltinIndex = 4; 5064 break; 5065 5066 case Builtin::BI__sync_fetch_and_nand: 5067 case Builtin::BI__sync_fetch_and_nand_1: 5068 case Builtin::BI__sync_fetch_and_nand_2: 5069 case Builtin::BI__sync_fetch_and_nand_4: 5070 case Builtin::BI__sync_fetch_and_nand_8: 5071 case Builtin::BI__sync_fetch_and_nand_16: 5072 BuiltinIndex = 5; 5073 WarnAboutSemanticsChange = true; 5074 break; 5075 5076 case Builtin::BI__sync_add_and_fetch: 5077 case Builtin::BI__sync_add_and_fetch_1: 5078 case Builtin::BI__sync_add_and_fetch_2: 5079 case Builtin::BI__sync_add_and_fetch_4: 5080 case Builtin::BI__sync_add_and_fetch_8: 5081 case Builtin::BI__sync_add_and_fetch_16: 5082 BuiltinIndex = 6; 5083 break; 5084 5085 case Builtin::BI__sync_sub_and_fetch: 5086 case Builtin::BI__sync_sub_and_fetch_1: 5087 case Builtin::BI__sync_sub_and_fetch_2: 5088 case Builtin::BI__sync_sub_and_fetch_4: 5089 case Builtin::BI__sync_sub_and_fetch_8: 5090 case Builtin::BI__sync_sub_and_fetch_16: 5091 BuiltinIndex = 7; 5092 break; 5093 5094 case Builtin::BI__sync_and_and_fetch: 5095 case Builtin::BI__sync_and_and_fetch_1: 5096 case Builtin::BI__sync_and_and_fetch_2: 5097 case Builtin::BI__sync_and_and_fetch_4: 5098 case Builtin::BI__sync_and_and_fetch_8: 5099 case Builtin::BI__sync_and_and_fetch_16: 5100 BuiltinIndex = 8; 5101 break; 5102 5103 case Builtin::BI__sync_or_and_fetch: 5104 case Builtin::BI__sync_or_and_fetch_1: 5105 case Builtin::BI__sync_or_and_fetch_2: 5106 case Builtin::BI__sync_or_and_fetch_4: 5107 case Builtin::BI__sync_or_and_fetch_8: 5108 case Builtin::BI__sync_or_and_fetch_16: 5109 BuiltinIndex = 9; 5110 break; 5111 5112 case Builtin::BI__sync_xor_and_fetch: 5113 case Builtin::BI__sync_xor_and_fetch_1: 5114 case Builtin::BI__sync_xor_and_fetch_2: 5115 case Builtin::BI__sync_xor_and_fetch_4: 5116 case Builtin::BI__sync_xor_and_fetch_8: 5117 case Builtin::BI__sync_xor_and_fetch_16: 5118 BuiltinIndex = 10; 5119 break; 5120 5121 case Builtin::BI__sync_nand_and_fetch: 5122 case Builtin::BI__sync_nand_and_fetch_1: 5123 case Builtin::BI__sync_nand_and_fetch_2: 5124 case Builtin::BI__sync_nand_and_fetch_4: 5125 case Builtin::BI__sync_nand_and_fetch_8: 5126 case Builtin::BI__sync_nand_and_fetch_16: 5127 BuiltinIndex = 11; 5128 WarnAboutSemanticsChange = true; 5129 break; 5130 5131 case Builtin::BI__sync_val_compare_and_swap: 5132 case Builtin::BI__sync_val_compare_and_swap_1: 5133 case Builtin::BI__sync_val_compare_and_swap_2: 5134 case Builtin::BI__sync_val_compare_and_swap_4: 5135 case Builtin::BI__sync_val_compare_and_swap_8: 5136 case Builtin::BI__sync_val_compare_and_swap_16: 5137 BuiltinIndex = 12; 5138 NumFixed = 2; 5139 break; 5140 5141 case Builtin::BI__sync_bool_compare_and_swap: 5142 case Builtin::BI__sync_bool_compare_and_swap_1: 5143 case Builtin::BI__sync_bool_compare_and_swap_2: 5144 case Builtin::BI__sync_bool_compare_and_swap_4: 5145 case Builtin::BI__sync_bool_compare_and_swap_8: 5146 case Builtin::BI__sync_bool_compare_and_swap_16: 5147 BuiltinIndex = 13; 5148 NumFixed = 2; 5149 ResultType = Context.BoolTy; 5150 break; 5151 5152 case Builtin::BI__sync_lock_test_and_set: 5153 case Builtin::BI__sync_lock_test_and_set_1: 5154 case Builtin::BI__sync_lock_test_and_set_2: 5155 case Builtin::BI__sync_lock_test_and_set_4: 5156 case Builtin::BI__sync_lock_test_and_set_8: 5157 case Builtin::BI__sync_lock_test_and_set_16: 5158 BuiltinIndex = 14; 5159 break; 5160 5161 case Builtin::BI__sync_lock_release: 5162 case Builtin::BI__sync_lock_release_1: 5163 case Builtin::BI__sync_lock_release_2: 5164 case Builtin::BI__sync_lock_release_4: 5165 case Builtin::BI__sync_lock_release_8: 5166 case Builtin::BI__sync_lock_release_16: 5167 BuiltinIndex = 15; 5168 NumFixed = 0; 5169 ResultType = Context.VoidTy; 5170 break; 5171 5172 case Builtin::BI__sync_swap: 5173 case Builtin::BI__sync_swap_1: 5174 case Builtin::BI__sync_swap_2: 5175 case Builtin::BI__sync_swap_4: 5176 case Builtin::BI__sync_swap_8: 5177 case Builtin::BI__sync_swap_16: 5178 BuiltinIndex = 16; 5179 break; 5180 } 5181 5182 // Now that we know how many fixed arguments we expect, first check that we 5183 // have at least that many. 5184 if (TheCall->getNumArgs() < 1+NumFixed) { 5185 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5186 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5187 << Callee->getSourceRange(); 5188 return ExprError(); 5189 } 5190 5191 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5192 << Callee->getSourceRange(); 5193 5194 if (WarnAboutSemanticsChange) { 5195 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5196 << Callee->getSourceRange(); 5197 } 5198 5199 // Get the decl for the concrete builtin from this, we can tell what the 5200 // concrete integer type we should convert to is. 5201 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5202 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5203 FunctionDecl *NewBuiltinDecl; 5204 if (NewBuiltinID == BuiltinID) 5205 NewBuiltinDecl = FDecl; 5206 else { 5207 // Perform builtin lookup to avoid redeclaring it. 5208 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5209 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5210 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5211 assert(Res.getFoundDecl()); 5212 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5213 if (!NewBuiltinDecl) 5214 return ExprError(); 5215 } 5216 5217 // The first argument --- the pointer --- has a fixed type; we 5218 // deduce the types of the rest of the arguments accordingly. Walk 5219 // the remaining arguments, converting them to the deduced value type. 5220 for (unsigned i = 0; i != NumFixed; ++i) { 5221 ExprResult Arg = TheCall->getArg(i+1); 5222 5223 // GCC does an implicit conversion to the pointer or integer ValType. This 5224 // can fail in some cases (1i -> int**), check for this error case now. 5225 // Initialize the argument. 5226 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5227 ValType, /*consume*/ false); 5228 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5229 if (Arg.isInvalid()) 5230 return ExprError(); 5231 5232 // Okay, we have something that *can* be converted to the right type. Check 5233 // to see if there is a potentially weird extension going on here. This can 5234 // happen when you do an atomic operation on something like an char* and 5235 // pass in 42. The 42 gets converted to char. This is even more strange 5236 // for things like 45.123 -> char, etc. 5237 // FIXME: Do this check. 5238 TheCall->setArg(i+1, Arg.get()); 5239 } 5240 5241 // Create a new DeclRefExpr to refer to the new decl. 5242 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5243 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5244 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5245 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5246 5247 // Set the callee in the CallExpr. 5248 // FIXME: This loses syntactic information. 5249 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5250 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5251 CK_BuiltinFnToFnPtr); 5252 TheCall->setCallee(PromotedCall.get()); 5253 5254 // Change the result type of the call to match the original value type. This 5255 // is arbitrary, but the codegen for these builtins ins design to handle it 5256 // gracefully. 5257 TheCall->setType(ResultType); 5258 5259 return TheCallResult; 5260 } 5261 5262 /// SemaBuiltinNontemporalOverloaded - We have a call to 5263 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5264 /// overloaded function based on the pointer type of its last argument. 5265 /// 5266 /// This function goes through and does final semantic checking for these 5267 /// builtins. 5268 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5269 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5270 DeclRefExpr *DRE = 5271 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5272 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5273 unsigned BuiltinID = FDecl->getBuiltinID(); 5274 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5275 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5276 "Unexpected nontemporal load/store builtin!"); 5277 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5278 unsigned numArgs = isStore ? 2 : 1; 5279 5280 // Ensure that we have the proper number of arguments. 5281 if (checkArgCount(*this, TheCall, numArgs)) 5282 return ExprError(); 5283 5284 // Inspect the last argument of the nontemporal builtin. This should always 5285 // be a pointer type, from which we imply the type of the memory access. 5286 // Because it is a pointer type, we don't have to worry about any implicit 5287 // casts here. 5288 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5289 ExprResult PointerArgResult = 5290 DefaultFunctionArrayLvalueConversion(PointerArg); 5291 5292 if (PointerArgResult.isInvalid()) 5293 return ExprError(); 5294 PointerArg = PointerArgResult.get(); 5295 TheCall->setArg(numArgs - 1, PointerArg); 5296 5297 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5298 if (!pointerType) { 5299 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5300 << PointerArg->getType() << PointerArg->getSourceRange(); 5301 return ExprError(); 5302 } 5303 5304 QualType ValType = pointerType->getPointeeType(); 5305 5306 // Strip any qualifiers off ValType. 5307 ValType = ValType.getUnqualifiedType(); 5308 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5309 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5310 !ValType->isVectorType()) { 5311 Diag(DRE->getBeginLoc(), 5312 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5313 << PointerArg->getType() << PointerArg->getSourceRange(); 5314 return ExprError(); 5315 } 5316 5317 if (!isStore) { 5318 TheCall->setType(ValType); 5319 return TheCallResult; 5320 } 5321 5322 ExprResult ValArg = TheCall->getArg(0); 5323 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5324 Context, ValType, /*consume*/ false); 5325 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5326 if (ValArg.isInvalid()) 5327 return ExprError(); 5328 5329 TheCall->setArg(0, ValArg.get()); 5330 TheCall->setType(Context.VoidTy); 5331 return TheCallResult; 5332 } 5333 5334 /// CheckObjCString - Checks that the argument to the builtin 5335 /// CFString constructor is correct 5336 /// Note: It might also make sense to do the UTF-16 conversion here (would 5337 /// simplify the backend). 5338 bool Sema::CheckObjCString(Expr *Arg) { 5339 Arg = Arg->IgnoreParenCasts(); 5340 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5341 5342 if (!Literal || !Literal->isAscii()) { 5343 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5344 << Arg->getSourceRange(); 5345 return true; 5346 } 5347 5348 if (Literal->containsNonAsciiOrNull()) { 5349 StringRef String = Literal->getString(); 5350 unsigned NumBytes = String.size(); 5351 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5352 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5353 llvm::UTF16 *ToPtr = &ToBuf[0]; 5354 5355 llvm::ConversionResult Result = 5356 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5357 ToPtr + NumBytes, llvm::strictConversion); 5358 // Check for conversion failure. 5359 if (Result != llvm::conversionOK) 5360 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5361 << Arg->getSourceRange(); 5362 } 5363 return false; 5364 } 5365 5366 /// CheckObjCString - Checks that the format string argument to the os_log() 5367 /// and os_trace() functions is correct, and converts it to const char *. 5368 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5369 Arg = Arg->IgnoreParenCasts(); 5370 auto *Literal = dyn_cast<StringLiteral>(Arg); 5371 if (!Literal) { 5372 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5373 Literal = ObjcLiteral->getString(); 5374 } 5375 } 5376 5377 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5378 return ExprError( 5379 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5380 << Arg->getSourceRange()); 5381 } 5382 5383 ExprResult Result(Literal); 5384 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5385 InitializedEntity Entity = 5386 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5387 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5388 return Result; 5389 } 5390 5391 /// Check that the user is calling the appropriate va_start builtin for the 5392 /// target and calling convention. 5393 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5394 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5395 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5396 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5397 bool IsWindows = TT.isOSWindows(); 5398 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5399 if (IsX64 || IsAArch64) { 5400 CallingConv CC = CC_C; 5401 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5402 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5403 if (IsMSVAStart) { 5404 // Don't allow this in System V ABI functions. 5405 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5406 return S.Diag(Fn->getBeginLoc(), 5407 diag::err_ms_va_start_used_in_sysv_function); 5408 } else { 5409 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5410 // On x64 Windows, don't allow this in System V ABI functions. 5411 // (Yes, that means there's no corresponding way to support variadic 5412 // System V ABI functions on Windows.) 5413 if ((IsWindows && CC == CC_X86_64SysV) || 5414 (!IsWindows && CC == CC_Win64)) 5415 return S.Diag(Fn->getBeginLoc(), 5416 diag::err_va_start_used_in_wrong_abi_function) 5417 << !IsWindows; 5418 } 5419 return false; 5420 } 5421 5422 if (IsMSVAStart) 5423 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5424 return false; 5425 } 5426 5427 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5428 ParmVarDecl **LastParam = nullptr) { 5429 // Determine whether the current function, block, or obj-c method is variadic 5430 // and get its parameter list. 5431 bool IsVariadic = false; 5432 ArrayRef<ParmVarDecl *> Params; 5433 DeclContext *Caller = S.CurContext; 5434 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5435 IsVariadic = Block->isVariadic(); 5436 Params = Block->parameters(); 5437 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5438 IsVariadic = FD->isVariadic(); 5439 Params = FD->parameters(); 5440 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5441 IsVariadic = MD->isVariadic(); 5442 // FIXME: This isn't correct for methods (results in bogus warning). 5443 Params = MD->parameters(); 5444 } else if (isa<CapturedDecl>(Caller)) { 5445 // We don't support va_start in a CapturedDecl. 5446 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5447 return true; 5448 } else { 5449 // This must be some other declcontext that parses exprs. 5450 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5451 return true; 5452 } 5453 5454 if (!IsVariadic) { 5455 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5456 return true; 5457 } 5458 5459 if (LastParam) 5460 *LastParam = Params.empty() ? nullptr : Params.back(); 5461 5462 return false; 5463 } 5464 5465 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5466 /// for validity. Emit an error and return true on failure; return false 5467 /// on success. 5468 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5469 Expr *Fn = TheCall->getCallee(); 5470 5471 if (checkVAStartABI(*this, BuiltinID, Fn)) 5472 return true; 5473 5474 if (TheCall->getNumArgs() > 2) { 5475 Diag(TheCall->getArg(2)->getBeginLoc(), 5476 diag::err_typecheck_call_too_many_args) 5477 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5478 << Fn->getSourceRange() 5479 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5480 (*(TheCall->arg_end() - 1))->getEndLoc()); 5481 return true; 5482 } 5483 5484 if (TheCall->getNumArgs() < 2) { 5485 return Diag(TheCall->getEndLoc(), 5486 diag::err_typecheck_call_too_few_args_at_least) 5487 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5488 } 5489 5490 // Type-check the first argument normally. 5491 if (checkBuiltinArgument(*this, TheCall, 0)) 5492 return true; 5493 5494 // Check that the current function is variadic, and get its last parameter. 5495 ParmVarDecl *LastParam; 5496 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5497 return true; 5498 5499 // Verify that the second argument to the builtin is the last argument of the 5500 // current function or method. 5501 bool SecondArgIsLastNamedArgument = false; 5502 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5503 5504 // These are valid if SecondArgIsLastNamedArgument is false after the next 5505 // block. 5506 QualType Type; 5507 SourceLocation ParamLoc; 5508 bool IsCRegister = false; 5509 5510 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5511 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5512 SecondArgIsLastNamedArgument = PV == LastParam; 5513 5514 Type = PV->getType(); 5515 ParamLoc = PV->getLocation(); 5516 IsCRegister = 5517 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5518 } 5519 } 5520 5521 if (!SecondArgIsLastNamedArgument) 5522 Diag(TheCall->getArg(1)->getBeginLoc(), 5523 diag::warn_second_arg_of_va_start_not_last_named_param); 5524 else if (IsCRegister || Type->isReferenceType() || 5525 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5526 // Promotable integers are UB, but enumerations need a bit of 5527 // extra checking to see what their promotable type actually is. 5528 if (!Type->isPromotableIntegerType()) 5529 return false; 5530 if (!Type->isEnumeralType()) 5531 return true; 5532 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5533 return !(ED && 5534 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5535 }()) { 5536 unsigned Reason = 0; 5537 if (Type->isReferenceType()) Reason = 1; 5538 else if (IsCRegister) Reason = 2; 5539 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5540 Diag(ParamLoc, diag::note_parameter_type) << Type; 5541 } 5542 5543 TheCall->setType(Context.VoidTy); 5544 return false; 5545 } 5546 5547 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5548 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5549 // const char *named_addr); 5550 5551 Expr *Func = Call->getCallee(); 5552 5553 if (Call->getNumArgs() < 3) 5554 return Diag(Call->getEndLoc(), 5555 diag::err_typecheck_call_too_few_args_at_least) 5556 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5557 5558 // Type-check the first argument normally. 5559 if (checkBuiltinArgument(*this, Call, 0)) 5560 return true; 5561 5562 // Check that the current function is variadic. 5563 if (checkVAStartIsInVariadicFunction(*this, Func)) 5564 return true; 5565 5566 // __va_start on Windows does not validate the parameter qualifiers 5567 5568 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5569 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5570 5571 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5572 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5573 5574 const QualType &ConstCharPtrTy = 5575 Context.getPointerType(Context.CharTy.withConst()); 5576 if (!Arg1Ty->isPointerType() || 5577 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5578 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5579 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5580 << 0 /* qualifier difference */ 5581 << 3 /* parameter mismatch */ 5582 << 2 << Arg1->getType() << ConstCharPtrTy; 5583 5584 const QualType SizeTy = Context.getSizeType(); 5585 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5586 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5587 << Arg2->getType() << SizeTy << 1 /* different class */ 5588 << 0 /* qualifier difference */ 5589 << 3 /* parameter mismatch */ 5590 << 3 << Arg2->getType() << SizeTy; 5591 5592 return false; 5593 } 5594 5595 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5596 /// friends. This is declared to take (...), so we have to check everything. 5597 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5598 if (TheCall->getNumArgs() < 2) 5599 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5600 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5601 if (TheCall->getNumArgs() > 2) 5602 return Diag(TheCall->getArg(2)->getBeginLoc(), 5603 diag::err_typecheck_call_too_many_args) 5604 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5605 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5606 (*(TheCall->arg_end() - 1))->getEndLoc()); 5607 5608 ExprResult OrigArg0 = TheCall->getArg(0); 5609 ExprResult OrigArg1 = TheCall->getArg(1); 5610 5611 // Do standard promotions between the two arguments, returning their common 5612 // type. 5613 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5614 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5615 return true; 5616 5617 // Make sure any conversions are pushed back into the call; this is 5618 // type safe since unordered compare builtins are declared as "_Bool 5619 // foo(...)". 5620 TheCall->setArg(0, OrigArg0.get()); 5621 TheCall->setArg(1, OrigArg1.get()); 5622 5623 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5624 return false; 5625 5626 // If the common type isn't a real floating type, then the arguments were 5627 // invalid for this operation. 5628 if (Res.isNull() || !Res->isRealFloatingType()) 5629 return Diag(OrigArg0.get()->getBeginLoc(), 5630 diag::err_typecheck_call_invalid_ordered_compare) 5631 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5632 << SourceRange(OrigArg0.get()->getBeginLoc(), 5633 OrigArg1.get()->getEndLoc()); 5634 5635 return false; 5636 } 5637 5638 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5639 /// __builtin_isnan and friends. This is declared to take (...), so we have 5640 /// to check everything. We expect the last argument to be a floating point 5641 /// value. 5642 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5643 if (TheCall->getNumArgs() < NumArgs) 5644 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5645 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5646 if (TheCall->getNumArgs() > NumArgs) 5647 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5648 diag::err_typecheck_call_too_many_args) 5649 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5650 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5651 (*(TheCall->arg_end() - 1))->getEndLoc()); 5652 5653 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5654 5655 if (OrigArg->isTypeDependent()) 5656 return false; 5657 5658 // This operation requires a non-_Complex floating-point number. 5659 if (!OrigArg->getType()->isRealFloatingType()) 5660 return Diag(OrigArg->getBeginLoc(), 5661 diag::err_typecheck_call_invalid_unary_fp) 5662 << OrigArg->getType() << OrigArg->getSourceRange(); 5663 5664 // If this is an implicit conversion from float -> float, double, or 5665 // long double, remove it. 5666 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5667 // Only remove standard FloatCasts, leaving other casts inplace 5668 if (Cast->getCastKind() == CK_FloatingCast) { 5669 Expr *CastArg = Cast->getSubExpr(); 5670 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5671 assert( 5672 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5673 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5674 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5675 "promotion from float to either float, double, or long double is " 5676 "the only expected cast here"); 5677 Cast->setSubExpr(nullptr); 5678 TheCall->setArg(NumArgs-1, CastArg); 5679 } 5680 } 5681 } 5682 5683 return false; 5684 } 5685 5686 // Customized Sema Checking for VSX builtins that have the following signature: 5687 // vector [...] builtinName(vector [...], vector [...], const int); 5688 // Which takes the same type of vectors (any legal vector type) for the first 5689 // two arguments and takes compile time constant for the third argument. 5690 // Example builtins are : 5691 // vector double vec_xxpermdi(vector double, vector double, int); 5692 // vector short vec_xxsldwi(vector short, vector short, int); 5693 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5694 unsigned ExpectedNumArgs = 3; 5695 if (TheCall->getNumArgs() < ExpectedNumArgs) 5696 return Diag(TheCall->getEndLoc(), 5697 diag::err_typecheck_call_too_few_args_at_least) 5698 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5699 << TheCall->getSourceRange(); 5700 5701 if (TheCall->getNumArgs() > ExpectedNumArgs) 5702 return Diag(TheCall->getEndLoc(), 5703 diag::err_typecheck_call_too_many_args_at_most) 5704 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5705 << TheCall->getSourceRange(); 5706 5707 // Check the third argument is a compile time constant 5708 llvm::APSInt Value; 5709 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5710 return Diag(TheCall->getBeginLoc(), 5711 diag::err_vsx_builtin_nonconstant_argument) 5712 << 3 /* argument index */ << TheCall->getDirectCallee() 5713 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5714 TheCall->getArg(2)->getEndLoc()); 5715 5716 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5717 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5718 5719 // Check the type of argument 1 and argument 2 are vectors. 5720 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5721 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5722 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5723 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5724 << TheCall->getDirectCallee() 5725 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5726 TheCall->getArg(1)->getEndLoc()); 5727 } 5728 5729 // Check the first two arguments are the same type. 5730 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5731 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5732 << TheCall->getDirectCallee() 5733 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5734 TheCall->getArg(1)->getEndLoc()); 5735 } 5736 5737 // When default clang type checking is turned off and the customized type 5738 // checking is used, the returning type of the function must be explicitly 5739 // set. Otherwise it is _Bool by default. 5740 TheCall->setType(Arg1Ty); 5741 5742 return false; 5743 } 5744 5745 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5746 // This is declared to take (...), so we have to check everything. 5747 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5748 if (TheCall->getNumArgs() < 2) 5749 return ExprError(Diag(TheCall->getEndLoc(), 5750 diag::err_typecheck_call_too_few_args_at_least) 5751 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5752 << TheCall->getSourceRange()); 5753 5754 // Determine which of the following types of shufflevector we're checking: 5755 // 1) unary, vector mask: (lhs, mask) 5756 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5757 QualType resType = TheCall->getArg(0)->getType(); 5758 unsigned numElements = 0; 5759 5760 if (!TheCall->getArg(0)->isTypeDependent() && 5761 !TheCall->getArg(1)->isTypeDependent()) { 5762 QualType LHSType = TheCall->getArg(0)->getType(); 5763 QualType RHSType = TheCall->getArg(1)->getType(); 5764 5765 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5766 return ExprError( 5767 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5768 << TheCall->getDirectCallee() 5769 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5770 TheCall->getArg(1)->getEndLoc())); 5771 5772 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5773 unsigned numResElements = TheCall->getNumArgs() - 2; 5774 5775 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5776 // with mask. If so, verify that RHS is an integer vector type with the 5777 // same number of elts as lhs. 5778 if (TheCall->getNumArgs() == 2) { 5779 if (!RHSType->hasIntegerRepresentation() || 5780 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5781 return ExprError(Diag(TheCall->getBeginLoc(), 5782 diag::err_vec_builtin_incompatible_vector) 5783 << TheCall->getDirectCallee() 5784 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5785 TheCall->getArg(1)->getEndLoc())); 5786 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5787 return ExprError(Diag(TheCall->getBeginLoc(), 5788 diag::err_vec_builtin_incompatible_vector) 5789 << TheCall->getDirectCallee() 5790 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5791 TheCall->getArg(1)->getEndLoc())); 5792 } else if (numElements != numResElements) { 5793 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5794 resType = Context.getVectorType(eltType, numResElements, 5795 VectorType::GenericVector); 5796 } 5797 } 5798 5799 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5800 if (TheCall->getArg(i)->isTypeDependent() || 5801 TheCall->getArg(i)->isValueDependent()) 5802 continue; 5803 5804 llvm::APSInt Result(32); 5805 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5806 return ExprError(Diag(TheCall->getBeginLoc(), 5807 diag::err_shufflevector_nonconstant_argument) 5808 << TheCall->getArg(i)->getSourceRange()); 5809 5810 // Allow -1 which will be translated to undef in the IR. 5811 if (Result.isSigned() && Result.isAllOnesValue()) 5812 continue; 5813 5814 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5815 return ExprError(Diag(TheCall->getBeginLoc(), 5816 diag::err_shufflevector_argument_too_large) 5817 << TheCall->getArg(i)->getSourceRange()); 5818 } 5819 5820 SmallVector<Expr*, 32> exprs; 5821 5822 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5823 exprs.push_back(TheCall->getArg(i)); 5824 TheCall->setArg(i, nullptr); 5825 } 5826 5827 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5828 TheCall->getCallee()->getBeginLoc(), 5829 TheCall->getRParenLoc()); 5830 } 5831 5832 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5833 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5834 SourceLocation BuiltinLoc, 5835 SourceLocation RParenLoc) { 5836 ExprValueKind VK = VK_RValue; 5837 ExprObjectKind OK = OK_Ordinary; 5838 QualType DstTy = TInfo->getType(); 5839 QualType SrcTy = E->getType(); 5840 5841 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5842 return ExprError(Diag(BuiltinLoc, 5843 diag::err_convertvector_non_vector) 5844 << E->getSourceRange()); 5845 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5846 return ExprError(Diag(BuiltinLoc, 5847 diag::err_convertvector_non_vector_type)); 5848 5849 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5850 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5851 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5852 if (SrcElts != DstElts) 5853 return ExprError(Diag(BuiltinLoc, 5854 diag::err_convertvector_incompatible_vector) 5855 << E->getSourceRange()); 5856 } 5857 5858 return new (Context) 5859 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5860 } 5861 5862 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5863 // This is declared to take (const void*, ...) and can take two 5864 // optional constant int args. 5865 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5866 unsigned NumArgs = TheCall->getNumArgs(); 5867 5868 if (NumArgs > 3) 5869 return Diag(TheCall->getEndLoc(), 5870 diag::err_typecheck_call_too_many_args_at_most) 5871 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5872 5873 // Argument 0 is checked for us and the remaining arguments must be 5874 // constant integers. 5875 for (unsigned i = 1; i != NumArgs; ++i) 5876 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5877 return true; 5878 5879 return false; 5880 } 5881 5882 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5883 // __assume does not evaluate its arguments, and should warn if its argument 5884 // has side effects. 5885 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5886 Expr *Arg = TheCall->getArg(0); 5887 if (Arg->isInstantiationDependent()) return false; 5888 5889 if (Arg->HasSideEffects(Context)) 5890 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5891 << Arg->getSourceRange() 5892 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5893 5894 return false; 5895 } 5896 5897 /// Handle __builtin_alloca_with_align. This is declared 5898 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5899 /// than 8. 5900 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5901 // The alignment must be a constant integer. 5902 Expr *Arg = TheCall->getArg(1); 5903 5904 // We can't check the value of a dependent argument. 5905 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5906 if (const auto *UE = 5907 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5908 if (UE->getKind() == UETT_AlignOf || 5909 UE->getKind() == UETT_PreferredAlignOf) 5910 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5911 << Arg->getSourceRange(); 5912 5913 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5914 5915 if (!Result.isPowerOf2()) 5916 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5917 << Arg->getSourceRange(); 5918 5919 if (Result < Context.getCharWidth()) 5920 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5921 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5922 5923 if (Result > std::numeric_limits<int32_t>::max()) 5924 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5925 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5926 } 5927 5928 return false; 5929 } 5930 5931 /// Handle __builtin_assume_aligned. This is declared 5932 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5933 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5934 unsigned NumArgs = TheCall->getNumArgs(); 5935 5936 if (NumArgs > 3) 5937 return Diag(TheCall->getEndLoc(), 5938 diag::err_typecheck_call_too_many_args_at_most) 5939 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5940 5941 // The alignment must be a constant integer. 5942 Expr *Arg = TheCall->getArg(1); 5943 5944 // We can't check the value of a dependent argument. 5945 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5946 llvm::APSInt Result; 5947 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5948 return true; 5949 5950 if (!Result.isPowerOf2()) 5951 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5952 << Arg->getSourceRange(); 5953 } 5954 5955 if (NumArgs > 2) { 5956 ExprResult Arg(TheCall->getArg(2)); 5957 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5958 Context.getSizeType(), false); 5959 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5960 if (Arg.isInvalid()) return true; 5961 TheCall->setArg(2, Arg.get()); 5962 } 5963 5964 return false; 5965 } 5966 5967 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5968 unsigned BuiltinID = 5969 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5970 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5971 5972 unsigned NumArgs = TheCall->getNumArgs(); 5973 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5974 if (NumArgs < NumRequiredArgs) { 5975 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5976 << 0 /* function call */ << NumRequiredArgs << NumArgs 5977 << TheCall->getSourceRange(); 5978 } 5979 if (NumArgs >= NumRequiredArgs + 0x100) { 5980 return Diag(TheCall->getEndLoc(), 5981 diag::err_typecheck_call_too_many_args_at_most) 5982 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5983 << TheCall->getSourceRange(); 5984 } 5985 unsigned i = 0; 5986 5987 // For formatting call, check buffer arg. 5988 if (!IsSizeCall) { 5989 ExprResult Arg(TheCall->getArg(i)); 5990 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5991 Context, Context.VoidPtrTy, false); 5992 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5993 if (Arg.isInvalid()) 5994 return true; 5995 TheCall->setArg(i, Arg.get()); 5996 i++; 5997 } 5998 5999 // Check string literal arg. 6000 unsigned FormatIdx = i; 6001 { 6002 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6003 if (Arg.isInvalid()) 6004 return true; 6005 TheCall->setArg(i, Arg.get()); 6006 i++; 6007 } 6008 6009 // Make sure variadic args are scalar. 6010 unsigned FirstDataArg = i; 6011 while (i < NumArgs) { 6012 ExprResult Arg = DefaultVariadicArgumentPromotion( 6013 TheCall->getArg(i), VariadicFunction, nullptr); 6014 if (Arg.isInvalid()) 6015 return true; 6016 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6017 if (ArgSize.getQuantity() >= 0x100) { 6018 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6019 << i << (int)ArgSize.getQuantity() << 0xff 6020 << TheCall->getSourceRange(); 6021 } 6022 TheCall->setArg(i, Arg.get()); 6023 i++; 6024 } 6025 6026 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6027 // call to avoid duplicate diagnostics. 6028 if (!IsSizeCall) { 6029 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6030 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6031 bool Success = CheckFormatArguments( 6032 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6033 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6034 CheckedVarArgs); 6035 if (!Success) 6036 return true; 6037 } 6038 6039 if (IsSizeCall) { 6040 TheCall->setType(Context.getSizeType()); 6041 } else { 6042 TheCall->setType(Context.VoidPtrTy); 6043 } 6044 return false; 6045 } 6046 6047 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6048 /// TheCall is a constant expression. 6049 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6050 llvm::APSInt &Result) { 6051 Expr *Arg = TheCall->getArg(ArgNum); 6052 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6053 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6054 6055 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6056 6057 if (!Arg->isIntegerConstantExpr(Result, Context)) 6058 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6059 << FDecl->getDeclName() << Arg->getSourceRange(); 6060 6061 return false; 6062 } 6063 6064 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6065 /// TheCall is a constant expression in the range [Low, High]. 6066 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6067 int Low, int High, bool RangeIsError) { 6068 if (isConstantEvaluated()) 6069 return false; 6070 llvm::APSInt Result; 6071 6072 // We can't check the value of a dependent argument. 6073 Expr *Arg = TheCall->getArg(ArgNum); 6074 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6075 return false; 6076 6077 // Check constant-ness first. 6078 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6079 return true; 6080 6081 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6082 if (RangeIsError) 6083 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6084 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6085 else 6086 // Defer the warning until we know if the code will be emitted so that 6087 // dead code can ignore this. 6088 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6089 PDiag(diag::warn_argument_invalid_range) 6090 << Result.toString(10) << Low << High 6091 << Arg->getSourceRange()); 6092 } 6093 6094 return false; 6095 } 6096 6097 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6098 /// TheCall is a constant expression is a multiple of Num.. 6099 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6100 unsigned Num) { 6101 llvm::APSInt Result; 6102 6103 // We can't check the value of a dependent argument. 6104 Expr *Arg = TheCall->getArg(ArgNum); 6105 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6106 return false; 6107 6108 // Check constant-ness first. 6109 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6110 return true; 6111 6112 if (Result.getSExtValue() % Num != 0) 6113 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6114 << Num << Arg->getSourceRange(); 6115 6116 return false; 6117 } 6118 6119 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6120 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6121 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6122 if (checkArgCount(*this, TheCall, 2)) 6123 return true; 6124 Expr *Arg0 = TheCall->getArg(0); 6125 Expr *Arg1 = TheCall->getArg(1); 6126 6127 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6128 if (FirstArg.isInvalid()) 6129 return true; 6130 QualType FirstArgType = FirstArg.get()->getType(); 6131 if (!FirstArgType->isAnyPointerType()) 6132 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6133 << "first" << FirstArgType << Arg0->getSourceRange(); 6134 TheCall->setArg(0, FirstArg.get()); 6135 6136 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6137 if (SecArg.isInvalid()) 6138 return true; 6139 QualType SecArgType = SecArg.get()->getType(); 6140 if (!SecArgType->isIntegerType()) 6141 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6142 << "second" << SecArgType << Arg1->getSourceRange(); 6143 6144 // Derive the return type from the pointer argument. 6145 TheCall->setType(FirstArgType); 6146 return false; 6147 } 6148 6149 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6150 if (checkArgCount(*this, TheCall, 2)) 6151 return true; 6152 6153 Expr *Arg0 = TheCall->getArg(0); 6154 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6155 if (FirstArg.isInvalid()) 6156 return true; 6157 QualType FirstArgType = FirstArg.get()->getType(); 6158 if (!FirstArgType->isAnyPointerType()) 6159 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6160 << "first" << FirstArgType << Arg0->getSourceRange(); 6161 TheCall->setArg(0, FirstArg.get()); 6162 6163 // Derive the return type from the pointer argument. 6164 TheCall->setType(FirstArgType); 6165 6166 // Second arg must be an constant in range [0,15] 6167 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6168 } 6169 6170 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6171 if (checkArgCount(*this, TheCall, 2)) 6172 return true; 6173 Expr *Arg0 = TheCall->getArg(0); 6174 Expr *Arg1 = TheCall->getArg(1); 6175 6176 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6177 if (FirstArg.isInvalid()) 6178 return true; 6179 QualType FirstArgType = FirstArg.get()->getType(); 6180 if (!FirstArgType->isAnyPointerType()) 6181 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6182 << "first" << FirstArgType << Arg0->getSourceRange(); 6183 6184 QualType SecArgType = Arg1->getType(); 6185 if (!SecArgType->isIntegerType()) 6186 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6187 << "second" << SecArgType << Arg1->getSourceRange(); 6188 TheCall->setType(Context.IntTy); 6189 return false; 6190 } 6191 6192 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6193 BuiltinID == AArch64::BI__builtin_arm_stg) { 6194 if (checkArgCount(*this, TheCall, 1)) 6195 return true; 6196 Expr *Arg0 = TheCall->getArg(0); 6197 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6198 if (FirstArg.isInvalid()) 6199 return true; 6200 6201 QualType FirstArgType = FirstArg.get()->getType(); 6202 if (!FirstArgType->isAnyPointerType()) 6203 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6204 << "first" << FirstArgType << Arg0->getSourceRange(); 6205 TheCall->setArg(0, FirstArg.get()); 6206 6207 // Derive the return type from the pointer argument. 6208 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6209 TheCall->setType(FirstArgType); 6210 return false; 6211 } 6212 6213 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6214 Expr *ArgA = TheCall->getArg(0); 6215 Expr *ArgB = TheCall->getArg(1); 6216 6217 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6218 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6219 6220 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6221 return true; 6222 6223 QualType ArgTypeA = ArgExprA.get()->getType(); 6224 QualType ArgTypeB = ArgExprB.get()->getType(); 6225 6226 auto isNull = [&] (Expr *E) -> bool { 6227 return E->isNullPointerConstant( 6228 Context, Expr::NPC_ValueDependentIsNotNull); }; 6229 6230 // argument should be either a pointer or null 6231 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6232 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6233 << "first" << ArgTypeA << ArgA->getSourceRange(); 6234 6235 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6236 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6237 << "second" << ArgTypeB << ArgB->getSourceRange(); 6238 6239 // Ensure Pointee types are compatible 6240 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6241 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6242 QualType pointeeA = ArgTypeA->getPointeeType(); 6243 QualType pointeeB = ArgTypeB->getPointeeType(); 6244 if (!Context.typesAreCompatible( 6245 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6246 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6247 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6248 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6249 << ArgB->getSourceRange(); 6250 } 6251 } 6252 6253 // at least one argument should be pointer type 6254 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6255 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6256 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6257 6258 if (isNull(ArgA)) // adopt type of the other pointer 6259 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6260 6261 if (isNull(ArgB)) 6262 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6263 6264 TheCall->setArg(0, ArgExprA.get()); 6265 TheCall->setArg(1, ArgExprB.get()); 6266 TheCall->setType(Context.LongLongTy); 6267 return false; 6268 } 6269 assert(false && "Unhandled ARM MTE intrinsic"); 6270 return true; 6271 } 6272 6273 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6274 /// TheCall is an ARM/AArch64 special register string literal. 6275 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6276 int ArgNum, unsigned ExpectedFieldNum, 6277 bool AllowName) { 6278 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6279 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6280 BuiltinID == ARM::BI__builtin_arm_rsr || 6281 BuiltinID == ARM::BI__builtin_arm_rsrp || 6282 BuiltinID == ARM::BI__builtin_arm_wsr || 6283 BuiltinID == ARM::BI__builtin_arm_wsrp; 6284 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6285 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6286 BuiltinID == AArch64::BI__builtin_arm_rsr || 6287 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6288 BuiltinID == AArch64::BI__builtin_arm_wsr || 6289 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6290 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6291 6292 // We can't check the value of a dependent argument. 6293 Expr *Arg = TheCall->getArg(ArgNum); 6294 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6295 return false; 6296 6297 // Check if the argument is a string literal. 6298 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6299 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6300 << Arg->getSourceRange(); 6301 6302 // Check the type of special register given. 6303 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6304 SmallVector<StringRef, 6> Fields; 6305 Reg.split(Fields, ":"); 6306 6307 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6308 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6309 << Arg->getSourceRange(); 6310 6311 // If the string is the name of a register then we cannot check that it is 6312 // valid here but if the string is of one the forms described in ACLE then we 6313 // can check that the supplied fields are integers and within the valid 6314 // ranges. 6315 if (Fields.size() > 1) { 6316 bool FiveFields = Fields.size() == 5; 6317 6318 bool ValidString = true; 6319 if (IsARMBuiltin) { 6320 ValidString &= Fields[0].startswith_lower("cp") || 6321 Fields[0].startswith_lower("p"); 6322 if (ValidString) 6323 Fields[0] = 6324 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6325 6326 ValidString &= Fields[2].startswith_lower("c"); 6327 if (ValidString) 6328 Fields[2] = Fields[2].drop_front(1); 6329 6330 if (FiveFields) { 6331 ValidString &= Fields[3].startswith_lower("c"); 6332 if (ValidString) 6333 Fields[3] = Fields[3].drop_front(1); 6334 } 6335 } 6336 6337 SmallVector<int, 5> Ranges; 6338 if (FiveFields) 6339 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6340 else 6341 Ranges.append({15, 7, 15}); 6342 6343 for (unsigned i=0; i<Fields.size(); ++i) { 6344 int IntField; 6345 ValidString &= !Fields[i].getAsInteger(10, IntField); 6346 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6347 } 6348 6349 if (!ValidString) 6350 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6351 << Arg->getSourceRange(); 6352 } else if (IsAArch64Builtin && Fields.size() == 1) { 6353 // If the register name is one of those that appear in the condition below 6354 // and the special register builtin being used is one of the write builtins, 6355 // then we require that the argument provided for writing to the register 6356 // is an integer constant expression. This is because it will be lowered to 6357 // an MSR (immediate) instruction, so we need to know the immediate at 6358 // compile time. 6359 if (TheCall->getNumArgs() != 2) 6360 return false; 6361 6362 std::string RegLower = Reg.lower(); 6363 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6364 RegLower != "pan" && RegLower != "uao") 6365 return false; 6366 6367 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6368 } 6369 6370 return false; 6371 } 6372 6373 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6374 /// This checks that the target supports __builtin_longjmp and 6375 /// that val is a constant 1. 6376 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6377 if (!Context.getTargetInfo().hasSjLjLowering()) 6378 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6379 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6380 6381 Expr *Arg = TheCall->getArg(1); 6382 llvm::APSInt Result; 6383 6384 // TODO: This is less than ideal. Overload this to take a value. 6385 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6386 return true; 6387 6388 if (Result != 1) 6389 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6390 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6391 6392 return false; 6393 } 6394 6395 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6396 /// This checks that the target supports __builtin_setjmp. 6397 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6398 if (!Context.getTargetInfo().hasSjLjLowering()) 6399 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6400 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6401 return false; 6402 } 6403 6404 namespace { 6405 6406 class UncoveredArgHandler { 6407 enum { Unknown = -1, AllCovered = -2 }; 6408 6409 signed FirstUncoveredArg = Unknown; 6410 SmallVector<const Expr *, 4> DiagnosticExprs; 6411 6412 public: 6413 UncoveredArgHandler() = default; 6414 6415 bool hasUncoveredArg() const { 6416 return (FirstUncoveredArg >= 0); 6417 } 6418 6419 unsigned getUncoveredArg() const { 6420 assert(hasUncoveredArg() && "no uncovered argument"); 6421 return FirstUncoveredArg; 6422 } 6423 6424 void setAllCovered() { 6425 // A string has been found with all arguments covered, so clear out 6426 // the diagnostics. 6427 DiagnosticExprs.clear(); 6428 FirstUncoveredArg = AllCovered; 6429 } 6430 6431 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6432 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6433 6434 // Don't update if a previous string covers all arguments. 6435 if (FirstUncoveredArg == AllCovered) 6436 return; 6437 6438 // UncoveredArgHandler tracks the highest uncovered argument index 6439 // and with it all the strings that match this index. 6440 if (NewFirstUncoveredArg == FirstUncoveredArg) 6441 DiagnosticExprs.push_back(StrExpr); 6442 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6443 DiagnosticExprs.clear(); 6444 DiagnosticExprs.push_back(StrExpr); 6445 FirstUncoveredArg = NewFirstUncoveredArg; 6446 } 6447 } 6448 6449 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6450 }; 6451 6452 enum StringLiteralCheckType { 6453 SLCT_NotALiteral, 6454 SLCT_UncheckedLiteral, 6455 SLCT_CheckedLiteral 6456 }; 6457 6458 } // namespace 6459 6460 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6461 BinaryOperatorKind BinOpKind, 6462 bool AddendIsRight) { 6463 unsigned BitWidth = Offset.getBitWidth(); 6464 unsigned AddendBitWidth = Addend.getBitWidth(); 6465 // There might be negative interim results. 6466 if (Addend.isUnsigned()) { 6467 Addend = Addend.zext(++AddendBitWidth); 6468 Addend.setIsSigned(true); 6469 } 6470 // Adjust the bit width of the APSInts. 6471 if (AddendBitWidth > BitWidth) { 6472 Offset = Offset.sext(AddendBitWidth); 6473 BitWidth = AddendBitWidth; 6474 } else if (BitWidth > AddendBitWidth) { 6475 Addend = Addend.sext(BitWidth); 6476 } 6477 6478 bool Ov = false; 6479 llvm::APSInt ResOffset = Offset; 6480 if (BinOpKind == BO_Add) 6481 ResOffset = Offset.sadd_ov(Addend, Ov); 6482 else { 6483 assert(AddendIsRight && BinOpKind == BO_Sub && 6484 "operator must be add or sub with addend on the right"); 6485 ResOffset = Offset.ssub_ov(Addend, Ov); 6486 } 6487 6488 // We add an offset to a pointer here so we should support an offset as big as 6489 // possible. 6490 if (Ov) { 6491 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6492 "index (intermediate) result too big"); 6493 Offset = Offset.sext(2 * BitWidth); 6494 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6495 return; 6496 } 6497 6498 Offset = ResOffset; 6499 } 6500 6501 namespace { 6502 6503 // This is a wrapper class around StringLiteral to support offsetted string 6504 // literals as format strings. It takes the offset into account when returning 6505 // the string and its length or the source locations to display notes correctly. 6506 class FormatStringLiteral { 6507 const StringLiteral *FExpr; 6508 int64_t Offset; 6509 6510 public: 6511 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6512 : FExpr(fexpr), Offset(Offset) {} 6513 6514 StringRef getString() const { 6515 return FExpr->getString().drop_front(Offset); 6516 } 6517 6518 unsigned getByteLength() const { 6519 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6520 } 6521 6522 unsigned getLength() const { return FExpr->getLength() - Offset; } 6523 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6524 6525 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6526 6527 QualType getType() const { return FExpr->getType(); } 6528 6529 bool isAscii() const { return FExpr->isAscii(); } 6530 bool isWide() const { return FExpr->isWide(); } 6531 bool isUTF8() const { return FExpr->isUTF8(); } 6532 bool isUTF16() const { return FExpr->isUTF16(); } 6533 bool isUTF32() const { return FExpr->isUTF32(); } 6534 bool isPascal() const { return FExpr->isPascal(); } 6535 6536 SourceLocation getLocationOfByte( 6537 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6538 const TargetInfo &Target, unsigned *StartToken = nullptr, 6539 unsigned *StartTokenByteOffset = nullptr) const { 6540 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6541 StartToken, StartTokenByteOffset); 6542 } 6543 6544 SourceLocation getBeginLoc() const LLVM_READONLY { 6545 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6546 } 6547 6548 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6549 }; 6550 6551 } // namespace 6552 6553 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6554 const Expr *OrigFormatExpr, 6555 ArrayRef<const Expr *> Args, 6556 bool HasVAListArg, unsigned format_idx, 6557 unsigned firstDataArg, 6558 Sema::FormatStringType Type, 6559 bool inFunctionCall, 6560 Sema::VariadicCallType CallType, 6561 llvm::SmallBitVector &CheckedVarArgs, 6562 UncoveredArgHandler &UncoveredArg); 6563 6564 // Determine if an expression is a string literal or constant string. 6565 // If this function returns false on the arguments to a function expecting a 6566 // format string, we will usually need to emit a warning. 6567 // True string literals are then checked by CheckFormatString. 6568 static StringLiteralCheckType 6569 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6570 bool HasVAListArg, unsigned format_idx, 6571 unsigned firstDataArg, Sema::FormatStringType Type, 6572 Sema::VariadicCallType CallType, bool InFunctionCall, 6573 llvm::SmallBitVector &CheckedVarArgs, 6574 UncoveredArgHandler &UncoveredArg, 6575 llvm::APSInt Offset) { 6576 if (S.isConstantEvaluated()) 6577 return SLCT_NotALiteral; 6578 tryAgain: 6579 assert(Offset.isSigned() && "invalid offset"); 6580 6581 if (E->isTypeDependent() || E->isValueDependent()) 6582 return SLCT_NotALiteral; 6583 6584 E = E->IgnoreParenCasts(); 6585 6586 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6587 // Technically -Wformat-nonliteral does not warn about this case. 6588 // The behavior of printf and friends in this case is implementation 6589 // dependent. Ideally if the format string cannot be null then 6590 // it should have a 'nonnull' attribute in the function prototype. 6591 return SLCT_UncheckedLiteral; 6592 6593 switch (E->getStmtClass()) { 6594 case Stmt::BinaryConditionalOperatorClass: 6595 case Stmt::ConditionalOperatorClass: { 6596 // The expression is a literal if both sub-expressions were, and it was 6597 // completely checked only if both sub-expressions were checked. 6598 const AbstractConditionalOperator *C = 6599 cast<AbstractConditionalOperator>(E); 6600 6601 // Determine whether it is necessary to check both sub-expressions, for 6602 // example, because the condition expression is a constant that can be 6603 // evaluated at compile time. 6604 bool CheckLeft = true, CheckRight = true; 6605 6606 bool Cond; 6607 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6608 S.isConstantEvaluated())) { 6609 if (Cond) 6610 CheckRight = false; 6611 else 6612 CheckLeft = false; 6613 } 6614 6615 // We need to maintain the offsets for the right and the left hand side 6616 // separately to check if every possible indexed expression is a valid 6617 // string literal. They might have different offsets for different string 6618 // literals in the end. 6619 StringLiteralCheckType Left; 6620 if (!CheckLeft) 6621 Left = SLCT_UncheckedLiteral; 6622 else { 6623 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6624 HasVAListArg, format_idx, firstDataArg, 6625 Type, CallType, InFunctionCall, 6626 CheckedVarArgs, UncoveredArg, Offset); 6627 if (Left == SLCT_NotALiteral || !CheckRight) { 6628 return Left; 6629 } 6630 } 6631 6632 StringLiteralCheckType Right = 6633 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6634 HasVAListArg, format_idx, firstDataArg, 6635 Type, CallType, InFunctionCall, CheckedVarArgs, 6636 UncoveredArg, Offset); 6637 6638 return (CheckLeft && Left < Right) ? Left : Right; 6639 } 6640 6641 case Stmt::ImplicitCastExprClass: 6642 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6643 goto tryAgain; 6644 6645 case Stmt::OpaqueValueExprClass: 6646 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6647 E = src; 6648 goto tryAgain; 6649 } 6650 return SLCT_NotALiteral; 6651 6652 case Stmt::PredefinedExprClass: 6653 // While __func__, etc., are technically not string literals, they 6654 // cannot contain format specifiers and thus are not a security 6655 // liability. 6656 return SLCT_UncheckedLiteral; 6657 6658 case Stmt::DeclRefExprClass: { 6659 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6660 6661 // As an exception, do not flag errors for variables binding to 6662 // const string literals. 6663 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6664 bool isConstant = false; 6665 QualType T = DR->getType(); 6666 6667 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6668 isConstant = AT->getElementType().isConstant(S.Context); 6669 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6670 isConstant = T.isConstant(S.Context) && 6671 PT->getPointeeType().isConstant(S.Context); 6672 } else if (T->isObjCObjectPointerType()) { 6673 // In ObjC, there is usually no "const ObjectPointer" type, 6674 // so don't check if the pointee type is constant. 6675 isConstant = T.isConstant(S.Context); 6676 } 6677 6678 if (isConstant) { 6679 if (const Expr *Init = VD->getAnyInitializer()) { 6680 // Look through initializers like const char c[] = { "foo" } 6681 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6682 if (InitList->isStringLiteralInit()) 6683 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6684 } 6685 return checkFormatStringExpr(S, Init, Args, 6686 HasVAListArg, format_idx, 6687 firstDataArg, Type, CallType, 6688 /*InFunctionCall*/ false, CheckedVarArgs, 6689 UncoveredArg, Offset); 6690 } 6691 } 6692 6693 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6694 // special check to see if the format string is a function parameter 6695 // of the function calling the printf function. If the function 6696 // has an attribute indicating it is a printf-like function, then we 6697 // should suppress warnings concerning non-literals being used in a call 6698 // to a vprintf function. For example: 6699 // 6700 // void 6701 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6702 // va_list ap; 6703 // va_start(ap, fmt); 6704 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6705 // ... 6706 // } 6707 if (HasVAListArg) { 6708 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6709 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6710 int PVIndex = PV->getFunctionScopeIndex() + 1; 6711 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6712 // adjust for implicit parameter 6713 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6714 if (MD->isInstance()) 6715 ++PVIndex; 6716 // We also check if the formats are compatible. 6717 // We can't pass a 'scanf' string to a 'printf' function. 6718 if (PVIndex == PVFormat->getFormatIdx() && 6719 Type == S.GetFormatStringType(PVFormat)) 6720 return SLCT_UncheckedLiteral; 6721 } 6722 } 6723 } 6724 } 6725 } 6726 6727 return SLCT_NotALiteral; 6728 } 6729 6730 case Stmt::CallExprClass: 6731 case Stmt::CXXMemberCallExprClass: { 6732 const CallExpr *CE = cast<CallExpr>(E); 6733 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6734 bool IsFirst = true; 6735 StringLiteralCheckType CommonResult; 6736 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6737 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6738 StringLiteralCheckType Result = checkFormatStringExpr( 6739 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6740 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6741 if (IsFirst) { 6742 CommonResult = Result; 6743 IsFirst = false; 6744 } 6745 } 6746 if (!IsFirst) 6747 return CommonResult; 6748 6749 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6750 unsigned BuiltinID = FD->getBuiltinID(); 6751 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6752 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6753 const Expr *Arg = CE->getArg(0); 6754 return checkFormatStringExpr(S, Arg, Args, 6755 HasVAListArg, format_idx, 6756 firstDataArg, Type, CallType, 6757 InFunctionCall, CheckedVarArgs, 6758 UncoveredArg, Offset); 6759 } 6760 } 6761 } 6762 6763 return SLCT_NotALiteral; 6764 } 6765 case Stmt::ObjCMessageExprClass: { 6766 const auto *ME = cast<ObjCMessageExpr>(E); 6767 if (const auto *ND = ME->getMethodDecl()) { 6768 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6769 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6770 return checkFormatStringExpr( 6771 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6772 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6773 } 6774 } 6775 6776 return SLCT_NotALiteral; 6777 } 6778 case Stmt::ObjCStringLiteralClass: 6779 case Stmt::StringLiteralClass: { 6780 const StringLiteral *StrE = nullptr; 6781 6782 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6783 StrE = ObjCFExpr->getString(); 6784 else 6785 StrE = cast<StringLiteral>(E); 6786 6787 if (StrE) { 6788 if (Offset.isNegative() || Offset > StrE->getLength()) { 6789 // TODO: It would be better to have an explicit warning for out of 6790 // bounds literals. 6791 return SLCT_NotALiteral; 6792 } 6793 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6794 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6795 firstDataArg, Type, InFunctionCall, CallType, 6796 CheckedVarArgs, UncoveredArg); 6797 return SLCT_CheckedLiteral; 6798 } 6799 6800 return SLCT_NotALiteral; 6801 } 6802 case Stmt::BinaryOperatorClass: { 6803 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6804 6805 // A string literal + an int offset is still a string literal. 6806 if (BinOp->isAdditiveOp()) { 6807 Expr::EvalResult LResult, RResult; 6808 6809 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6810 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6811 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6812 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6813 6814 if (LIsInt != RIsInt) { 6815 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6816 6817 if (LIsInt) { 6818 if (BinOpKind == BO_Add) { 6819 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6820 E = BinOp->getRHS(); 6821 goto tryAgain; 6822 } 6823 } else { 6824 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6825 E = BinOp->getLHS(); 6826 goto tryAgain; 6827 } 6828 } 6829 } 6830 6831 return SLCT_NotALiteral; 6832 } 6833 case Stmt::UnaryOperatorClass: { 6834 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6835 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6836 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6837 Expr::EvalResult IndexResult; 6838 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6839 Expr::SE_NoSideEffects, 6840 S.isConstantEvaluated())) { 6841 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6842 /*RHS is int*/ true); 6843 E = ASE->getBase(); 6844 goto tryAgain; 6845 } 6846 } 6847 6848 return SLCT_NotALiteral; 6849 } 6850 6851 default: 6852 return SLCT_NotALiteral; 6853 } 6854 } 6855 6856 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6857 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6858 .Case("scanf", FST_Scanf) 6859 .Cases("printf", "printf0", FST_Printf) 6860 .Cases("NSString", "CFString", FST_NSString) 6861 .Case("strftime", FST_Strftime) 6862 .Case("strfmon", FST_Strfmon) 6863 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6864 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6865 .Case("os_trace", FST_OSLog) 6866 .Case("os_log", FST_OSLog) 6867 .Default(FST_Unknown); 6868 } 6869 6870 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6871 /// functions) for correct use of format strings. 6872 /// Returns true if a format string has been fully checked. 6873 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6874 ArrayRef<const Expr *> Args, 6875 bool IsCXXMember, 6876 VariadicCallType CallType, 6877 SourceLocation Loc, SourceRange Range, 6878 llvm::SmallBitVector &CheckedVarArgs) { 6879 FormatStringInfo FSI; 6880 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6881 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6882 FSI.FirstDataArg, GetFormatStringType(Format), 6883 CallType, Loc, Range, CheckedVarArgs); 6884 return false; 6885 } 6886 6887 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6888 bool HasVAListArg, unsigned format_idx, 6889 unsigned firstDataArg, FormatStringType Type, 6890 VariadicCallType CallType, 6891 SourceLocation Loc, SourceRange Range, 6892 llvm::SmallBitVector &CheckedVarArgs) { 6893 // CHECK: printf/scanf-like function is called with no format string. 6894 if (format_idx >= Args.size()) { 6895 Diag(Loc, diag::warn_missing_format_string) << Range; 6896 return false; 6897 } 6898 6899 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6900 6901 // CHECK: format string is not a string literal. 6902 // 6903 // Dynamically generated format strings are difficult to 6904 // automatically vet at compile time. Requiring that format strings 6905 // are string literals: (1) permits the checking of format strings by 6906 // the compiler and thereby (2) can practically remove the source of 6907 // many format string exploits. 6908 6909 // Format string can be either ObjC string (e.g. @"%d") or 6910 // C string (e.g. "%d") 6911 // ObjC string uses the same format specifiers as C string, so we can use 6912 // the same format string checking logic for both ObjC and C strings. 6913 UncoveredArgHandler UncoveredArg; 6914 StringLiteralCheckType CT = 6915 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6916 format_idx, firstDataArg, Type, CallType, 6917 /*IsFunctionCall*/ true, CheckedVarArgs, 6918 UncoveredArg, 6919 /*no string offset*/ llvm::APSInt(64, false) = 0); 6920 6921 // Generate a diagnostic where an uncovered argument is detected. 6922 if (UncoveredArg.hasUncoveredArg()) { 6923 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6924 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6925 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6926 } 6927 6928 if (CT != SLCT_NotALiteral) 6929 // Literal format string found, check done! 6930 return CT == SLCT_CheckedLiteral; 6931 6932 // Strftime is particular as it always uses a single 'time' argument, 6933 // so it is safe to pass a non-literal string. 6934 if (Type == FST_Strftime) 6935 return false; 6936 6937 // Do not emit diag when the string param is a macro expansion and the 6938 // format is either NSString or CFString. This is a hack to prevent 6939 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6940 // which are usually used in place of NS and CF string literals. 6941 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6942 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6943 return false; 6944 6945 // If there are no arguments specified, warn with -Wformat-security, otherwise 6946 // warn only with -Wformat-nonliteral. 6947 if (Args.size() == firstDataArg) { 6948 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6949 << OrigFormatExpr->getSourceRange(); 6950 switch (Type) { 6951 default: 6952 break; 6953 case FST_Kprintf: 6954 case FST_FreeBSDKPrintf: 6955 case FST_Printf: 6956 Diag(FormatLoc, diag::note_format_security_fixit) 6957 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6958 break; 6959 case FST_NSString: 6960 Diag(FormatLoc, diag::note_format_security_fixit) 6961 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6962 break; 6963 } 6964 } else { 6965 Diag(FormatLoc, diag::warn_format_nonliteral) 6966 << OrigFormatExpr->getSourceRange(); 6967 } 6968 return false; 6969 } 6970 6971 namespace { 6972 6973 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6974 protected: 6975 Sema &S; 6976 const FormatStringLiteral *FExpr; 6977 const Expr *OrigFormatExpr; 6978 const Sema::FormatStringType FSType; 6979 const unsigned FirstDataArg; 6980 const unsigned NumDataArgs; 6981 const char *Beg; // Start of format string. 6982 const bool HasVAListArg; 6983 ArrayRef<const Expr *> Args; 6984 unsigned FormatIdx; 6985 llvm::SmallBitVector CoveredArgs; 6986 bool usesPositionalArgs = false; 6987 bool atFirstArg = true; 6988 bool inFunctionCall; 6989 Sema::VariadicCallType CallType; 6990 llvm::SmallBitVector &CheckedVarArgs; 6991 UncoveredArgHandler &UncoveredArg; 6992 6993 public: 6994 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6995 const Expr *origFormatExpr, 6996 const Sema::FormatStringType type, unsigned firstDataArg, 6997 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6998 ArrayRef<const Expr *> Args, unsigned formatIdx, 6999 bool inFunctionCall, Sema::VariadicCallType callType, 7000 llvm::SmallBitVector &CheckedVarArgs, 7001 UncoveredArgHandler &UncoveredArg) 7002 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7003 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7004 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7005 inFunctionCall(inFunctionCall), CallType(callType), 7006 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7007 CoveredArgs.resize(numDataArgs); 7008 CoveredArgs.reset(); 7009 } 7010 7011 void DoneProcessing(); 7012 7013 void HandleIncompleteSpecifier(const char *startSpecifier, 7014 unsigned specifierLen) override; 7015 7016 void HandleInvalidLengthModifier( 7017 const analyze_format_string::FormatSpecifier &FS, 7018 const analyze_format_string::ConversionSpecifier &CS, 7019 const char *startSpecifier, unsigned specifierLen, 7020 unsigned DiagID); 7021 7022 void HandleNonStandardLengthModifier( 7023 const analyze_format_string::FormatSpecifier &FS, 7024 const char *startSpecifier, unsigned specifierLen); 7025 7026 void HandleNonStandardConversionSpecifier( 7027 const analyze_format_string::ConversionSpecifier &CS, 7028 const char *startSpecifier, unsigned specifierLen); 7029 7030 void HandlePosition(const char *startPos, unsigned posLen) override; 7031 7032 void HandleInvalidPosition(const char *startSpecifier, 7033 unsigned specifierLen, 7034 analyze_format_string::PositionContext p) override; 7035 7036 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7037 7038 void HandleNullChar(const char *nullCharacter) override; 7039 7040 template <typename Range> 7041 static void 7042 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7043 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7044 bool IsStringLocation, Range StringRange, 7045 ArrayRef<FixItHint> Fixit = None); 7046 7047 protected: 7048 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7049 const char *startSpec, 7050 unsigned specifierLen, 7051 const char *csStart, unsigned csLen); 7052 7053 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7054 const char *startSpec, 7055 unsigned specifierLen); 7056 7057 SourceRange getFormatStringRange(); 7058 CharSourceRange getSpecifierRange(const char *startSpecifier, 7059 unsigned specifierLen); 7060 SourceLocation getLocationOfByte(const char *x); 7061 7062 const Expr *getDataArg(unsigned i) const; 7063 7064 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7065 const analyze_format_string::ConversionSpecifier &CS, 7066 const char *startSpecifier, unsigned specifierLen, 7067 unsigned argIndex); 7068 7069 template <typename Range> 7070 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7071 bool IsStringLocation, Range StringRange, 7072 ArrayRef<FixItHint> Fixit = None); 7073 }; 7074 7075 } // namespace 7076 7077 SourceRange CheckFormatHandler::getFormatStringRange() { 7078 return OrigFormatExpr->getSourceRange(); 7079 } 7080 7081 CharSourceRange CheckFormatHandler:: 7082 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7083 SourceLocation Start = getLocationOfByte(startSpecifier); 7084 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7085 7086 // Advance the end SourceLocation by one due to half-open ranges. 7087 End = End.getLocWithOffset(1); 7088 7089 return CharSourceRange::getCharRange(Start, End); 7090 } 7091 7092 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7093 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7094 S.getLangOpts(), S.Context.getTargetInfo()); 7095 } 7096 7097 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7098 unsigned specifierLen){ 7099 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7100 getLocationOfByte(startSpecifier), 7101 /*IsStringLocation*/true, 7102 getSpecifierRange(startSpecifier, specifierLen)); 7103 } 7104 7105 void CheckFormatHandler::HandleInvalidLengthModifier( 7106 const analyze_format_string::FormatSpecifier &FS, 7107 const analyze_format_string::ConversionSpecifier &CS, 7108 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7109 using namespace analyze_format_string; 7110 7111 const LengthModifier &LM = FS.getLengthModifier(); 7112 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7113 7114 // See if we know how to fix this length modifier. 7115 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7116 if (FixedLM) { 7117 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7118 getLocationOfByte(LM.getStart()), 7119 /*IsStringLocation*/true, 7120 getSpecifierRange(startSpecifier, specifierLen)); 7121 7122 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7123 << FixedLM->toString() 7124 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7125 7126 } else { 7127 FixItHint Hint; 7128 if (DiagID == diag::warn_format_nonsensical_length) 7129 Hint = FixItHint::CreateRemoval(LMRange); 7130 7131 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7132 getLocationOfByte(LM.getStart()), 7133 /*IsStringLocation*/true, 7134 getSpecifierRange(startSpecifier, specifierLen), 7135 Hint); 7136 } 7137 } 7138 7139 void CheckFormatHandler::HandleNonStandardLengthModifier( 7140 const analyze_format_string::FormatSpecifier &FS, 7141 const char *startSpecifier, unsigned specifierLen) { 7142 using namespace analyze_format_string; 7143 7144 const LengthModifier &LM = FS.getLengthModifier(); 7145 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7146 7147 // See if we know how to fix this length modifier. 7148 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7149 if (FixedLM) { 7150 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7151 << LM.toString() << 0, 7152 getLocationOfByte(LM.getStart()), 7153 /*IsStringLocation*/true, 7154 getSpecifierRange(startSpecifier, specifierLen)); 7155 7156 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7157 << FixedLM->toString() 7158 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7159 7160 } else { 7161 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7162 << LM.toString() << 0, 7163 getLocationOfByte(LM.getStart()), 7164 /*IsStringLocation*/true, 7165 getSpecifierRange(startSpecifier, specifierLen)); 7166 } 7167 } 7168 7169 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7170 const analyze_format_string::ConversionSpecifier &CS, 7171 const char *startSpecifier, unsigned specifierLen) { 7172 using namespace analyze_format_string; 7173 7174 // See if we know how to fix this conversion specifier. 7175 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7176 if (FixedCS) { 7177 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7178 << CS.toString() << /*conversion specifier*/1, 7179 getLocationOfByte(CS.getStart()), 7180 /*IsStringLocation*/true, 7181 getSpecifierRange(startSpecifier, specifierLen)); 7182 7183 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7184 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7185 << FixedCS->toString() 7186 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7187 } else { 7188 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7189 << CS.toString() << /*conversion specifier*/1, 7190 getLocationOfByte(CS.getStart()), 7191 /*IsStringLocation*/true, 7192 getSpecifierRange(startSpecifier, specifierLen)); 7193 } 7194 } 7195 7196 void CheckFormatHandler::HandlePosition(const char *startPos, 7197 unsigned posLen) { 7198 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7199 getLocationOfByte(startPos), 7200 /*IsStringLocation*/true, 7201 getSpecifierRange(startPos, posLen)); 7202 } 7203 7204 void 7205 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7206 analyze_format_string::PositionContext p) { 7207 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7208 << (unsigned) p, 7209 getLocationOfByte(startPos), /*IsStringLocation*/true, 7210 getSpecifierRange(startPos, posLen)); 7211 } 7212 7213 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7214 unsigned posLen) { 7215 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7216 getLocationOfByte(startPos), 7217 /*IsStringLocation*/true, 7218 getSpecifierRange(startPos, posLen)); 7219 } 7220 7221 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7222 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7223 // The presence of a null character is likely an error. 7224 EmitFormatDiagnostic( 7225 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7226 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7227 getFormatStringRange()); 7228 } 7229 } 7230 7231 // Note that this may return NULL if there was an error parsing or building 7232 // one of the argument expressions. 7233 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7234 return Args[FirstDataArg + i]; 7235 } 7236 7237 void CheckFormatHandler::DoneProcessing() { 7238 // Does the number of data arguments exceed the number of 7239 // format conversions in the format string? 7240 if (!HasVAListArg) { 7241 // Find any arguments that weren't covered. 7242 CoveredArgs.flip(); 7243 signed notCoveredArg = CoveredArgs.find_first(); 7244 if (notCoveredArg >= 0) { 7245 assert((unsigned)notCoveredArg < NumDataArgs); 7246 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7247 } else { 7248 UncoveredArg.setAllCovered(); 7249 } 7250 } 7251 } 7252 7253 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7254 const Expr *ArgExpr) { 7255 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7256 "Invalid state"); 7257 7258 if (!ArgExpr) 7259 return; 7260 7261 SourceLocation Loc = ArgExpr->getBeginLoc(); 7262 7263 if (S.getSourceManager().isInSystemMacro(Loc)) 7264 return; 7265 7266 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7267 for (auto E : DiagnosticExprs) 7268 PDiag << E->getSourceRange(); 7269 7270 CheckFormatHandler::EmitFormatDiagnostic( 7271 S, IsFunctionCall, DiagnosticExprs[0], 7272 PDiag, Loc, /*IsStringLocation*/false, 7273 DiagnosticExprs[0]->getSourceRange()); 7274 } 7275 7276 bool 7277 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7278 SourceLocation Loc, 7279 const char *startSpec, 7280 unsigned specifierLen, 7281 const char *csStart, 7282 unsigned csLen) { 7283 bool keepGoing = true; 7284 if (argIndex < NumDataArgs) { 7285 // Consider the argument coverered, even though the specifier doesn't 7286 // make sense. 7287 CoveredArgs.set(argIndex); 7288 } 7289 else { 7290 // If argIndex exceeds the number of data arguments we 7291 // don't issue a warning because that is just a cascade of warnings (and 7292 // they may have intended '%%' anyway). We don't want to continue processing 7293 // the format string after this point, however, as we will like just get 7294 // gibberish when trying to match arguments. 7295 keepGoing = false; 7296 } 7297 7298 StringRef Specifier(csStart, csLen); 7299 7300 // If the specifier in non-printable, it could be the first byte of a UTF-8 7301 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7302 // hex value. 7303 std::string CodePointStr; 7304 if (!llvm::sys::locale::isPrint(*csStart)) { 7305 llvm::UTF32 CodePoint; 7306 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7307 const llvm::UTF8 *E = 7308 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7309 llvm::ConversionResult Result = 7310 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7311 7312 if (Result != llvm::conversionOK) { 7313 unsigned char FirstChar = *csStart; 7314 CodePoint = (llvm::UTF32)FirstChar; 7315 } 7316 7317 llvm::raw_string_ostream OS(CodePointStr); 7318 if (CodePoint < 256) 7319 OS << "\\x" << llvm::format("%02x", CodePoint); 7320 else if (CodePoint <= 0xFFFF) 7321 OS << "\\u" << llvm::format("%04x", CodePoint); 7322 else 7323 OS << "\\U" << llvm::format("%08x", CodePoint); 7324 OS.flush(); 7325 Specifier = CodePointStr; 7326 } 7327 7328 EmitFormatDiagnostic( 7329 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7330 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7331 7332 return keepGoing; 7333 } 7334 7335 void 7336 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7337 const char *startSpec, 7338 unsigned specifierLen) { 7339 EmitFormatDiagnostic( 7340 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7341 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7342 } 7343 7344 bool 7345 CheckFormatHandler::CheckNumArgs( 7346 const analyze_format_string::FormatSpecifier &FS, 7347 const analyze_format_string::ConversionSpecifier &CS, 7348 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7349 7350 if (argIndex >= NumDataArgs) { 7351 PartialDiagnostic PDiag = FS.usesPositionalArg() 7352 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7353 << (argIndex+1) << NumDataArgs) 7354 : S.PDiag(diag::warn_printf_insufficient_data_args); 7355 EmitFormatDiagnostic( 7356 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7357 getSpecifierRange(startSpecifier, specifierLen)); 7358 7359 // Since more arguments than conversion tokens are given, by extension 7360 // all arguments are covered, so mark this as so. 7361 UncoveredArg.setAllCovered(); 7362 return false; 7363 } 7364 return true; 7365 } 7366 7367 template<typename Range> 7368 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7369 SourceLocation Loc, 7370 bool IsStringLocation, 7371 Range StringRange, 7372 ArrayRef<FixItHint> FixIt) { 7373 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7374 Loc, IsStringLocation, StringRange, FixIt); 7375 } 7376 7377 /// If the format string is not within the function call, emit a note 7378 /// so that the function call and string are in diagnostic messages. 7379 /// 7380 /// \param InFunctionCall if true, the format string is within the function 7381 /// call and only one diagnostic message will be produced. Otherwise, an 7382 /// extra note will be emitted pointing to location of the format string. 7383 /// 7384 /// \param ArgumentExpr the expression that is passed as the format string 7385 /// argument in the function call. Used for getting locations when two 7386 /// diagnostics are emitted. 7387 /// 7388 /// \param PDiag the callee should already have provided any strings for the 7389 /// diagnostic message. This function only adds locations and fixits 7390 /// to diagnostics. 7391 /// 7392 /// \param Loc primary location for diagnostic. If two diagnostics are 7393 /// required, one will be at Loc and a new SourceLocation will be created for 7394 /// the other one. 7395 /// 7396 /// \param IsStringLocation if true, Loc points to the format string should be 7397 /// used for the note. Otherwise, Loc points to the argument list and will 7398 /// be used with PDiag. 7399 /// 7400 /// \param StringRange some or all of the string to highlight. This is 7401 /// templated so it can accept either a CharSourceRange or a SourceRange. 7402 /// 7403 /// \param FixIt optional fix it hint for the format string. 7404 template <typename Range> 7405 void CheckFormatHandler::EmitFormatDiagnostic( 7406 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7407 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7408 Range StringRange, ArrayRef<FixItHint> FixIt) { 7409 if (InFunctionCall) { 7410 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7411 D << StringRange; 7412 D << FixIt; 7413 } else { 7414 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7415 << ArgumentExpr->getSourceRange(); 7416 7417 const Sema::SemaDiagnosticBuilder &Note = 7418 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7419 diag::note_format_string_defined); 7420 7421 Note << StringRange; 7422 Note << FixIt; 7423 } 7424 } 7425 7426 //===--- CHECK: Printf format string checking ------------------------------===// 7427 7428 namespace { 7429 7430 class CheckPrintfHandler : public CheckFormatHandler { 7431 public: 7432 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7433 const Expr *origFormatExpr, 7434 const Sema::FormatStringType type, unsigned firstDataArg, 7435 unsigned numDataArgs, bool isObjC, const char *beg, 7436 bool hasVAListArg, ArrayRef<const Expr *> Args, 7437 unsigned formatIdx, bool inFunctionCall, 7438 Sema::VariadicCallType CallType, 7439 llvm::SmallBitVector &CheckedVarArgs, 7440 UncoveredArgHandler &UncoveredArg) 7441 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7442 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7443 inFunctionCall, CallType, CheckedVarArgs, 7444 UncoveredArg) {} 7445 7446 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7447 7448 /// Returns true if '%@' specifiers are allowed in the format string. 7449 bool allowsObjCArg() const { 7450 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7451 FSType == Sema::FST_OSTrace; 7452 } 7453 7454 bool HandleInvalidPrintfConversionSpecifier( 7455 const analyze_printf::PrintfSpecifier &FS, 7456 const char *startSpecifier, 7457 unsigned specifierLen) override; 7458 7459 void handleInvalidMaskType(StringRef MaskType) override; 7460 7461 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7462 const char *startSpecifier, 7463 unsigned specifierLen) override; 7464 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7465 const char *StartSpecifier, 7466 unsigned SpecifierLen, 7467 const Expr *E); 7468 7469 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7470 const char *startSpecifier, unsigned specifierLen); 7471 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7472 const analyze_printf::OptionalAmount &Amt, 7473 unsigned type, 7474 const char *startSpecifier, unsigned specifierLen); 7475 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7476 const analyze_printf::OptionalFlag &flag, 7477 const char *startSpecifier, unsigned specifierLen); 7478 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7479 const analyze_printf::OptionalFlag &ignoredFlag, 7480 const analyze_printf::OptionalFlag &flag, 7481 const char *startSpecifier, unsigned specifierLen); 7482 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7483 const Expr *E); 7484 7485 void HandleEmptyObjCModifierFlag(const char *startFlag, 7486 unsigned flagLen) override; 7487 7488 void HandleInvalidObjCModifierFlag(const char *startFlag, 7489 unsigned flagLen) override; 7490 7491 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7492 const char *flagsEnd, 7493 const char *conversionPosition) 7494 override; 7495 }; 7496 7497 } // namespace 7498 7499 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7500 const analyze_printf::PrintfSpecifier &FS, 7501 const char *startSpecifier, 7502 unsigned specifierLen) { 7503 const analyze_printf::PrintfConversionSpecifier &CS = 7504 FS.getConversionSpecifier(); 7505 7506 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7507 getLocationOfByte(CS.getStart()), 7508 startSpecifier, specifierLen, 7509 CS.getStart(), CS.getLength()); 7510 } 7511 7512 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7513 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7514 } 7515 7516 bool CheckPrintfHandler::HandleAmount( 7517 const analyze_format_string::OptionalAmount &Amt, 7518 unsigned k, const char *startSpecifier, 7519 unsigned specifierLen) { 7520 if (Amt.hasDataArgument()) { 7521 if (!HasVAListArg) { 7522 unsigned argIndex = Amt.getArgIndex(); 7523 if (argIndex >= NumDataArgs) { 7524 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7525 << k, 7526 getLocationOfByte(Amt.getStart()), 7527 /*IsStringLocation*/true, 7528 getSpecifierRange(startSpecifier, specifierLen)); 7529 // Don't do any more checking. We will just emit 7530 // spurious errors. 7531 return false; 7532 } 7533 7534 // Type check the data argument. It should be an 'int'. 7535 // Although not in conformance with C99, we also allow the argument to be 7536 // an 'unsigned int' as that is a reasonably safe case. GCC also 7537 // doesn't emit a warning for that case. 7538 CoveredArgs.set(argIndex); 7539 const Expr *Arg = getDataArg(argIndex); 7540 if (!Arg) 7541 return false; 7542 7543 QualType T = Arg->getType(); 7544 7545 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7546 assert(AT.isValid()); 7547 7548 if (!AT.matchesType(S.Context, T)) { 7549 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7550 << k << AT.getRepresentativeTypeName(S.Context) 7551 << T << Arg->getSourceRange(), 7552 getLocationOfByte(Amt.getStart()), 7553 /*IsStringLocation*/true, 7554 getSpecifierRange(startSpecifier, specifierLen)); 7555 // Don't do any more checking. We will just emit 7556 // spurious errors. 7557 return false; 7558 } 7559 } 7560 } 7561 return true; 7562 } 7563 7564 void CheckPrintfHandler::HandleInvalidAmount( 7565 const analyze_printf::PrintfSpecifier &FS, 7566 const analyze_printf::OptionalAmount &Amt, 7567 unsigned type, 7568 const char *startSpecifier, 7569 unsigned specifierLen) { 7570 const analyze_printf::PrintfConversionSpecifier &CS = 7571 FS.getConversionSpecifier(); 7572 7573 FixItHint fixit = 7574 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7575 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7576 Amt.getConstantLength())) 7577 : FixItHint(); 7578 7579 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7580 << type << CS.toString(), 7581 getLocationOfByte(Amt.getStart()), 7582 /*IsStringLocation*/true, 7583 getSpecifierRange(startSpecifier, specifierLen), 7584 fixit); 7585 } 7586 7587 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7588 const analyze_printf::OptionalFlag &flag, 7589 const char *startSpecifier, 7590 unsigned specifierLen) { 7591 // Warn about pointless flag with a fixit removal. 7592 const analyze_printf::PrintfConversionSpecifier &CS = 7593 FS.getConversionSpecifier(); 7594 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7595 << flag.toString() << CS.toString(), 7596 getLocationOfByte(flag.getPosition()), 7597 /*IsStringLocation*/true, 7598 getSpecifierRange(startSpecifier, specifierLen), 7599 FixItHint::CreateRemoval( 7600 getSpecifierRange(flag.getPosition(), 1))); 7601 } 7602 7603 void CheckPrintfHandler::HandleIgnoredFlag( 7604 const analyze_printf::PrintfSpecifier &FS, 7605 const analyze_printf::OptionalFlag &ignoredFlag, 7606 const analyze_printf::OptionalFlag &flag, 7607 const char *startSpecifier, 7608 unsigned specifierLen) { 7609 // Warn about ignored flag with a fixit removal. 7610 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7611 << ignoredFlag.toString() << flag.toString(), 7612 getLocationOfByte(ignoredFlag.getPosition()), 7613 /*IsStringLocation*/true, 7614 getSpecifierRange(startSpecifier, specifierLen), 7615 FixItHint::CreateRemoval( 7616 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7617 } 7618 7619 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7620 unsigned flagLen) { 7621 // Warn about an empty flag. 7622 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7623 getLocationOfByte(startFlag), 7624 /*IsStringLocation*/true, 7625 getSpecifierRange(startFlag, flagLen)); 7626 } 7627 7628 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7629 unsigned flagLen) { 7630 // Warn about an invalid flag. 7631 auto Range = getSpecifierRange(startFlag, flagLen); 7632 StringRef flag(startFlag, flagLen); 7633 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7634 getLocationOfByte(startFlag), 7635 /*IsStringLocation*/true, 7636 Range, FixItHint::CreateRemoval(Range)); 7637 } 7638 7639 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7640 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7641 // Warn about using '[...]' without a '@' conversion. 7642 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7643 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7644 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7645 getLocationOfByte(conversionPosition), 7646 /*IsStringLocation*/true, 7647 Range, FixItHint::CreateRemoval(Range)); 7648 } 7649 7650 // Determines if the specified is a C++ class or struct containing 7651 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7652 // "c_str()"). 7653 template<typename MemberKind> 7654 static llvm::SmallPtrSet<MemberKind*, 1> 7655 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7656 const RecordType *RT = Ty->getAs<RecordType>(); 7657 llvm::SmallPtrSet<MemberKind*, 1> Results; 7658 7659 if (!RT) 7660 return Results; 7661 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7662 if (!RD || !RD->getDefinition()) 7663 return Results; 7664 7665 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7666 Sema::LookupMemberName); 7667 R.suppressDiagnostics(); 7668 7669 // We just need to include all members of the right kind turned up by the 7670 // filter, at this point. 7671 if (S.LookupQualifiedName(R, RT->getDecl())) 7672 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7673 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7674 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7675 Results.insert(FK); 7676 } 7677 return Results; 7678 } 7679 7680 /// Check if we could call '.c_str()' on an object. 7681 /// 7682 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7683 /// allow the call, or if it would be ambiguous). 7684 bool Sema::hasCStrMethod(const Expr *E) { 7685 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7686 7687 MethodSet Results = 7688 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7689 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7690 MI != ME; ++MI) 7691 if ((*MI)->getMinRequiredArguments() == 0) 7692 return true; 7693 return false; 7694 } 7695 7696 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7697 // better diagnostic if so. AT is assumed to be valid. 7698 // Returns true when a c_str() conversion method is found. 7699 bool CheckPrintfHandler::checkForCStrMembers( 7700 const analyze_printf::ArgType &AT, const Expr *E) { 7701 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7702 7703 MethodSet Results = 7704 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7705 7706 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7707 MI != ME; ++MI) { 7708 const CXXMethodDecl *Method = *MI; 7709 if (Method->getMinRequiredArguments() == 0 && 7710 AT.matchesType(S.Context, Method->getReturnType())) { 7711 // FIXME: Suggest parens if the expression needs them. 7712 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7713 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7714 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7715 return true; 7716 } 7717 } 7718 7719 return false; 7720 } 7721 7722 bool 7723 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7724 &FS, 7725 const char *startSpecifier, 7726 unsigned specifierLen) { 7727 using namespace analyze_format_string; 7728 using namespace analyze_printf; 7729 7730 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7731 7732 if (FS.consumesDataArgument()) { 7733 if (atFirstArg) { 7734 atFirstArg = false; 7735 usesPositionalArgs = FS.usesPositionalArg(); 7736 } 7737 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7738 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7739 startSpecifier, specifierLen); 7740 return false; 7741 } 7742 } 7743 7744 // First check if the field width, precision, and conversion specifier 7745 // have matching data arguments. 7746 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7747 startSpecifier, specifierLen)) { 7748 return false; 7749 } 7750 7751 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7752 startSpecifier, specifierLen)) { 7753 return false; 7754 } 7755 7756 if (!CS.consumesDataArgument()) { 7757 // FIXME: Technically specifying a precision or field width here 7758 // makes no sense. Worth issuing a warning at some point. 7759 return true; 7760 } 7761 7762 // Consume the argument. 7763 unsigned argIndex = FS.getArgIndex(); 7764 if (argIndex < NumDataArgs) { 7765 // The check to see if the argIndex is valid will come later. 7766 // We set the bit here because we may exit early from this 7767 // function if we encounter some other error. 7768 CoveredArgs.set(argIndex); 7769 } 7770 7771 // FreeBSD kernel extensions. 7772 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7773 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7774 // We need at least two arguments. 7775 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7776 return false; 7777 7778 // Claim the second argument. 7779 CoveredArgs.set(argIndex + 1); 7780 7781 // Type check the first argument (int for %b, pointer for %D) 7782 const Expr *Ex = getDataArg(argIndex); 7783 const analyze_printf::ArgType &AT = 7784 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7785 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7786 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7787 EmitFormatDiagnostic( 7788 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7789 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7790 << false << Ex->getSourceRange(), 7791 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7792 getSpecifierRange(startSpecifier, specifierLen)); 7793 7794 // Type check the second argument (char * for both %b and %D) 7795 Ex = getDataArg(argIndex + 1); 7796 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7797 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7798 EmitFormatDiagnostic( 7799 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7800 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7801 << false << Ex->getSourceRange(), 7802 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7803 getSpecifierRange(startSpecifier, specifierLen)); 7804 7805 return true; 7806 } 7807 7808 // Check for using an Objective-C specific conversion specifier 7809 // in a non-ObjC literal. 7810 if (!allowsObjCArg() && CS.isObjCArg()) { 7811 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7812 specifierLen); 7813 } 7814 7815 // %P can only be used with os_log. 7816 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7817 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7818 specifierLen); 7819 } 7820 7821 // %n is not allowed with os_log. 7822 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7823 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7824 getLocationOfByte(CS.getStart()), 7825 /*IsStringLocation*/ false, 7826 getSpecifierRange(startSpecifier, specifierLen)); 7827 7828 return true; 7829 } 7830 7831 // Only scalars are allowed for os_trace. 7832 if (FSType == Sema::FST_OSTrace && 7833 (CS.getKind() == ConversionSpecifier::PArg || 7834 CS.getKind() == ConversionSpecifier::sArg || 7835 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7836 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7837 specifierLen); 7838 } 7839 7840 // Check for use of public/private annotation outside of os_log(). 7841 if (FSType != Sema::FST_OSLog) { 7842 if (FS.isPublic().isSet()) { 7843 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7844 << "public", 7845 getLocationOfByte(FS.isPublic().getPosition()), 7846 /*IsStringLocation*/ false, 7847 getSpecifierRange(startSpecifier, specifierLen)); 7848 } 7849 if (FS.isPrivate().isSet()) { 7850 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7851 << "private", 7852 getLocationOfByte(FS.isPrivate().getPosition()), 7853 /*IsStringLocation*/ false, 7854 getSpecifierRange(startSpecifier, specifierLen)); 7855 } 7856 } 7857 7858 // Check for invalid use of field width 7859 if (!FS.hasValidFieldWidth()) { 7860 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7861 startSpecifier, specifierLen); 7862 } 7863 7864 // Check for invalid use of precision 7865 if (!FS.hasValidPrecision()) { 7866 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7867 startSpecifier, specifierLen); 7868 } 7869 7870 // Precision is mandatory for %P specifier. 7871 if (CS.getKind() == ConversionSpecifier::PArg && 7872 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7873 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7874 getLocationOfByte(startSpecifier), 7875 /*IsStringLocation*/ false, 7876 getSpecifierRange(startSpecifier, specifierLen)); 7877 } 7878 7879 // Check each flag does not conflict with any other component. 7880 if (!FS.hasValidThousandsGroupingPrefix()) 7881 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7882 if (!FS.hasValidLeadingZeros()) 7883 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7884 if (!FS.hasValidPlusPrefix()) 7885 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7886 if (!FS.hasValidSpacePrefix()) 7887 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7888 if (!FS.hasValidAlternativeForm()) 7889 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7890 if (!FS.hasValidLeftJustified()) 7891 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7892 7893 // Check that flags are not ignored by another flag 7894 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7895 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7896 startSpecifier, specifierLen); 7897 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7898 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7899 startSpecifier, specifierLen); 7900 7901 // Check the length modifier is valid with the given conversion specifier. 7902 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7903 S.getLangOpts())) 7904 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7905 diag::warn_format_nonsensical_length); 7906 else if (!FS.hasStandardLengthModifier()) 7907 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7908 else if (!FS.hasStandardLengthConversionCombination()) 7909 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7910 diag::warn_format_non_standard_conversion_spec); 7911 7912 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7913 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7914 7915 // The remaining checks depend on the data arguments. 7916 if (HasVAListArg) 7917 return true; 7918 7919 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7920 return false; 7921 7922 const Expr *Arg = getDataArg(argIndex); 7923 if (!Arg) 7924 return true; 7925 7926 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7927 } 7928 7929 static bool requiresParensToAddCast(const Expr *E) { 7930 // FIXME: We should have a general way to reason about operator 7931 // precedence and whether parens are actually needed here. 7932 // Take care of a few common cases where they aren't. 7933 const Expr *Inside = E->IgnoreImpCasts(); 7934 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7935 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7936 7937 switch (Inside->getStmtClass()) { 7938 case Stmt::ArraySubscriptExprClass: 7939 case Stmt::CallExprClass: 7940 case Stmt::CharacterLiteralClass: 7941 case Stmt::CXXBoolLiteralExprClass: 7942 case Stmt::DeclRefExprClass: 7943 case Stmt::FloatingLiteralClass: 7944 case Stmt::IntegerLiteralClass: 7945 case Stmt::MemberExprClass: 7946 case Stmt::ObjCArrayLiteralClass: 7947 case Stmt::ObjCBoolLiteralExprClass: 7948 case Stmt::ObjCBoxedExprClass: 7949 case Stmt::ObjCDictionaryLiteralClass: 7950 case Stmt::ObjCEncodeExprClass: 7951 case Stmt::ObjCIvarRefExprClass: 7952 case Stmt::ObjCMessageExprClass: 7953 case Stmt::ObjCPropertyRefExprClass: 7954 case Stmt::ObjCStringLiteralClass: 7955 case Stmt::ObjCSubscriptRefExprClass: 7956 case Stmt::ParenExprClass: 7957 case Stmt::StringLiteralClass: 7958 case Stmt::UnaryOperatorClass: 7959 return false; 7960 default: 7961 return true; 7962 } 7963 } 7964 7965 static std::pair<QualType, StringRef> 7966 shouldNotPrintDirectly(const ASTContext &Context, 7967 QualType IntendedTy, 7968 const Expr *E) { 7969 // Use a 'while' to peel off layers of typedefs. 7970 QualType TyTy = IntendedTy; 7971 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7972 StringRef Name = UserTy->getDecl()->getName(); 7973 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7974 .Case("CFIndex", Context.getNSIntegerType()) 7975 .Case("NSInteger", Context.getNSIntegerType()) 7976 .Case("NSUInteger", Context.getNSUIntegerType()) 7977 .Case("SInt32", Context.IntTy) 7978 .Case("UInt32", Context.UnsignedIntTy) 7979 .Default(QualType()); 7980 7981 if (!CastTy.isNull()) 7982 return std::make_pair(CastTy, Name); 7983 7984 TyTy = UserTy->desugar(); 7985 } 7986 7987 // Strip parens if necessary. 7988 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7989 return shouldNotPrintDirectly(Context, 7990 PE->getSubExpr()->getType(), 7991 PE->getSubExpr()); 7992 7993 // If this is a conditional expression, then its result type is constructed 7994 // via usual arithmetic conversions and thus there might be no necessary 7995 // typedef sugar there. Recurse to operands to check for NSInteger & 7996 // Co. usage condition. 7997 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7998 QualType TrueTy, FalseTy; 7999 StringRef TrueName, FalseName; 8000 8001 std::tie(TrueTy, TrueName) = 8002 shouldNotPrintDirectly(Context, 8003 CO->getTrueExpr()->getType(), 8004 CO->getTrueExpr()); 8005 std::tie(FalseTy, FalseName) = 8006 shouldNotPrintDirectly(Context, 8007 CO->getFalseExpr()->getType(), 8008 CO->getFalseExpr()); 8009 8010 if (TrueTy == FalseTy) 8011 return std::make_pair(TrueTy, TrueName); 8012 else if (TrueTy.isNull()) 8013 return std::make_pair(FalseTy, FalseName); 8014 else if (FalseTy.isNull()) 8015 return std::make_pair(TrueTy, TrueName); 8016 } 8017 8018 return std::make_pair(QualType(), StringRef()); 8019 } 8020 8021 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8022 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8023 /// type do not count. 8024 static bool 8025 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8026 QualType From = ICE->getSubExpr()->getType(); 8027 QualType To = ICE->getType(); 8028 // It's an integer promotion if the destination type is the promoted 8029 // source type. 8030 if (ICE->getCastKind() == CK_IntegralCast && 8031 From->isPromotableIntegerType() && 8032 S.Context.getPromotedIntegerType(From) == To) 8033 return true; 8034 // Look through vector types, since we do default argument promotion for 8035 // those in OpenCL. 8036 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8037 From = VecTy->getElementType(); 8038 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8039 To = VecTy->getElementType(); 8040 // It's a floating promotion if the source type is a lower rank. 8041 return ICE->getCastKind() == CK_FloatingCast && 8042 S.Context.getFloatingTypeOrder(From, To) < 0; 8043 } 8044 8045 bool 8046 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8047 const char *StartSpecifier, 8048 unsigned SpecifierLen, 8049 const Expr *E) { 8050 using namespace analyze_format_string; 8051 using namespace analyze_printf; 8052 8053 // Now type check the data expression that matches the 8054 // format specifier. 8055 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8056 if (!AT.isValid()) 8057 return true; 8058 8059 QualType ExprTy = E->getType(); 8060 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8061 ExprTy = TET->getUnderlyingExpr()->getType(); 8062 } 8063 8064 const analyze_printf::ArgType::MatchKind Match = 8065 AT.matchesType(S.Context, ExprTy); 8066 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 8067 if (Match == analyze_printf::ArgType::Match) 8068 return true; 8069 8070 // Look through argument promotions for our error message's reported type. 8071 // This includes the integral and floating promotions, but excludes array 8072 // and function pointer decay (seeing that an argument intended to be a 8073 // string has type 'char [6]' is probably more confusing than 'char *') and 8074 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8075 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8076 if (isArithmeticArgumentPromotion(S, ICE)) { 8077 E = ICE->getSubExpr(); 8078 ExprTy = E->getType(); 8079 8080 // Check if we didn't match because of an implicit cast from a 'char' 8081 // or 'short' to an 'int'. This is done because printf is a varargs 8082 // function. 8083 if (ICE->getType() == S.Context.IntTy || 8084 ICE->getType() == S.Context.UnsignedIntTy) { 8085 // All further checking is done on the subexpression. 8086 if (AT.matchesType(S.Context, ExprTy)) 8087 return true; 8088 } 8089 } 8090 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8091 // Special case for 'a', which has type 'int' in C. 8092 // Note, however, that we do /not/ want to treat multibyte constants like 8093 // 'MooV' as characters! This form is deprecated but still exists. 8094 if (ExprTy == S.Context.IntTy) 8095 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8096 ExprTy = S.Context.CharTy; 8097 } 8098 8099 // Look through enums to their underlying type. 8100 bool IsEnum = false; 8101 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8102 ExprTy = EnumTy->getDecl()->getIntegerType(); 8103 IsEnum = true; 8104 } 8105 8106 // %C in an Objective-C context prints a unichar, not a wchar_t. 8107 // If the argument is an integer of some kind, believe the %C and suggest 8108 // a cast instead of changing the conversion specifier. 8109 QualType IntendedTy = ExprTy; 8110 if (isObjCContext() && 8111 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8112 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8113 !ExprTy->isCharType()) { 8114 // 'unichar' is defined as a typedef of unsigned short, but we should 8115 // prefer using the typedef if it is visible. 8116 IntendedTy = S.Context.UnsignedShortTy; 8117 8118 // While we are here, check if the value is an IntegerLiteral that happens 8119 // to be within the valid range. 8120 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8121 const llvm::APInt &V = IL->getValue(); 8122 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8123 return true; 8124 } 8125 8126 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8127 Sema::LookupOrdinaryName); 8128 if (S.LookupName(Result, S.getCurScope())) { 8129 NamedDecl *ND = Result.getFoundDecl(); 8130 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8131 if (TD->getUnderlyingType() == IntendedTy) 8132 IntendedTy = S.Context.getTypedefType(TD); 8133 } 8134 } 8135 } 8136 8137 // Special-case some of Darwin's platform-independence types by suggesting 8138 // casts to primitive types that are known to be large enough. 8139 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8140 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8141 QualType CastTy; 8142 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8143 if (!CastTy.isNull()) { 8144 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8145 // (long in ASTContext). Only complain to pedants. 8146 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8147 (AT.isSizeT() || AT.isPtrdiffT()) && 8148 AT.matchesType(S.Context, CastTy)) 8149 Pedantic = true; 8150 IntendedTy = CastTy; 8151 ShouldNotPrintDirectly = true; 8152 } 8153 } 8154 8155 // We may be able to offer a FixItHint if it is a supported type. 8156 PrintfSpecifier fixedFS = FS; 8157 bool Success = 8158 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8159 8160 if (Success) { 8161 // Get the fix string from the fixed format specifier 8162 SmallString<16> buf; 8163 llvm::raw_svector_ostream os(buf); 8164 fixedFS.toString(os); 8165 8166 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8167 8168 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8169 unsigned Diag = 8170 Pedantic 8171 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8172 : diag::warn_format_conversion_argument_type_mismatch; 8173 // In this case, the specifier is wrong and should be changed to match 8174 // the argument. 8175 EmitFormatDiagnostic(S.PDiag(Diag) 8176 << AT.getRepresentativeTypeName(S.Context) 8177 << IntendedTy << IsEnum << E->getSourceRange(), 8178 E->getBeginLoc(), 8179 /*IsStringLocation*/ false, SpecRange, 8180 FixItHint::CreateReplacement(SpecRange, os.str())); 8181 } else { 8182 // The canonical type for formatting this value is different from the 8183 // actual type of the expression. (This occurs, for example, with Darwin's 8184 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8185 // should be printed as 'long' for 64-bit compatibility.) 8186 // Rather than emitting a normal format/argument mismatch, we want to 8187 // add a cast to the recommended type (and correct the format string 8188 // if necessary). 8189 SmallString<16> CastBuf; 8190 llvm::raw_svector_ostream CastFix(CastBuf); 8191 CastFix << "("; 8192 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8193 CastFix << ")"; 8194 8195 SmallVector<FixItHint,4> Hints; 8196 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8197 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8198 8199 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8200 // If there's already a cast present, just replace it. 8201 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8202 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8203 8204 } else if (!requiresParensToAddCast(E)) { 8205 // If the expression has high enough precedence, 8206 // just write the C-style cast. 8207 Hints.push_back( 8208 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8209 } else { 8210 // Otherwise, add parens around the expression as well as the cast. 8211 CastFix << "("; 8212 Hints.push_back( 8213 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8214 8215 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8216 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8217 } 8218 8219 if (ShouldNotPrintDirectly) { 8220 // The expression has a type that should not be printed directly. 8221 // We extract the name from the typedef because we don't want to show 8222 // the underlying type in the diagnostic. 8223 StringRef Name; 8224 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8225 Name = TypedefTy->getDecl()->getName(); 8226 else 8227 Name = CastTyName; 8228 unsigned Diag = Pedantic 8229 ? diag::warn_format_argument_needs_cast_pedantic 8230 : diag::warn_format_argument_needs_cast; 8231 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8232 << E->getSourceRange(), 8233 E->getBeginLoc(), /*IsStringLocation=*/false, 8234 SpecRange, Hints); 8235 } else { 8236 // In this case, the expression could be printed using a different 8237 // specifier, but we've decided that the specifier is probably correct 8238 // and we should cast instead. Just use the normal warning message. 8239 EmitFormatDiagnostic( 8240 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8241 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8242 << E->getSourceRange(), 8243 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8244 } 8245 } 8246 } else { 8247 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8248 SpecifierLen); 8249 // Since the warning for passing non-POD types to variadic functions 8250 // was deferred until now, we emit a warning for non-POD 8251 // arguments here. 8252 switch (S.isValidVarArgType(ExprTy)) { 8253 case Sema::VAK_Valid: 8254 case Sema::VAK_ValidInCXX11: { 8255 unsigned Diag = 8256 Pedantic 8257 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8258 : diag::warn_format_conversion_argument_type_mismatch; 8259 8260 EmitFormatDiagnostic( 8261 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8262 << IsEnum << CSR << E->getSourceRange(), 8263 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8264 break; 8265 } 8266 case Sema::VAK_Undefined: 8267 case Sema::VAK_MSVCUndefined: 8268 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8269 << S.getLangOpts().CPlusPlus11 << ExprTy 8270 << CallType 8271 << AT.getRepresentativeTypeName(S.Context) << CSR 8272 << E->getSourceRange(), 8273 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8274 checkForCStrMembers(AT, E); 8275 break; 8276 8277 case Sema::VAK_Invalid: 8278 if (ExprTy->isObjCObjectType()) 8279 EmitFormatDiagnostic( 8280 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8281 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8282 << AT.getRepresentativeTypeName(S.Context) << CSR 8283 << E->getSourceRange(), 8284 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8285 else 8286 // FIXME: If this is an initializer list, suggest removing the braces 8287 // or inserting a cast to the target type. 8288 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8289 << isa<InitListExpr>(E) << ExprTy << CallType 8290 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8291 break; 8292 } 8293 8294 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8295 "format string specifier index out of range"); 8296 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8297 } 8298 8299 return true; 8300 } 8301 8302 //===--- CHECK: Scanf format string checking ------------------------------===// 8303 8304 namespace { 8305 8306 class CheckScanfHandler : public CheckFormatHandler { 8307 public: 8308 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8309 const Expr *origFormatExpr, Sema::FormatStringType type, 8310 unsigned firstDataArg, unsigned numDataArgs, 8311 const char *beg, bool hasVAListArg, 8312 ArrayRef<const Expr *> Args, unsigned formatIdx, 8313 bool inFunctionCall, Sema::VariadicCallType CallType, 8314 llvm::SmallBitVector &CheckedVarArgs, 8315 UncoveredArgHandler &UncoveredArg) 8316 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8317 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8318 inFunctionCall, CallType, CheckedVarArgs, 8319 UncoveredArg) {} 8320 8321 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8322 const char *startSpecifier, 8323 unsigned specifierLen) override; 8324 8325 bool HandleInvalidScanfConversionSpecifier( 8326 const analyze_scanf::ScanfSpecifier &FS, 8327 const char *startSpecifier, 8328 unsigned specifierLen) override; 8329 8330 void HandleIncompleteScanList(const char *start, const char *end) override; 8331 }; 8332 8333 } // namespace 8334 8335 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8336 const char *end) { 8337 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8338 getLocationOfByte(end), /*IsStringLocation*/true, 8339 getSpecifierRange(start, end - start)); 8340 } 8341 8342 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8343 const analyze_scanf::ScanfSpecifier &FS, 8344 const char *startSpecifier, 8345 unsigned specifierLen) { 8346 const analyze_scanf::ScanfConversionSpecifier &CS = 8347 FS.getConversionSpecifier(); 8348 8349 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8350 getLocationOfByte(CS.getStart()), 8351 startSpecifier, specifierLen, 8352 CS.getStart(), CS.getLength()); 8353 } 8354 8355 bool CheckScanfHandler::HandleScanfSpecifier( 8356 const analyze_scanf::ScanfSpecifier &FS, 8357 const char *startSpecifier, 8358 unsigned specifierLen) { 8359 using namespace analyze_scanf; 8360 using namespace analyze_format_string; 8361 8362 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8363 8364 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8365 // be used to decide if we are using positional arguments consistently. 8366 if (FS.consumesDataArgument()) { 8367 if (atFirstArg) { 8368 atFirstArg = false; 8369 usesPositionalArgs = FS.usesPositionalArg(); 8370 } 8371 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8372 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8373 startSpecifier, specifierLen); 8374 return false; 8375 } 8376 } 8377 8378 // Check if the field with is non-zero. 8379 const OptionalAmount &Amt = FS.getFieldWidth(); 8380 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8381 if (Amt.getConstantAmount() == 0) { 8382 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8383 Amt.getConstantLength()); 8384 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8385 getLocationOfByte(Amt.getStart()), 8386 /*IsStringLocation*/true, R, 8387 FixItHint::CreateRemoval(R)); 8388 } 8389 } 8390 8391 if (!FS.consumesDataArgument()) { 8392 // FIXME: Technically specifying a precision or field width here 8393 // makes no sense. Worth issuing a warning at some point. 8394 return true; 8395 } 8396 8397 // Consume the argument. 8398 unsigned argIndex = FS.getArgIndex(); 8399 if (argIndex < NumDataArgs) { 8400 // The check to see if the argIndex is valid will come later. 8401 // We set the bit here because we may exit early from this 8402 // function if we encounter some other error. 8403 CoveredArgs.set(argIndex); 8404 } 8405 8406 // Check the length modifier is valid with the given conversion specifier. 8407 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8408 S.getLangOpts())) 8409 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8410 diag::warn_format_nonsensical_length); 8411 else if (!FS.hasStandardLengthModifier()) 8412 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8413 else if (!FS.hasStandardLengthConversionCombination()) 8414 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8415 diag::warn_format_non_standard_conversion_spec); 8416 8417 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8418 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8419 8420 // The remaining checks depend on the data arguments. 8421 if (HasVAListArg) 8422 return true; 8423 8424 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8425 return false; 8426 8427 // Check that the argument type matches the format specifier. 8428 const Expr *Ex = getDataArg(argIndex); 8429 if (!Ex) 8430 return true; 8431 8432 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8433 8434 if (!AT.isValid()) { 8435 return true; 8436 } 8437 8438 analyze_format_string::ArgType::MatchKind Match = 8439 AT.matchesType(S.Context, Ex->getType()); 8440 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8441 if (Match == analyze_format_string::ArgType::Match) 8442 return true; 8443 8444 ScanfSpecifier fixedFS = FS; 8445 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8446 S.getLangOpts(), S.Context); 8447 8448 unsigned Diag = 8449 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8450 : diag::warn_format_conversion_argument_type_mismatch; 8451 8452 if (Success) { 8453 // Get the fix string from the fixed format specifier. 8454 SmallString<128> buf; 8455 llvm::raw_svector_ostream os(buf); 8456 fixedFS.toString(os); 8457 8458 EmitFormatDiagnostic( 8459 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8460 << Ex->getType() << false << Ex->getSourceRange(), 8461 Ex->getBeginLoc(), 8462 /*IsStringLocation*/ false, 8463 getSpecifierRange(startSpecifier, specifierLen), 8464 FixItHint::CreateReplacement( 8465 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8466 } else { 8467 EmitFormatDiagnostic(S.PDiag(Diag) 8468 << AT.getRepresentativeTypeName(S.Context) 8469 << Ex->getType() << false << Ex->getSourceRange(), 8470 Ex->getBeginLoc(), 8471 /*IsStringLocation*/ false, 8472 getSpecifierRange(startSpecifier, specifierLen)); 8473 } 8474 8475 return true; 8476 } 8477 8478 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8479 const Expr *OrigFormatExpr, 8480 ArrayRef<const Expr *> Args, 8481 bool HasVAListArg, unsigned format_idx, 8482 unsigned firstDataArg, 8483 Sema::FormatStringType Type, 8484 bool inFunctionCall, 8485 Sema::VariadicCallType CallType, 8486 llvm::SmallBitVector &CheckedVarArgs, 8487 UncoveredArgHandler &UncoveredArg) { 8488 // CHECK: is the format string a wide literal? 8489 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8490 CheckFormatHandler::EmitFormatDiagnostic( 8491 S, inFunctionCall, Args[format_idx], 8492 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8493 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8494 return; 8495 } 8496 8497 // Str - The format string. NOTE: this is NOT null-terminated! 8498 StringRef StrRef = FExpr->getString(); 8499 const char *Str = StrRef.data(); 8500 // Account for cases where the string literal is truncated in a declaration. 8501 const ConstantArrayType *T = 8502 S.Context.getAsConstantArrayType(FExpr->getType()); 8503 assert(T && "String literal not of constant array type!"); 8504 size_t TypeSize = T->getSize().getZExtValue(); 8505 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8506 const unsigned numDataArgs = Args.size() - firstDataArg; 8507 8508 // Emit a warning if the string literal is truncated and does not contain an 8509 // embedded null character. 8510 if (TypeSize <= StrRef.size() && 8511 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8512 CheckFormatHandler::EmitFormatDiagnostic( 8513 S, inFunctionCall, Args[format_idx], 8514 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8515 FExpr->getBeginLoc(), 8516 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8517 return; 8518 } 8519 8520 // CHECK: empty format string? 8521 if (StrLen == 0 && numDataArgs > 0) { 8522 CheckFormatHandler::EmitFormatDiagnostic( 8523 S, inFunctionCall, Args[format_idx], 8524 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8525 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8526 return; 8527 } 8528 8529 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8530 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8531 Type == Sema::FST_OSTrace) { 8532 CheckPrintfHandler H( 8533 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8534 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8535 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8536 CheckedVarArgs, UncoveredArg); 8537 8538 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8539 S.getLangOpts(), 8540 S.Context.getTargetInfo(), 8541 Type == Sema::FST_FreeBSDKPrintf)) 8542 H.DoneProcessing(); 8543 } else if (Type == Sema::FST_Scanf) { 8544 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8545 numDataArgs, Str, HasVAListArg, Args, format_idx, 8546 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8547 8548 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8549 S.getLangOpts(), 8550 S.Context.getTargetInfo())) 8551 H.DoneProcessing(); 8552 } // TODO: handle other formats 8553 } 8554 8555 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8556 // Str - The format string. NOTE: this is NOT null-terminated! 8557 StringRef StrRef = FExpr->getString(); 8558 const char *Str = StrRef.data(); 8559 // Account for cases where the string literal is truncated in a declaration. 8560 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8561 assert(T && "String literal not of constant array type!"); 8562 size_t TypeSize = T->getSize().getZExtValue(); 8563 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8564 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8565 getLangOpts(), 8566 Context.getTargetInfo()); 8567 } 8568 8569 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8570 8571 // Returns the related absolute value function that is larger, of 0 if one 8572 // does not exist. 8573 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8574 switch (AbsFunction) { 8575 default: 8576 return 0; 8577 8578 case Builtin::BI__builtin_abs: 8579 return Builtin::BI__builtin_labs; 8580 case Builtin::BI__builtin_labs: 8581 return Builtin::BI__builtin_llabs; 8582 case Builtin::BI__builtin_llabs: 8583 return 0; 8584 8585 case Builtin::BI__builtin_fabsf: 8586 return Builtin::BI__builtin_fabs; 8587 case Builtin::BI__builtin_fabs: 8588 return Builtin::BI__builtin_fabsl; 8589 case Builtin::BI__builtin_fabsl: 8590 return 0; 8591 8592 case Builtin::BI__builtin_cabsf: 8593 return Builtin::BI__builtin_cabs; 8594 case Builtin::BI__builtin_cabs: 8595 return Builtin::BI__builtin_cabsl; 8596 case Builtin::BI__builtin_cabsl: 8597 return 0; 8598 8599 case Builtin::BIabs: 8600 return Builtin::BIlabs; 8601 case Builtin::BIlabs: 8602 return Builtin::BIllabs; 8603 case Builtin::BIllabs: 8604 return 0; 8605 8606 case Builtin::BIfabsf: 8607 return Builtin::BIfabs; 8608 case Builtin::BIfabs: 8609 return Builtin::BIfabsl; 8610 case Builtin::BIfabsl: 8611 return 0; 8612 8613 case Builtin::BIcabsf: 8614 return Builtin::BIcabs; 8615 case Builtin::BIcabs: 8616 return Builtin::BIcabsl; 8617 case Builtin::BIcabsl: 8618 return 0; 8619 } 8620 } 8621 8622 // Returns the argument type of the absolute value function. 8623 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8624 unsigned AbsType) { 8625 if (AbsType == 0) 8626 return QualType(); 8627 8628 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8629 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8630 if (Error != ASTContext::GE_None) 8631 return QualType(); 8632 8633 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8634 if (!FT) 8635 return QualType(); 8636 8637 if (FT->getNumParams() != 1) 8638 return QualType(); 8639 8640 return FT->getParamType(0); 8641 } 8642 8643 // Returns the best absolute value function, or zero, based on type and 8644 // current absolute value function. 8645 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8646 unsigned AbsFunctionKind) { 8647 unsigned BestKind = 0; 8648 uint64_t ArgSize = Context.getTypeSize(ArgType); 8649 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8650 Kind = getLargerAbsoluteValueFunction(Kind)) { 8651 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8652 if (Context.getTypeSize(ParamType) >= ArgSize) { 8653 if (BestKind == 0) 8654 BestKind = Kind; 8655 else if (Context.hasSameType(ParamType, ArgType)) { 8656 BestKind = Kind; 8657 break; 8658 } 8659 } 8660 } 8661 return BestKind; 8662 } 8663 8664 enum AbsoluteValueKind { 8665 AVK_Integer, 8666 AVK_Floating, 8667 AVK_Complex 8668 }; 8669 8670 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8671 if (T->isIntegralOrEnumerationType()) 8672 return AVK_Integer; 8673 if (T->isRealFloatingType()) 8674 return AVK_Floating; 8675 if (T->isAnyComplexType()) 8676 return AVK_Complex; 8677 8678 llvm_unreachable("Type not integer, floating, or complex"); 8679 } 8680 8681 // Changes the absolute value function to a different type. Preserves whether 8682 // the function is a builtin. 8683 static unsigned changeAbsFunction(unsigned AbsKind, 8684 AbsoluteValueKind ValueKind) { 8685 switch (ValueKind) { 8686 case AVK_Integer: 8687 switch (AbsKind) { 8688 default: 8689 return 0; 8690 case Builtin::BI__builtin_fabsf: 8691 case Builtin::BI__builtin_fabs: 8692 case Builtin::BI__builtin_fabsl: 8693 case Builtin::BI__builtin_cabsf: 8694 case Builtin::BI__builtin_cabs: 8695 case Builtin::BI__builtin_cabsl: 8696 return Builtin::BI__builtin_abs; 8697 case Builtin::BIfabsf: 8698 case Builtin::BIfabs: 8699 case Builtin::BIfabsl: 8700 case Builtin::BIcabsf: 8701 case Builtin::BIcabs: 8702 case Builtin::BIcabsl: 8703 return Builtin::BIabs; 8704 } 8705 case AVK_Floating: 8706 switch (AbsKind) { 8707 default: 8708 return 0; 8709 case Builtin::BI__builtin_abs: 8710 case Builtin::BI__builtin_labs: 8711 case Builtin::BI__builtin_llabs: 8712 case Builtin::BI__builtin_cabsf: 8713 case Builtin::BI__builtin_cabs: 8714 case Builtin::BI__builtin_cabsl: 8715 return Builtin::BI__builtin_fabsf; 8716 case Builtin::BIabs: 8717 case Builtin::BIlabs: 8718 case Builtin::BIllabs: 8719 case Builtin::BIcabsf: 8720 case Builtin::BIcabs: 8721 case Builtin::BIcabsl: 8722 return Builtin::BIfabsf; 8723 } 8724 case AVK_Complex: 8725 switch (AbsKind) { 8726 default: 8727 return 0; 8728 case Builtin::BI__builtin_abs: 8729 case Builtin::BI__builtin_labs: 8730 case Builtin::BI__builtin_llabs: 8731 case Builtin::BI__builtin_fabsf: 8732 case Builtin::BI__builtin_fabs: 8733 case Builtin::BI__builtin_fabsl: 8734 return Builtin::BI__builtin_cabsf; 8735 case Builtin::BIabs: 8736 case Builtin::BIlabs: 8737 case Builtin::BIllabs: 8738 case Builtin::BIfabsf: 8739 case Builtin::BIfabs: 8740 case Builtin::BIfabsl: 8741 return Builtin::BIcabsf; 8742 } 8743 } 8744 llvm_unreachable("Unable to convert function"); 8745 } 8746 8747 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8748 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8749 if (!FnInfo) 8750 return 0; 8751 8752 switch (FDecl->getBuiltinID()) { 8753 default: 8754 return 0; 8755 case Builtin::BI__builtin_abs: 8756 case Builtin::BI__builtin_fabs: 8757 case Builtin::BI__builtin_fabsf: 8758 case Builtin::BI__builtin_fabsl: 8759 case Builtin::BI__builtin_labs: 8760 case Builtin::BI__builtin_llabs: 8761 case Builtin::BI__builtin_cabs: 8762 case Builtin::BI__builtin_cabsf: 8763 case Builtin::BI__builtin_cabsl: 8764 case Builtin::BIabs: 8765 case Builtin::BIlabs: 8766 case Builtin::BIllabs: 8767 case Builtin::BIfabs: 8768 case Builtin::BIfabsf: 8769 case Builtin::BIfabsl: 8770 case Builtin::BIcabs: 8771 case Builtin::BIcabsf: 8772 case Builtin::BIcabsl: 8773 return FDecl->getBuiltinID(); 8774 } 8775 llvm_unreachable("Unknown Builtin type"); 8776 } 8777 8778 // If the replacement is valid, emit a note with replacement function. 8779 // Additionally, suggest including the proper header if not already included. 8780 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8781 unsigned AbsKind, QualType ArgType) { 8782 bool EmitHeaderHint = true; 8783 const char *HeaderName = nullptr; 8784 const char *FunctionName = nullptr; 8785 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8786 FunctionName = "std::abs"; 8787 if (ArgType->isIntegralOrEnumerationType()) { 8788 HeaderName = "cstdlib"; 8789 } else if (ArgType->isRealFloatingType()) { 8790 HeaderName = "cmath"; 8791 } else { 8792 llvm_unreachable("Invalid Type"); 8793 } 8794 8795 // Lookup all std::abs 8796 if (NamespaceDecl *Std = S.getStdNamespace()) { 8797 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8798 R.suppressDiagnostics(); 8799 S.LookupQualifiedName(R, Std); 8800 8801 for (const auto *I : R) { 8802 const FunctionDecl *FDecl = nullptr; 8803 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8804 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8805 } else { 8806 FDecl = dyn_cast<FunctionDecl>(I); 8807 } 8808 if (!FDecl) 8809 continue; 8810 8811 // Found std::abs(), check that they are the right ones. 8812 if (FDecl->getNumParams() != 1) 8813 continue; 8814 8815 // Check that the parameter type can handle the argument. 8816 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8817 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8818 S.Context.getTypeSize(ArgType) <= 8819 S.Context.getTypeSize(ParamType)) { 8820 // Found a function, don't need the header hint. 8821 EmitHeaderHint = false; 8822 break; 8823 } 8824 } 8825 } 8826 } else { 8827 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8828 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8829 8830 if (HeaderName) { 8831 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8832 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8833 R.suppressDiagnostics(); 8834 S.LookupName(R, S.getCurScope()); 8835 8836 if (R.isSingleResult()) { 8837 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8838 if (FD && FD->getBuiltinID() == AbsKind) { 8839 EmitHeaderHint = false; 8840 } else { 8841 return; 8842 } 8843 } else if (!R.empty()) { 8844 return; 8845 } 8846 } 8847 } 8848 8849 S.Diag(Loc, diag::note_replace_abs_function) 8850 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8851 8852 if (!HeaderName) 8853 return; 8854 8855 if (!EmitHeaderHint) 8856 return; 8857 8858 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8859 << FunctionName; 8860 } 8861 8862 template <std::size_t StrLen> 8863 static bool IsStdFunction(const FunctionDecl *FDecl, 8864 const char (&Str)[StrLen]) { 8865 if (!FDecl) 8866 return false; 8867 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8868 return false; 8869 if (!FDecl->isInStdNamespace()) 8870 return false; 8871 8872 return true; 8873 } 8874 8875 // Warn when using the wrong abs() function. 8876 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8877 const FunctionDecl *FDecl) { 8878 if (Call->getNumArgs() != 1) 8879 return; 8880 8881 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8882 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8883 if (AbsKind == 0 && !IsStdAbs) 8884 return; 8885 8886 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8887 QualType ParamType = Call->getArg(0)->getType(); 8888 8889 // Unsigned types cannot be negative. Suggest removing the absolute value 8890 // function call. 8891 if (ArgType->isUnsignedIntegerType()) { 8892 const char *FunctionName = 8893 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8894 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8895 Diag(Call->getExprLoc(), diag::note_remove_abs) 8896 << FunctionName 8897 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8898 return; 8899 } 8900 8901 // Taking the absolute value of a pointer is very suspicious, they probably 8902 // wanted to index into an array, dereference a pointer, call a function, etc. 8903 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8904 unsigned DiagType = 0; 8905 if (ArgType->isFunctionType()) 8906 DiagType = 1; 8907 else if (ArgType->isArrayType()) 8908 DiagType = 2; 8909 8910 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8911 return; 8912 } 8913 8914 // std::abs has overloads which prevent most of the absolute value problems 8915 // from occurring. 8916 if (IsStdAbs) 8917 return; 8918 8919 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8920 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8921 8922 // The argument and parameter are the same kind. Check if they are the right 8923 // size. 8924 if (ArgValueKind == ParamValueKind) { 8925 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8926 return; 8927 8928 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8929 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8930 << FDecl << ArgType << ParamType; 8931 8932 if (NewAbsKind == 0) 8933 return; 8934 8935 emitReplacement(*this, Call->getExprLoc(), 8936 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8937 return; 8938 } 8939 8940 // ArgValueKind != ParamValueKind 8941 // The wrong type of absolute value function was used. Attempt to find the 8942 // proper one. 8943 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8944 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8945 if (NewAbsKind == 0) 8946 return; 8947 8948 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8949 << FDecl << ParamValueKind << ArgValueKind; 8950 8951 emitReplacement(*this, Call->getExprLoc(), 8952 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8953 } 8954 8955 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8956 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8957 const FunctionDecl *FDecl) { 8958 if (!Call || !FDecl) return; 8959 8960 // Ignore template specializations and macros. 8961 if (inTemplateInstantiation()) return; 8962 if (Call->getExprLoc().isMacroID()) return; 8963 8964 // Only care about the one template argument, two function parameter std::max 8965 if (Call->getNumArgs() != 2) return; 8966 if (!IsStdFunction(FDecl, "max")) return; 8967 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8968 if (!ArgList) return; 8969 if (ArgList->size() != 1) return; 8970 8971 // Check that template type argument is unsigned integer. 8972 const auto& TA = ArgList->get(0); 8973 if (TA.getKind() != TemplateArgument::Type) return; 8974 QualType ArgType = TA.getAsType(); 8975 if (!ArgType->isUnsignedIntegerType()) return; 8976 8977 // See if either argument is a literal zero. 8978 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8979 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8980 if (!MTE) return false; 8981 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8982 if (!Num) return false; 8983 if (Num->getValue() != 0) return false; 8984 return true; 8985 }; 8986 8987 const Expr *FirstArg = Call->getArg(0); 8988 const Expr *SecondArg = Call->getArg(1); 8989 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8990 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8991 8992 // Only warn when exactly one argument is zero. 8993 if (IsFirstArgZero == IsSecondArgZero) return; 8994 8995 SourceRange FirstRange = FirstArg->getSourceRange(); 8996 SourceRange SecondRange = SecondArg->getSourceRange(); 8997 8998 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8999 9000 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9001 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9002 9003 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9004 SourceRange RemovalRange; 9005 if (IsFirstArgZero) { 9006 RemovalRange = SourceRange(FirstRange.getBegin(), 9007 SecondRange.getBegin().getLocWithOffset(-1)); 9008 } else { 9009 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9010 SecondRange.getEnd()); 9011 } 9012 9013 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9014 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9015 << FixItHint::CreateRemoval(RemovalRange); 9016 } 9017 9018 //===--- CHECK: Standard memory functions ---------------------------------===// 9019 9020 /// Takes the expression passed to the size_t parameter of functions 9021 /// such as memcmp, strncat, etc and warns if it's a comparison. 9022 /// 9023 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9024 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9025 IdentifierInfo *FnName, 9026 SourceLocation FnLoc, 9027 SourceLocation RParenLoc) { 9028 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9029 if (!Size) 9030 return false; 9031 9032 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9033 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9034 return false; 9035 9036 SourceRange SizeRange = Size->getSourceRange(); 9037 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9038 << SizeRange << FnName; 9039 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9040 << FnName 9041 << FixItHint::CreateInsertion( 9042 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9043 << FixItHint::CreateRemoval(RParenLoc); 9044 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9045 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9046 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9047 ")"); 9048 9049 return true; 9050 } 9051 9052 /// Determine whether the given type is or contains a dynamic class type 9053 /// (e.g., whether it has a vtable). 9054 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9055 bool &IsContained) { 9056 // Look through array types while ignoring qualifiers. 9057 const Type *Ty = T->getBaseElementTypeUnsafe(); 9058 IsContained = false; 9059 9060 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9061 RD = RD ? RD->getDefinition() : nullptr; 9062 if (!RD || RD->isInvalidDecl()) 9063 return nullptr; 9064 9065 if (RD->isDynamicClass()) 9066 return RD; 9067 9068 // Check all the fields. If any bases were dynamic, the class is dynamic. 9069 // It's impossible for a class to transitively contain itself by value, so 9070 // infinite recursion is impossible. 9071 for (auto *FD : RD->fields()) { 9072 bool SubContained; 9073 if (const CXXRecordDecl *ContainedRD = 9074 getContainedDynamicClass(FD->getType(), SubContained)) { 9075 IsContained = true; 9076 return ContainedRD; 9077 } 9078 } 9079 9080 return nullptr; 9081 } 9082 9083 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9084 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9085 if (Unary->getKind() == UETT_SizeOf) 9086 return Unary; 9087 return nullptr; 9088 } 9089 9090 /// If E is a sizeof expression, returns its argument expression, 9091 /// otherwise returns NULL. 9092 static const Expr *getSizeOfExprArg(const Expr *E) { 9093 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9094 if (!SizeOf->isArgumentType()) 9095 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9096 return nullptr; 9097 } 9098 9099 /// If E is a sizeof expression, returns its argument type. 9100 static QualType getSizeOfArgType(const Expr *E) { 9101 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9102 return SizeOf->getTypeOfArgument(); 9103 return QualType(); 9104 } 9105 9106 namespace { 9107 9108 struct SearchNonTrivialToInitializeField 9109 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9110 using Super = 9111 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9112 9113 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9114 9115 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9116 SourceLocation SL) { 9117 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9118 asDerived().visitArray(PDIK, AT, SL); 9119 return; 9120 } 9121 9122 Super::visitWithKind(PDIK, FT, SL); 9123 } 9124 9125 void visitARCStrong(QualType FT, SourceLocation SL) { 9126 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9127 } 9128 void visitARCWeak(QualType FT, SourceLocation SL) { 9129 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9130 } 9131 void visitStruct(QualType FT, SourceLocation SL) { 9132 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9133 visit(FD->getType(), FD->getLocation()); 9134 } 9135 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9136 const ArrayType *AT, SourceLocation SL) { 9137 visit(getContext().getBaseElementType(AT), SL); 9138 } 9139 void visitTrivial(QualType FT, SourceLocation SL) {} 9140 9141 static void diag(QualType RT, const Expr *E, Sema &S) { 9142 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9143 } 9144 9145 ASTContext &getContext() { return S.getASTContext(); } 9146 9147 const Expr *E; 9148 Sema &S; 9149 }; 9150 9151 struct SearchNonTrivialToCopyField 9152 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9153 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9154 9155 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9156 9157 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9158 SourceLocation SL) { 9159 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9160 asDerived().visitArray(PCK, AT, SL); 9161 return; 9162 } 9163 9164 Super::visitWithKind(PCK, FT, SL); 9165 } 9166 9167 void visitARCStrong(QualType FT, SourceLocation SL) { 9168 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9169 } 9170 void visitARCWeak(QualType FT, SourceLocation SL) { 9171 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9172 } 9173 void visitStruct(QualType FT, SourceLocation SL) { 9174 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9175 visit(FD->getType(), FD->getLocation()); 9176 } 9177 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9178 SourceLocation SL) { 9179 visit(getContext().getBaseElementType(AT), SL); 9180 } 9181 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9182 SourceLocation SL) {} 9183 void visitTrivial(QualType FT, SourceLocation SL) {} 9184 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9185 9186 static void diag(QualType RT, const Expr *E, Sema &S) { 9187 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9188 } 9189 9190 ASTContext &getContext() { return S.getASTContext(); } 9191 9192 const Expr *E; 9193 Sema &S; 9194 }; 9195 9196 } 9197 9198 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9199 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9200 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9201 9202 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9203 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9204 return false; 9205 9206 return doesExprLikelyComputeSize(BO->getLHS()) || 9207 doesExprLikelyComputeSize(BO->getRHS()); 9208 } 9209 9210 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9211 } 9212 9213 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9214 /// 9215 /// \code 9216 /// #define MACRO 0 9217 /// foo(MACRO); 9218 /// foo(0); 9219 /// \endcode 9220 /// 9221 /// This should return true for the first call to foo, but not for the second 9222 /// (regardless of whether foo is a macro or function). 9223 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9224 SourceLocation CallLoc, 9225 SourceLocation ArgLoc) { 9226 if (!CallLoc.isMacroID()) 9227 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9228 9229 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9230 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9231 } 9232 9233 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9234 /// last two arguments transposed. 9235 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9236 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9237 return; 9238 9239 const Expr *SizeArg = 9240 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9241 9242 auto isLiteralZero = [](const Expr *E) { 9243 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9244 }; 9245 9246 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9247 SourceLocation CallLoc = Call->getRParenLoc(); 9248 SourceManager &SM = S.getSourceManager(); 9249 if (isLiteralZero(SizeArg) && 9250 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9251 9252 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9253 9254 // Some platforms #define bzero to __builtin_memset. See if this is the 9255 // case, and if so, emit a better diagnostic. 9256 if (BId == Builtin::BIbzero || 9257 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9258 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9259 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9260 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9261 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9262 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9263 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9264 } 9265 return; 9266 } 9267 9268 // If the second argument to a memset is a sizeof expression and the third 9269 // isn't, this is also likely an error. This should catch 9270 // 'memset(buf, sizeof(buf), 0xff)'. 9271 if (BId == Builtin::BImemset && 9272 doesExprLikelyComputeSize(Call->getArg(1)) && 9273 !doesExprLikelyComputeSize(Call->getArg(2))) { 9274 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9275 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9276 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9277 return; 9278 } 9279 } 9280 9281 /// Check for dangerous or invalid arguments to memset(). 9282 /// 9283 /// This issues warnings on known problematic, dangerous or unspecified 9284 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9285 /// function calls. 9286 /// 9287 /// \param Call The call expression to diagnose. 9288 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9289 unsigned BId, 9290 IdentifierInfo *FnName) { 9291 assert(BId != 0); 9292 9293 // It is possible to have a non-standard definition of memset. Validate 9294 // we have enough arguments, and if not, abort further checking. 9295 unsigned ExpectedNumArgs = 9296 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9297 if (Call->getNumArgs() < ExpectedNumArgs) 9298 return; 9299 9300 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9301 BId == Builtin::BIstrndup ? 1 : 2); 9302 unsigned LenArg = 9303 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9304 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9305 9306 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9307 Call->getBeginLoc(), Call->getRParenLoc())) 9308 return; 9309 9310 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9311 CheckMemaccessSize(*this, BId, Call); 9312 9313 // We have special checking when the length is a sizeof expression. 9314 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9315 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9316 llvm::FoldingSetNodeID SizeOfArgID; 9317 9318 // Although widely used, 'bzero' is not a standard function. Be more strict 9319 // with the argument types before allowing diagnostics and only allow the 9320 // form bzero(ptr, sizeof(...)). 9321 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9322 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9323 return; 9324 9325 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9326 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9327 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9328 9329 QualType DestTy = Dest->getType(); 9330 QualType PointeeTy; 9331 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9332 PointeeTy = DestPtrTy->getPointeeType(); 9333 9334 // Never warn about void type pointers. This can be used to suppress 9335 // false positives. 9336 if (PointeeTy->isVoidType()) 9337 continue; 9338 9339 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9340 // actually comparing the expressions for equality. Because computing the 9341 // expression IDs can be expensive, we only do this if the diagnostic is 9342 // enabled. 9343 if (SizeOfArg && 9344 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9345 SizeOfArg->getExprLoc())) { 9346 // We only compute IDs for expressions if the warning is enabled, and 9347 // cache the sizeof arg's ID. 9348 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9349 SizeOfArg->Profile(SizeOfArgID, Context, true); 9350 llvm::FoldingSetNodeID DestID; 9351 Dest->Profile(DestID, Context, true); 9352 if (DestID == SizeOfArgID) { 9353 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9354 // over sizeof(src) as well. 9355 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9356 StringRef ReadableName = FnName->getName(); 9357 9358 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9359 if (UnaryOp->getOpcode() == UO_AddrOf) 9360 ActionIdx = 1; // If its an address-of operator, just remove it. 9361 if (!PointeeTy->isIncompleteType() && 9362 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9363 ActionIdx = 2; // If the pointee's size is sizeof(char), 9364 // suggest an explicit length. 9365 9366 // If the function is defined as a builtin macro, do not show macro 9367 // expansion. 9368 SourceLocation SL = SizeOfArg->getExprLoc(); 9369 SourceRange DSR = Dest->getSourceRange(); 9370 SourceRange SSR = SizeOfArg->getSourceRange(); 9371 SourceManager &SM = getSourceManager(); 9372 9373 if (SM.isMacroArgExpansion(SL)) { 9374 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9375 SL = SM.getSpellingLoc(SL); 9376 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9377 SM.getSpellingLoc(DSR.getEnd())); 9378 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9379 SM.getSpellingLoc(SSR.getEnd())); 9380 } 9381 9382 DiagRuntimeBehavior(SL, SizeOfArg, 9383 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9384 << ReadableName 9385 << PointeeTy 9386 << DestTy 9387 << DSR 9388 << SSR); 9389 DiagRuntimeBehavior(SL, SizeOfArg, 9390 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9391 << ActionIdx 9392 << SSR); 9393 9394 break; 9395 } 9396 } 9397 9398 // Also check for cases where the sizeof argument is the exact same 9399 // type as the memory argument, and where it points to a user-defined 9400 // record type. 9401 if (SizeOfArgTy != QualType()) { 9402 if (PointeeTy->isRecordType() && 9403 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9404 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9405 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9406 << FnName << SizeOfArgTy << ArgIdx 9407 << PointeeTy << Dest->getSourceRange() 9408 << LenExpr->getSourceRange()); 9409 break; 9410 } 9411 } 9412 } else if (DestTy->isArrayType()) { 9413 PointeeTy = DestTy; 9414 } 9415 9416 if (PointeeTy == QualType()) 9417 continue; 9418 9419 // Always complain about dynamic classes. 9420 bool IsContained; 9421 if (const CXXRecordDecl *ContainedRD = 9422 getContainedDynamicClass(PointeeTy, IsContained)) { 9423 9424 unsigned OperationType = 0; 9425 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9426 // "overwritten" if we're warning about the destination for any call 9427 // but memcmp; otherwise a verb appropriate to the call. 9428 if (ArgIdx != 0 || IsCmp) { 9429 if (BId == Builtin::BImemcpy) 9430 OperationType = 1; 9431 else if(BId == Builtin::BImemmove) 9432 OperationType = 2; 9433 else if (IsCmp) 9434 OperationType = 3; 9435 } 9436 9437 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9438 PDiag(diag::warn_dyn_class_memaccess) 9439 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9440 << IsContained << ContainedRD << OperationType 9441 << Call->getCallee()->getSourceRange()); 9442 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9443 BId != Builtin::BImemset) 9444 DiagRuntimeBehavior( 9445 Dest->getExprLoc(), Dest, 9446 PDiag(diag::warn_arc_object_memaccess) 9447 << ArgIdx << FnName << PointeeTy 9448 << Call->getCallee()->getSourceRange()); 9449 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9450 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9451 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9452 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9453 PDiag(diag::warn_cstruct_memaccess) 9454 << ArgIdx << FnName << PointeeTy << 0); 9455 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9456 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9457 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9458 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9459 PDiag(diag::warn_cstruct_memaccess) 9460 << ArgIdx << FnName << PointeeTy << 1); 9461 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9462 } else { 9463 continue; 9464 } 9465 } else 9466 continue; 9467 9468 DiagRuntimeBehavior( 9469 Dest->getExprLoc(), Dest, 9470 PDiag(diag::note_bad_memaccess_silence) 9471 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9472 break; 9473 } 9474 } 9475 9476 // A little helper routine: ignore addition and subtraction of integer literals. 9477 // This intentionally does not ignore all integer constant expressions because 9478 // we don't want to remove sizeof(). 9479 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9480 Ex = Ex->IgnoreParenCasts(); 9481 9482 while (true) { 9483 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9484 if (!BO || !BO->isAdditiveOp()) 9485 break; 9486 9487 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9488 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9489 9490 if (isa<IntegerLiteral>(RHS)) 9491 Ex = LHS; 9492 else if (isa<IntegerLiteral>(LHS)) 9493 Ex = RHS; 9494 else 9495 break; 9496 } 9497 9498 return Ex; 9499 } 9500 9501 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9502 ASTContext &Context) { 9503 // Only handle constant-sized or VLAs, but not flexible members. 9504 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9505 // Only issue the FIXIT for arrays of size > 1. 9506 if (CAT->getSize().getSExtValue() <= 1) 9507 return false; 9508 } else if (!Ty->isVariableArrayType()) { 9509 return false; 9510 } 9511 return true; 9512 } 9513 9514 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9515 // be the size of the source, instead of the destination. 9516 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9517 IdentifierInfo *FnName) { 9518 9519 // Don't crash if the user has the wrong number of arguments 9520 unsigned NumArgs = Call->getNumArgs(); 9521 if ((NumArgs != 3) && (NumArgs != 4)) 9522 return; 9523 9524 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9525 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9526 const Expr *CompareWithSrc = nullptr; 9527 9528 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9529 Call->getBeginLoc(), Call->getRParenLoc())) 9530 return; 9531 9532 // Look for 'strlcpy(dst, x, sizeof(x))' 9533 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9534 CompareWithSrc = Ex; 9535 else { 9536 // Look for 'strlcpy(dst, x, strlen(x))' 9537 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9538 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9539 SizeCall->getNumArgs() == 1) 9540 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9541 } 9542 } 9543 9544 if (!CompareWithSrc) 9545 return; 9546 9547 // Determine if the argument to sizeof/strlen is equal to the source 9548 // argument. In principle there's all kinds of things you could do 9549 // here, for instance creating an == expression and evaluating it with 9550 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9551 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9552 if (!SrcArgDRE) 9553 return; 9554 9555 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9556 if (!CompareWithSrcDRE || 9557 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9558 return; 9559 9560 const Expr *OriginalSizeArg = Call->getArg(2); 9561 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9562 << OriginalSizeArg->getSourceRange() << FnName; 9563 9564 // Output a FIXIT hint if the destination is an array (rather than a 9565 // pointer to an array). This could be enhanced to handle some 9566 // pointers if we know the actual size, like if DstArg is 'array+2' 9567 // we could say 'sizeof(array)-2'. 9568 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9569 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9570 return; 9571 9572 SmallString<128> sizeString; 9573 llvm::raw_svector_ostream OS(sizeString); 9574 OS << "sizeof("; 9575 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9576 OS << ")"; 9577 9578 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9579 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9580 OS.str()); 9581 } 9582 9583 /// Check if two expressions refer to the same declaration. 9584 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9585 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9586 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9587 return D1->getDecl() == D2->getDecl(); 9588 return false; 9589 } 9590 9591 static const Expr *getStrlenExprArg(const Expr *E) { 9592 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9593 const FunctionDecl *FD = CE->getDirectCallee(); 9594 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9595 return nullptr; 9596 return CE->getArg(0)->IgnoreParenCasts(); 9597 } 9598 return nullptr; 9599 } 9600 9601 // Warn on anti-patterns as the 'size' argument to strncat. 9602 // The correct size argument should look like following: 9603 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9604 void Sema::CheckStrncatArguments(const CallExpr *CE, 9605 IdentifierInfo *FnName) { 9606 // Don't crash if the user has the wrong number of arguments. 9607 if (CE->getNumArgs() < 3) 9608 return; 9609 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9610 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9611 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9612 9613 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9614 CE->getRParenLoc())) 9615 return; 9616 9617 // Identify common expressions, which are wrongly used as the size argument 9618 // to strncat and may lead to buffer overflows. 9619 unsigned PatternType = 0; 9620 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9621 // - sizeof(dst) 9622 if (referToTheSameDecl(SizeOfArg, DstArg)) 9623 PatternType = 1; 9624 // - sizeof(src) 9625 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9626 PatternType = 2; 9627 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9628 if (BE->getOpcode() == BO_Sub) { 9629 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9630 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9631 // - sizeof(dst) - strlen(dst) 9632 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9633 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9634 PatternType = 1; 9635 // - sizeof(src) - (anything) 9636 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9637 PatternType = 2; 9638 } 9639 } 9640 9641 if (PatternType == 0) 9642 return; 9643 9644 // Generate the diagnostic. 9645 SourceLocation SL = LenArg->getBeginLoc(); 9646 SourceRange SR = LenArg->getSourceRange(); 9647 SourceManager &SM = getSourceManager(); 9648 9649 // If the function is defined as a builtin macro, do not show macro expansion. 9650 if (SM.isMacroArgExpansion(SL)) { 9651 SL = SM.getSpellingLoc(SL); 9652 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9653 SM.getSpellingLoc(SR.getEnd())); 9654 } 9655 9656 // Check if the destination is an array (rather than a pointer to an array). 9657 QualType DstTy = DstArg->getType(); 9658 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9659 Context); 9660 if (!isKnownSizeArray) { 9661 if (PatternType == 1) 9662 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9663 else 9664 Diag(SL, diag::warn_strncat_src_size) << SR; 9665 return; 9666 } 9667 9668 if (PatternType == 1) 9669 Diag(SL, diag::warn_strncat_large_size) << SR; 9670 else 9671 Diag(SL, diag::warn_strncat_src_size) << SR; 9672 9673 SmallString<128> sizeString; 9674 llvm::raw_svector_ostream OS(sizeString); 9675 OS << "sizeof("; 9676 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9677 OS << ") - "; 9678 OS << "strlen("; 9679 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9680 OS << ") - 1"; 9681 9682 Diag(SL, diag::note_strncat_wrong_size) 9683 << FixItHint::CreateReplacement(SR, OS.str()); 9684 } 9685 9686 void 9687 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9688 SourceLocation ReturnLoc, 9689 bool isObjCMethod, 9690 const AttrVec *Attrs, 9691 const FunctionDecl *FD) { 9692 // Check if the return value is null but should not be. 9693 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9694 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9695 CheckNonNullExpr(*this, RetValExp)) 9696 Diag(ReturnLoc, diag::warn_null_ret) 9697 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9698 9699 // C++11 [basic.stc.dynamic.allocation]p4: 9700 // If an allocation function declared with a non-throwing 9701 // exception-specification fails to allocate storage, it shall return 9702 // a null pointer. Any other allocation function that fails to allocate 9703 // storage shall indicate failure only by throwing an exception [...] 9704 if (FD) { 9705 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9706 if (Op == OO_New || Op == OO_Array_New) { 9707 const FunctionProtoType *Proto 9708 = FD->getType()->castAs<FunctionProtoType>(); 9709 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9710 CheckNonNullExpr(*this, RetValExp)) 9711 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9712 << FD << getLangOpts().CPlusPlus11; 9713 } 9714 } 9715 } 9716 9717 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9718 9719 /// Check for comparisons of floating point operands using != and ==. 9720 /// Issue a warning if these are no self-comparisons, as they are not likely 9721 /// to do what the programmer intended. 9722 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9723 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9724 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9725 9726 // Special case: check for x == x (which is OK). 9727 // Do not emit warnings for such cases. 9728 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9729 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9730 if (DRL->getDecl() == DRR->getDecl()) 9731 return; 9732 9733 // Special case: check for comparisons against literals that can be exactly 9734 // represented by APFloat. In such cases, do not emit a warning. This 9735 // is a heuristic: often comparison against such literals are used to 9736 // detect if a value in a variable has not changed. This clearly can 9737 // lead to false negatives. 9738 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9739 if (FLL->isExact()) 9740 return; 9741 } else 9742 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9743 if (FLR->isExact()) 9744 return; 9745 9746 // Check for comparisons with builtin types. 9747 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9748 if (CL->getBuiltinCallee()) 9749 return; 9750 9751 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9752 if (CR->getBuiltinCallee()) 9753 return; 9754 9755 // Emit the diagnostic. 9756 Diag(Loc, diag::warn_floatingpoint_eq) 9757 << LHS->getSourceRange() << RHS->getSourceRange(); 9758 } 9759 9760 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9761 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9762 9763 namespace { 9764 9765 /// Structure recording the 'active' range of an integer-valued 9766 /// expression. 9767 struct IntRange { 9768 /// The number of bits active in the int. 9769 unsigned Width; 9770 9771 /// True if the int is known not to have negative values. 9772 bool NonNegative; 9773 9774 IntRange(unsigned Width, bool NonNegative) 9775 : Width(Width), NonNegative(NonNegative) {} 9776 9777 /// Returns the range of the bool type. 9778 static IntRange forBoolType() { 9779 return IntRange(1, true); 9780 } 9781 9782 /// Returns the range of an opaque value of the given integral type. 9783 static IntRange forValueOfType(ASTContext &C, QualType T) { 9784 return forValueOfCanonicalType(C, 9785 T->getCanonicalTypeInternal().getTypePtr()); 9786 } 9787 9788 /// Returns the range of an opaque value of a canonical integral type. 9789 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9790 assert(T->isCanonicalUnqualified()); 9791 9792 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9793 T = VT->getElementType().getTypePtr(); 9794 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9795 T = CT->getElementType().getTypePtr(); 9796 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9797 T = AT->getValueType().getTypePtr(); 9798 9799 if (!C.getLangOpts().CPlusPlus) { 9800 // For enum types in C code, use the underlying datatype. 9801 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9802 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9803 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9804 // For enum types in C++, use the known bit width of the enumerators. 9805 EnumDecl *Enum = ET->getDecl(); 9806 // In C++11, enums can have a fixed underlying type. Use this type to 9807 // compute the range. 9808 if (Enum->isFixed()) { 9809 return IntRange(C.getIntWidth(QualType(T, 0)), 9810 !ET->isSignedIntegerOrEnumerationType()); 9811 } 9812 9813 unsigned NumPositive = Enum->getNumPositiveBits(); 9814 unsigned NumNegative = Enum->getNumNegativeBits(); 9815 9816 if (NumNegative == 0) 9817 return IntRange(NumPositive, true/*NonNegative*/); 9818 else 9819 return IntRange(std::max(NumPositive + 1, NumNegative), 9820 false/*NonNegative*/); 9821 } 9822 9823 const BuiltinType *BT = cast<BuiltinType>(T); 9824 assert(BT->isInteger()); 9825 9826 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9827 } 9828 9829 /// Returns the "target" range of a canonical integral type, i.e. 9830 /// the range of values expressible in the type. 9831 /// 9832 /// This matches forValueOfCanonicalType except that enums have the 9833 /// full range of their type, not the range of their enumerators. 9834 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9835 assert(T->isCanonicalUnqualified()); 9836 9837 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9838 T = VT->getElementType().getTypePtr(); 9839 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9840 T = CT->getElementType().getTypePtr(); 9841 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9842 T = AT->getValueType().getTypePtr(); 9843 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9844 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9845 9846 const BuiltinType *BT = cast<BuiltinType>(T); 9847 assert(BT->isInteger()); 9848 9849 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9850 } 9851 9852 /// Returns the supremum of two ranges: i.e. their conservative merge. 9853 static IntRange join(IntRange L, IntRange R) { 9854 return IntRange(std::max(L.Width, R.Width), 9855 L.NonNegative && R.NonNegative); 9856 } 9857 9858 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9859 static IntRange meet(IntRange L, IntRange R) { 9860 return IntRange(std::min(L.Width, R.Width), 9861 L.NonNegative || R.NonNegative); 9862 } 9863 }; 9864 9865 } // namespace 9866 9867 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9868 unsigned MaxWidth) { 9869 if (value.isSigned() && value.isNegative()) 9870 return IntRange(value.getMinSignedBits(), false); 9871 9872 if (value.getBitWidth() > MaxWidth) 9873 value = value.trunc(MaxWidth); 9874 9875 // isNonNegative() just checks the sign bit without considering 9876 // signedness. 9877 return IntRange(value.getActiveBits(), true); 9878 } 9879 9880 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9881 unsigned MaxWidth) { 9882 if (result.isInt()) 9883 return GetValueRange(C, result.getInt(), MaxWidth); 9884 9885 if (result.isVector()) { 9886 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9887 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9888 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9889 R = IntRange::join(R, El); 9890 } 9891 return R; 9892 } 9893 9894 if (result.isComplexInt()) { 9895 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9896 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9897 return IntRange::join(R, I); 9898 } 9899 9900 // This can happen with lossless casts to intptr_t of "based" lvalues. 9901 // Assume it might use arbitrary bits. 9902 // FIXME: The only reason we need to pass the type in here is to get 9903 // the sign right on this one case. It would be nice if APValue 9904 // preserved this. 9905 assert(result.isLValue() || result.isAddrLabelDiff()); 9906 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9907 } 9908 9909 static QualType GetExprType(const Expr *E) { 9910 QualType Ty = E->getType(); 9911 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9912 Ty = AtomicRHS->getValueType(); 9913 return Ty; 9914 } 9915 9916 /// Pseudo-evaluate the given integer expression, estimating the 9917 /// range of values it might take. 9918 /// 9919 /// \param MaxWidth - the width to which the value will be truncated 9920 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 9921 bool InConstantContext) { 9922 E = E->IgnoreParens(); 9923 9924 // Try a full evaluation first. 9925 Expr::EvalResult result; 9926 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9927 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9928 9929 // I think we only want to look through implicit casts here; if the 9930 // user has an explicit widening cast, we should treat the value as 9931 // being of the new, wider type. 9932 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9933 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9934 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 9935 9936 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9937 9938 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9939 CE->getCastKind() == CK_BooleanToSignedIntegral; 9940 9941 // Assume that non-integer casts can span the full range of the type. 9942 if (!isIntegerCast) 9943 return OutputTypeRange; 9944 9945 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 9946 std::min(MaxWidth, OutputTypeRange.Width), 9947 InConstantContext); 9948 9949 // Bail out if the subexpr's range is as wide as the cast type. 9950 if (SubRange.Width >= OutputTypeRange.Width) 9951 return OutputTypeRange; 9952 9953 // Otherwise, we take the smaller width, and we're non-negative if 9954 // either the output type or the subexpr is. 9955 return IntRange(SubRange.Width, 9956 SubRange.NonNegative || OutputTypeRange.NonNegative); 9957 } 9958 9959 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9960 // If we can fold the condition, just take that operand. 9961 bool CondResult; 9962 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9963 return GetExprRange(C, 9964 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 9965 MaxWidth, InConstantContext); 9966 9967 // Otherwise, conservatively merge. 9968 IntRange L = 9969 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 9970 IntRange R = 9971 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 9972 return IntRange::join(L, R); 9973 } 9974 9975 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9976 switch (BO->getOpcode()) { 9977 case BO_Cmp: 9978 llvm_unreachable("builtin <=> should have class type"); 9979 9980 // Boolean-valued operations are single-bit and positive. 9981 case BO_LAnd: 9982 case BO_LOr: 9983 case BO_LT: 9984 case BO_GT: 9985 case BO_LE: 9986 case BO_GE: 9987 case BO_EQ: 9988 case BO_NE: 9989 return IntRange::forBoolType(); 9990 9991 // The type of the assignments is the type of the LHS, so the RHS 9992 // is not necessarily the same type. 9993 case BO_MulAssign: 9994 case BO_DivAssign: 9995 case BO_RemAssign: 9996 case BO_AddAssign: 9997 case BO_SubAssign: 9998 case BO_XorAssign: 9999 case BO_OrAssign: 10000 // TODO: bitfields? 10001 return IntRange::forValueOfType(C, GetExprType(E)); 10002 10003 // Simple assignments just pass through the RHS, which will have 10004 // been coerced to the LHS type. 10005 case BO_Assign: 10006 // TODO: bitfields? 10007 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10008 10009 // Operations with opaque sources are black-listed. 10010 case BO_PtrMemD: 10011 case BO_PtrMemI: 10012 return IntRange::forValueOfType(C, GetExprType(E)); 10013 10014 // Bitwise-and uses the *infinum* of the two source ranges. 10015 case BO_And: 10016 case BO_AndAssign: 10017 return IntRange::meet( 10018 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10019 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10020 10021 // Left shift gets black-listed based on a judgement call. 10022 case BO_Shl: 10023 // ...except that we want to treat '1 << (blah)' as logically 10024 // positive. It's an important idiom. 10025 if (IntegerLiteral *I 10026 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10027 if (I->getValue() == 1) { 10028 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10029 return IntRange(R.Width, /*NonNegative*/ true); 10030 } 10031 } 10032 LLVM_FALLTHROUGH; 10033 10034 case BO_ShlAssign: 10035 return IntRange::forValueOfType(C, GetExprType(E)); 10036 10037 // Right shift by a constant can narrow its left argument. 10038 case BO_Shr: 10039 case BO_ShrAssign: { 10040 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10041 10042 // If the shift amount is a positive constant, drop the width by 10043 // that much. 10044 llvm::APSInt shift; 10045 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10046 shift.isNonNegative()) { 10047 unsigned zext = shift.getZExtValue(); 10048 if (zext >= L.Width) 10049 L.Width = (L.NonNegative ? 0 : 1); 10050 else 10051 L.Width -= zext; 10052 } 10053 10054 return L; 10055 } 10056 10057 // Comma acts as its right operand. 10058 case BO_Comma: 10059 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10060 10061 // Black-list pointer subtractions. 10062 case BO_Sub: 10063 if (BO->getLHS()->getType()->isPointerType()) 10064 return IntRange::forValueOfType(C, GetExprType(E)); 10065 break; 10066 10067 // The width of a division result is mostly determined by the size 10068 // of the LHS. 10069 case BO_Div: { 10070 // Don't 'pre-truncate' the operands. 10071 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10072 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10073 10074 // If the divisor is constant, use that. 10075 llvm::APSInt divisor; 10076 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10077 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10078 if (log2 >= L.Width) 10079 L.Width = (L.NonNegative ? 0 : 1); 10080 else 10081 L.Width = std::min(L.Width - log2, MaxWidth); 10082 return L; 10083 } 10084 10085 // Otherwise, just use the LHS's width. 10086 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10087 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10088 } 10089 10090 // The result of a remainder can't be larger than the result of 10091 // either side. 10092 case BO_Rem: { 10093 // Don't 'pre-truncate' the operands. 10094 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10095 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10096 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10097 10098 IntRange meet = IntRange::meet(L, R); 10099 meet.Width = std::min(meet.Width, MaxWidth); 10100 return meet; 10101 } 10102 10103 // The default behavior is okay for these. 10104 case BO_Mul: 10105 case BO_Add: 10106 case BO_Xor: 10107 case BO_Or: 10108 break; 10109 } 10110 10111 // The default case is to treat the operation as if it were closed 10112 // on the narrowest type that encompasses both operands. 10113 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10114 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10115 return IntRange::join(L, R); 10116 } 10117 10118 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10119 switch (UO->getOpcode()) { 10120 // Boolean-valued operations are white-listed. 10121 case UO_LNot: 10122 return IntRange::forBoolType(); 10123 10124 // Operations with opaque sources are black-listed. 10125 case UO_Deref: 10126 case UO_AddrOf: // should be impossible 10127 return IntRange::forValueOfType(C, GetExprType(E)); 10128 10129 default: 10130 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10131 } 10132 } 10133 10134 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10135 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10136 10137 if (const auto *BitField = E->getSourceBitField()) 10138 return IntRange(BitField->getBitWidthValue(C), 10139 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10140 10141 return IntRange::forValueOfType(C, GetExprType(E)); 10142 } 10143 10144 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10145 bool InConstantContext) { 10146 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10147 } 10148 10149 /// Checks whether the given value, which currently has the given 10150 /// source semantics, has the same value when coerced through the 10151 /// target semantics. 10152 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10153 const llvm::fltSemantics &Src, 10154 const llvm::fltSemantics &Tgt) { 10155 llvm::APFloat truncated = value; 10156 10157 bool ignored; 10158 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10159 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10160 10161 return truncated.bitwiseIsEqual(value); 10162 } 10163 10164 /// Checks whether the given value, which currently has the given 10165 /// source semantics, has the same value when coerced through the 10166 /// target semantics. 10167 /// 10168 /// The value might be a vector of floats (or a complex number). 10169 static bool IsSameFloatAfterCast(const APValue &value, 10170 const llvm::fltSemantics &Src, 10171 const llvm::fltSemantics &Tgt) { 10172 if (value.isFloat()) 10173 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10174 10175 if (value.isVector()) { 10176 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10177 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10178 return false; 10179 return true; 10180 } 10181 10182 assert(value.isComplexFloat()); 10183 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10184 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10185 } 10186 10187 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 10188 10189 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10190 // Suppress cases where we are comparing against an enum constant. 10191 if (const DeclRefExpr *DR = 10192 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10193 if (isa<EnumConstantDecl>(DR->getDecl())) 10194 return true; 10195 10196 // Suppress cases where the '0' value is expanded from a macro. 10197 if (E->getBeginLoc().isMacroID()) 10198 return true; 10199 10200 return false; 10201 } 10202 10203 static bool isKnownToHaveUnsignedValue(Expr *E) { 10204 return E->getType()->isIntegerType() && 10205 (!E->getType()->isSignedIntegerType() || 10206 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10207 } 10208 10209 namespace { 10210 /// The promoted range of values of a type. In general this has the 10211 /// following structure: 10212 /// 10213 /// |-----------| . . . |-----------| 10214 /// ^ ^ ^ ^ 10215 /// Min HoleMin HoleMax Max 10216 /// 10217 /// ... where there is only a hole if a signed type is promoted to unsigned 10218 /// (in which case Min and Max are the smallest and largest representable 10219 /// values). 10220 struct PromotedRange { 10221 // Min, or HoleMax if there is a hole. 10222 llvm::APSInt PromotedMin; 10223 // Max, or HoleMin if there is a hole. 10224 llvm::APSInt PromotedMax; 10225 10226 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10227 if (R.Width == 0) 10228 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10229 else if (R.Width >= BitWidth && !Unsigned) { 10230 // Promotion made the type *narrower*. This happens when promoting 10231 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10232 // Treat all values of 'signed int' as being in range for now. 10233 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10234 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10235 } else { 10236 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10237 .extOrTrunc(BitWidth); 10238 PromotedMin.setIsUnsigned(Unsigned); 10239 10240 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10241 .extOrTrunc(BitWidth); 10242 PromotedMax.setIsUnsigned(Unsigned); 10243 } 10244 } 10245 10246 // Determine whether this range is contiguous (has no hole). 10247 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10248 10249 // Where a constant value is within the range. 10250 enum ComparisonResult { 10251 LT = 0x1, 10252 LE = 0x2, 10253 GT = 0x4, 10254 GE = 0x8, 10255 EQ = 0x10, 10256 NE = 0x20, 10257 InRangeFlag = 0x40, 10258 10259 Less = LE | LT | NE, 10260 Min = LE | InRangeFlag, 10261 InRange = InRangeFlag, 10262 Max = GE | InRangeFlag, 10263 Greater = GE | GT | NE, 10264 10265 OnlyValue = LE | GE | EQ | InRangeFlag, 10266 InHole = NE 10267 }; 10268 10269 ComparisonResult compare(const llvm::APSInt &Value) const { 10270 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10271 Value.isUnsigned() == PromotedMin.isUnsigned()); 10272 if (!isContiguous()) { 10273 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10274 if (Value.isMinValue()) return Min; 10275 if (Value.isMaxValue()) return Max; 10276 if (Value >= PromotedMin) return InRange; 10277 if (Value <= PromotedMax) return InRange; 10278 return InHole; 10279 } 10280 10281 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10282 case -1: return Less; 10283 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10284 case 1: 10285 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10286 case -1: return InRange; 10287 case 0: return Max; 10288 case 1: return Greater; 10289 } 10290 } 10291 10292 llvm_unreachable("impossible compare result"); 10293 } 10294 10295 static llvm::Optional<StringRef> 10296 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10297 if (Op == BO_Cmp) { 10298 ComparisonResult LTFlag = LT, GTFlag = GT; 10299 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10300 10301 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10302 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10303 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10304 return llvm::None; 10305 } 10306 10307 ComparisonResult TrueFlag, FalseFlag; 10308 if (Op == BO_EQ) { 10309 TrueFlag = EQ; 10310 FalseFlag = NE; 10311 } else if (Op == BO_NE) { 10312 TrueFlag = NE; 10313 FalseFlag = EQ; 10314 } else { 10315 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10316 TrueFlag = LT; 10317 FalseFlag = GE; 10318 } else { 10319 TrueFlag = GT; 10320 FalseFlag = LE; 10321 } 10322 if (Op == BO_GE || Op == BO_LE) 10323 std::swap(TrueFlag, FalseFlag); 10324 } 10325 if (R & TrueFlag) 10326 return StringRef("true"); 10327 if (R & FalseFlag) 10328 return StringRef("false"); 10329 return llvm::None; 10330 } 10331 }; 10332 } 10333 10334 static bool HasEnumType(Expr *E) { 10335 // Strip off implicit integral promotions. 10336 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10337 if (ICE->getCastKind() != CK_IntegralCast && 10338 ICE->getCastKind() != CK_NoOp) 10339 break; 10340 E = ICE->getSubExpr(); 10341 } 10342 10343 return E->getType()->isEnumeralType(); 10344 } 10345 10346 static int classifyConstantValue(Expr *Constant) { 10347 // The values of this enumeration are used in the diagnostics 10348 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10349 enum ConstantValueKind { 10350 Miscellaneous = 0, 10351 LiteralTrue, 10352 LiteralFalse 10353 }; 10354 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10355 return BL->getValue() ? ConstantValueKind::LiteralTrue 10356 : ConstantValueKind::LiteralFalse; 10357 return ConstantValueKind::Miscellaneous; 10358 } 10359 10360 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10361 Expr *Constant, Expr *Other, 10362 const llvm::APSInt &Value, 10363 bool RhsConstant) { 10364 if (S.inTemplateInstantiation()) 10365 return false; 10366 10367 Expr *OriginalOther = Other; 10368 10369 Constant = Constant->IgnoreParenImpCasts(); 10370 Other = Other->IgnoreParenImpCasts(); 10371 10372 // Suppress warnings on tautological comparisons between values of the same 10373 // enumeration type. There are only two ways we could warn on this: 10374 // - If the constant is outside the range of representable values of 10375 // the enumeration. In such a case, we should warn about the cast 10376 // to enumeration type, not about the comparison. 10377 // - If the constant is the maximum / minimum in-range value. For an 10378 // enumeratin type, such comparisons can be meaningful and useful. 10379 if (Constant->getType()->isEnumeralType() && 10380 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10381 return false; 10382 10383 // TODO: Investigate using GetExprRange() to get tighter bounds 10384 // on the bit ranges. 10385 QualType OtherT = Other->getType(); 10386 if (const auto *AT = OtherT->getAs<AtomicType>()) 10387 OtherT = AT->getValueType(); 10388 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10389 10390 // Whether we're treating Other as being a bool because of the form of 10391 // expression despite it having another type (typically 'int' in C). 10392 bool OtherIsBooleanDespiteType = 10393 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10394 if (OtherIsBooleanDespiteType) 10395 OtherRange = IntRange::forBoolType(); 10396 10397 // Determine the promoted range of the other type and see if a comparison of 10398 // the constant against that range is tautological. 10399 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10400 Value.isUnsigned()); 10401 auto Cmp = OtherPromotedRange.compare(Value); 10402 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10403 if (!Result) 10404 return false; 10405 10406 // Suppress the diagnostic for an in-range comparison if the constant comes 10407 // from a macro or enumerator. We don't want to diagnose 10408 // 10409 // some_long_value <= INT_MAX 10410 // 10411 // when sizeof(int) == sizeof(long). 10412 bool InRange = Cmp & PromotedRange::InRangeFlag; 10413 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10414 return false; 10415 10416 // If this is a comparison to an enum constant, include that 10417 // constant in the diagnostic. 10418 const EnumConstantDecl *ED = nullptr; 10419 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10420 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10421 10422 // Should be enough for uint128 (39 decimal digits) 10423 SmallString<64> PrettySourceValue; 10424 llvm::raw_svector_ostream OS(PrettySourceValue); 10425 if (ED) 10426 OS << '\'' << *ED << "' (" << Value << ")"; 10427 else 10428 OS << Value; 10429 10430 // FIXME: We use a somewhat different formatting for the in-range cases and 10431 // cases involving boolean values for historical reasons. We should pick a 10432 // consistent way of presenting these diagnostics. 10433 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10434 10435 S.DiagRuntimeBehavior( 10436 E->getOperatorLoc(), E, 10437 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10438 : diag::warn_tautological_bool_compare) 10439 << OS.str() << classifyConstantValue(Constant) << OtherT 10440 << OtherIsBooleanDespiteType << *Result 10441 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10442 } else { 10443 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10444 ? (HasEnumType(OriginalOther) 10445 ? diag::warn_unsigned_enum_always_true_comparison 10446 : diag::warn_unsigned_always_true_comparison) 10447 : diag::warn_tautological_constant_compare; 10448 10449 S.Diag(E->getOperatorLoc(), Diag) 10450 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10451 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10452 } 10453 10454 return true; 10455 } 10456 10457 /// Analyze the operands of the given comparison. Implements the 10458 /// fallback case from AnalyzeComparison. 10459 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10460 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10461 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10462 } 10463 10464 /// Implements -Wsign-compare. 10465 /// 10466 /// \param E the binary operator to check for warnings 10467 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10468 // The type the comparison is being performed in. 10469 QualType T = E->getLHS()->getType(); 10470 10471 // Only analyze comparison operators where both sides have been converted to 10472 // the same type. 10473 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10474 return AnalyzeImpConvsInComparison(S, E); 10475 10476 // Don't analyze value-dependent comparisons directly. 10477 if (E->isValueDependent()) 10478 return AnalyzeImpConvsInComparison(S, E); 10479 10480 Expr *LHS = E->getLHS(); 10481 Expr *RHS = E->getRHS(); 10482 10483 if (T->isIntegralType(S.Context)) { 10484 llvm::APSInt RHSValue; 10485 llvm::APSInt LHSValue; 10486 10487 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10488 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10489 10490 // We don't care about expressions whose result is a constant. 10491 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10492 return AnalyzeImpConvsInComparison(S, E); 10493 10494 // We only care about expressions where just one side is literal 10495 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10496 // Is the constant on the RHS or LHS? 10497 const bool RhsConstant = IsRHSIntegralLiteral; 10498 Expr *Const = RhsConstant ? RHS : LHS; 10499 Expr *Other = RhsConstant ? LHS : RHS; 10500 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10501 10502 // Check whether an integer constant comparison results in a value 10503 // of 'true' or 'false'. 10504 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10505 return AnalyzeImpConvsInComparison(S, E); 10506 } 10507 } 10508 10509 if (!T->hasUnsignedIntegerRepresentation()) { 10510 // We don't do anything special if this isn't an unsigned integral 10511 // comparison: we're only interested in integral comparisons, and 10512 // signed comparisons only happen in cases we don't care to warn about. 10513 return AnalyzeImpConvsInComparison(S, E); 10514 } 10515 10516 LHS = LHS->IgnoreParenImpCasts(); 10517 RHS = RHS->IgnoreParenImpCasts(); 10518 10519 if (!S.getLangOpts().CPlusPlus) { 10520 // Avoid warning about comparison of integers with different signs when 10521 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10522 // the type of `E`. 10523 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10524 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10525 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10526 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10527 } 10528 10529 // Check to see if one of the (unmodified) operands is of different 10530 // signedness. 10531 Expr *signedOperand, *unsignedOperand; 10532 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10533 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10534 "unsigned comparison between two signed integer expressions?"); 10535 signedOperand = LHS; 10536 unsignedOperand = RHS; 10537 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10538 signedOperand = RHS; 10539 unsignedOperand = LHS; 10540 } else { 10541 return AnalyzeImpConvsInComparison(S, E); 10542 } 10543 10544 // Otherwise, calculate the effective range of the signed operand. 10545 IntRange signedRange = 10546 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10547 10548 // Go ahead and analyze implicit conversions in the operands. Note 10549 // that we skip the implicit conversions on both sides. 10550 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10551 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10552 10553 // If the signed range is non-negative, -Wsign-compare won't fire. 10554 if (signedRange.NonNegative) 10555 return; 10556 10557 // For (in)equality comparisons, if the unsigned operand is a 10558 // constant which cannot collide with a overflowed signed operand, 10559 // then reinterpreting the signed operand as unsigned will not 10560 // change the result of the comparison. 10561 if (E->isEqualityOp()) { 10562 unsigned comparisonWidth = S.Context.getIntWidth(T); 10563 IntRange unsignedRange = 10564 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10565 10566 // We should never be unable to prove that the unsigned operand is 10567 // non-negative. 10568 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10569 10570 if (unsignedRange.Width < comparisonWidth) 10571 return; 10572 } 10573 10574 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10575 S.PDiag(diag::warn_mixed_sign_comparison) 10576 << LHS->getType() << RHS->getType() 10577 << LHS->getSourceRange() << RHS->getSourceRange()); 10578 } 10579 10580 /// Analyzes an attempt to assign the given value to a bitfield. 10581 /// 10582 /// Returns true if there was something fishy about the attempt. 10583 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10584 SourceLocation InitLoc) { 10585 assert(Bitfield->isBitField()); 10586 if (Bitfield->isInvalidDecl()) 10587 return false; 10588 10589 // White-list bool bitfields. 10590 QualType BitfieldType = Bitfield->getType(); 10591 if (BitfieldType->isBooleanType()) 10592 return false; 10593 10594 if (BitfieldType->isEnumeralType()) { 10595 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10596 // If the underlying enum type was not explicitly specified as an unsigned 10597 // type and the enum contain only positive values, MSVC++ will cause an 10598 // inconsistency by storing this as a signed type. 10599 if (S.getLangOpts().CPlusPlus11 && 10600 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10601 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10602 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10603 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10604 << BitfieldEnumDecl->getNameAsString(); 10605 } 10606 } 10607 10608 if (Bitfield->getType()->isBooleanType()) 10609 return false; 10610 10611 // Ignore value- or type-dependent expressions. 10612 if (Bitfield->getBitWidth()->isValueDependent() || 10613 Bitfield->getBitWidth()->isTypeDependent() || 10614 Init->isValueDependent() || 10615 Init->isTypeDependent()) 10616 return false; 10617 10618 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10619 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10620 10621 Expr::EvalResult Result; 10622 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10623 Expr::SE_AllowSideEffects)) { 10624 // The RHS is not constant. If the RHS has an enum type, make sure the 10625 // bitfield is wide enough to hold all the values of the enum without 10626 // truncation. 10627 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10628 EnumDecl *ED = EnumTy->getDecl(); 10629 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10630 10631 // Enum types are implicitly signed on Windows, so check if there are any 10632 // negative enumerators to see if the enum was intended to be signed or 10633 // not. 10634 bool SignedEnum = ED->getNumNegativeBits() > 0; 10635 10636 // Check for surprising sign changes when assigning enum values to a 10637 // bitfield of different signedness. If the bitfield is signed and we 10638 // have exactly the right number of bits to store this unsigned enum, 10639 // suggest changing the enum to an unsigned type. This typically happens 10640 // on Windows where unfixed enums always use an underlying type of 'int'. 10641 unsigned DiagID = 0; 10642 if (SignedEnum && !SignedBitfield) { 10643 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10644 } else if (SignedBitfield && !SignedEnum && 10645 ED->getNumPositiveBits() == FieldWidth) { 10646 DiagID = diag::warn_signed_bitfield_enum_conversion; 10647 } 10648 10649 if (DiagID) { 10650 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10651 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10652 SourceRange TypeRange = 10653 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10654 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10655 << SignedEnum << TypeRange; 10656 } 10657 10658 // Compute the required bitwidth. If the enum has negative values, we need 10659 // one more bit than the normal number of positive bits to represent the 10660 // sign bit. 10661 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10662 ED->getNumNegativeBits()) 10663 : ED->getNumPositiveBits(); 10664 10665 // Check the bitwidth. 10666 if (BitsNeeded > FieldWidth) { 10667 Expr *WidthExpr = Bitfield->getBitWidth(); 10668 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10669 << Bitfield << ED; 10670 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10671 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10672 } 10673 } 10674 10675 return false; 10676 } 10677 10678 llvm::APSInt Value = Result.Val.getInt(); 10679 10680 unsigned OriginalWidth = Value.getBitWidth(); 10681 10682 if (!Value.isSigned() || Value.isNegative()) 10683 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10684 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10685 OriginalWidth = Value.getMinSignedBits(); 10686 10687 if (OriginalWidth <= FieldWidth) 10688 return false; 10689 10690 // Compute the value which the bitfield will contain. 10691 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10692 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10693 10694 // Check whether the stored value is equal to the original value. 10695 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10696 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10697 return false; 10698 10699 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10700 // therefore don't strictly fit into a signed bitfield of width 1. 10701 if (FieldWidth == 1 && Value == 1) 10702 return false; 10703 10704 std::string PrettyValue = Value.toString(10); 10705 std::string PrettyTrunc = TruncatedValue.toString(10); 10706 10707 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10708 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10709 << Init->getSourceRange(); 10710 10711 return true; 10712 } 10713 10714 /// Analyze the given simple or compound assignment for warning-worthy 10715 /// operations. 10716 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10717 // Just recurse on the LHS. 10718 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10719 10720 // We want to recurse on the RHS as normal unless we're assigning to 10721 // a bitfield. 10722 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10723 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10724 E->getOperatorLoc())) { 10725 // Recurse, ignoring any implicit conversions on the RHS. 10726 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10727 E->getOperatorLoc()); 10728 } 10729 } 10730 10731 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10732 10733 // Diagnose implicitly sequentially-consistent atomic assignment. 10734 if (E->getLHS()->getType()->isAtomicType()) 10735 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10736 } 10737 10738 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10739 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10740 SourceLocation CContext, unsigned diag, 10741 bool pruneControlFlow = false) { 10742 if (pruneControlFlow) { 10743 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10744 S.PDiag(diag) 10745 << SourceType << T << E->getSourceRange() 10746 << SourceRange(CContext)); 10747 return; 10748 } 10749 S.Diag(E->getExprLoc(), diag) 10750 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10751 } 10752 10753 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10754 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10755 SourceLocation CContext, 10756 unsigned diag, bool pruneControlFlow = false) { 10757 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10758 } 10759 10760 /// Diagnose an implicit cast from a floating point value to an integer value. 10761 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10762 SourceLocation CContext) { 10763 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10764 const bool PruneWarnings = S.inTemplateInstantiation(); 10765 10766 Expr *InnerE = E->IgnoreParenImpCasts(); 10767 // We also want to warn on, e.g., "int i = -1.234" 10768 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10769 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10770 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10771 10772 const bool IsLiteral = 10773 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10774 10775 llvm::APFloat Value(0.0); 10776 bool IsConstant = 10777 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10778 if (!IsConstant) { 10779 return DiagnoseImpCast(S, E, T, CContext, 10780 diag::warn_impcast_float_integer, PruneWarnings); 10781 } 10782 10783 bool isExact = false; 10784 10785 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10786 T->hasUnsignedIntegerRepresentation()); 10787 llvm::APFloat::opStatus Result = Value.convertToInteger( 10788 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10789 10790 if (Result == llvm::APFloat::opOK && isExact) { 10791 if (IsLiteral) return; 10792 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10793 PruneWarnings); 10794 } 10795 10796 // Conversion of a floating-point value to a non-bool integer where the 10797 // integral part cannot be represented by the integer type is undefined. 10798 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10799 return DiagnoseImpCast( 10800 S, E, T, CContext, 10801 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10802 : diag::warn_impcast_float_to_integer_out_of_range, 10803 PruneWarnings); 10804 10805 unsigned DiagID = 0; 10806 if (IsLiteral) { 10807 // Warn on floating point literal to integer. 10808 DiagID = diag::warn_impcast_literal_float_to_integer; 10809 } else if (IntegerValue == 0) { 10810 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10811 return DiagnoseImpCast(S, E, T, CContext, 10812 diag::warn_impcast_float_integer, PruneWarnings); 10813 } 10814 // Warn on non-zero to zero conversion. 10815 DiagID = diag::warn_impcast_float_to_integer_zero; 10816 } else { 10817 if (IntegerValue.isUnsigned()) { 10818 if (!IntegerValue.isMaxValue()) { 10819 return DiagnoseImpCast(S, E, T, CContext, 10820 diag::warn_impcast_float_integer, PruneWarnings); 10821 } 10822 } else { // IntegerValue.isSigned() 10823 if (!IntegerValue.isMaxSignedValue() && 10824 !IntegerValue.isMinSignedValue()) { 10825 return DiagnoseImpCast(S, E, T, CContext, 10826 diag::warn_impcast_float_integer, PruneWarnings); 10827 } 10828 } 10829 // Warn on evaluatable floating point expression to integer conversion. 10830 DiagID = diag::warn_impcast_float_to_integer; 10831 } 10832 10833 // FIXME: Force the precision of the source value down so we don't print 10834 // digits which are usually useless (we don't really care here if we 10835 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10836 // would automatically print the shortest representation, but it's a bit 10837 // tricky to implement. 10838 SmallString<16> PrettySourceValue; 10839 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10840 precision = (precision * 59 + 195) / 196; 10841 Value.toString(PrettySourceValue, precision); 10842 10843 SmallString<16> PrettyTargetValue; 10844 if (IsBool) 10845 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10846 else 10847 IntegerValue.toString(PrettyTargetValue); 10848 10849 if (PruneWarnings) { 10850 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10851 S.PDiag(DiagID) 10852 << E->getType() << T.getUnqualifiedType() 10853 << PrettySourceValue << PrettyTargetValue 10854 << E->getSourceRange() << SourceRange(CContext)); 10855 } else { 10856 S.Diag(E->getExprLoc(), DiagID) 10857 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10858 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10859 } 10860 } 10861 10862 /// Analyze the given compound assignment for the possible losing of 10863 /// floating-point precision. 10864 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10865 assert(isa<CompoundAssignOperator>(E) && 10866 "Must be compound assignment operation"); 10867 // Recurse on the LHS and RHS in here 10868 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10869 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10870 10871 if (E->getLHS()->getType()->isAtomicType()) 10872 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10873 10874 // Now check the outermost expression 10875 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10876 const auto *RBT = cast<CompoundAssignOperator>(E) 10877 ->getComputationResultType() 10878 ->getAs<BuiltinType>(); 10879 10880 // The below checks assume source is floating point. 10881 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10882 10883 // If source is floating point but target is an integer. 10884 if (ResultBT->isInteger()) 10885 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10886 E->getExprLoc(), diag::warn_impcast_float_integer); 10887 10888 if (!ResultBT->isFloatingPoint()) 10889 return; 10890 10891 // If both source and target are floating points, warn about losing precision. 10892 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10893 QualType(ResultBT, 0), QualType(RBT, 0)); 10894 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10895 // warn about dropping FP rank. 10896 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10897 diag::warn_impcast_float_result_precision); 10898 } 10899 10900 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10901 IntRange Range) { 10902 if (!Range.Width) return "0"; 10903 10904 llvm::APSInt ValueInRange = Value; 10905 ValueInRange.setIsSigned(!Range.NonNegative); 10906 ValueInRange = ValueInRange.trunc(Range.Width); 10907 return ValueInRange.toString(10); 10908 } 10909 10910 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10911 if (!isa<ImplicitCastExpr>(Ex)) 10912 return false; 10913 10914 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10915 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10916 const Type *Source = 10917 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10918 if (Target->isDependentType()) 10919 return false; 10920 10921 const BuiltinType *FloatCandidateBT = 10922 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10923 const Type *BoolCandidateType = ToBool ? Target : Source; 10924 10925 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10926 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10927 } 10928 10929 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10930 SourceLocation CC) { 10931 unsigned NumArgs = TheCall->getNumArgs(); 10932 for (unsigned i = 0; i < NumArgs; ++i) { 10933 Expr *CurrA = TheCall->getArg(i); 10934 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10935 continue; 10936 10937 bool IsSwapped = ((i > 0) && 10938 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10939 IsSwapped |= ((i < (NumArgs - 1)) && 10940 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10941 if (IsSwapped) { 10942 // Warn on this floating-point to bool conversion. 10943 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10944 CurrA->getType(), CC, 10945 diag::warn_impcast_floating_point_to_bool); 10946 } 10947 } 10948 } 10949 10950 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10951 SourceLocation CC) { 10952 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10953 E->getExprLoc())) 10954 return; 10955 10956 // Don't warn on functions which have return type nullptr_t. 10957 if (isa<CallExpr>(E)) 10958 return; 10959 10960 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10961 const Expr::NullPointerConstantKind NullKind = 10962 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10963 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10964 return; 10965 10966 // Return if target type is a safe conversion. 10967 if (T->isAnyPointerType() || T->isBlockPointerType() || 10968 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10969 return; 10970 10971 SourceLocation Loc = E->getSourceRange().getBegin(); 10972 10973 // Venture through the macro stacks to get to the source of macro arguments. 10974 // The new location is a better location than the complete location that was 10975 // passed in. 10976 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10977 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10978 10979 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10980 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10981 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10982 Loc, S.SourceMgr, S.getLangOpts()); 10983 if (MacroName == "NULL") 10984 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10985 } 10986 10987 // Only warn if the null and context location are in the same macro expansion. 10988 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10989 return; 10990 10991 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10992 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10993 << FixItHint::CreateReplacement(Loc, 10994 S.getFixItZeroLiteralForType(T, Loc)); 10995 } 10996 10997 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10998 ObjCArrayLiteral *ArrayLiteral); 10999 11000 static void 11001 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11002 ObjCDictionaryLiteral *DictionaryLiteral); 11003 11004 /// Check a single element within a collection literal against the 11005 /// target element type. 11006 static void checkObjCCollectionLiteralElement(Sema &S, 11007 QualType TargetElementType, 11008 Expr *Element, 11009 unsigned ElementKind) { 11010 // Skip a bitcast to 'id' or qualified 'id'. 11011 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11012 if (ICE->getCastKind() == CK_BitCast && 11013 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11014 Element = ICE->getSubExpr(); 11015 } 11016 11017 QualType ElementType = Element->getType(); 11018 ExprResult ElementResult(Element); 11019 if (ElementType->getAs<ObjCObjectPointerType>() && 11020 S.CheckSingleAssignmentConstraints(TargetElementType, 11021 ElementResult, 11022 false, false) 11023 != Sema::Compatible) { 11024 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11025 << ElementType << ElementKind << TargetElementType 11026 << Element->getSourceRange(); 11027 } 11028 11029 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11030 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11031 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11032 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11033 } 11034 11035 /// Check an Objective-C array literal being converted to the given 11036 /// target type. 11037 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11038 ObjCArrayLiteral *ArrayLiteral) { 11039 if (!S.NSArrayDecl) 11040 return; 11041 11042 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11043 if (!TargetObjCPtr) 11044 return; 11045 11046 if (TargetObjCPtr->isUnspecialized() || 11047 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11048 != S.NSArrayDecl->getCanonicalDecl()) 11049 return; 11050 11051 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11052 if (TypeArgs.size() != 1) 11053 return; 11054 11055 QualType TargetElementType = TypeArgs[0]; 11056 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11057 checkObjCCollectionLiteralElement(S, TargetElementType, 11058 ArrayLiteral->getElement(I), 11059 0); 11060 } 11061 } 11062 11063 /// Check an Objective-C dictionary literal being converted to the given 11064 /// target type. 11065 static void 11066 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11067 ObjCDictionaryLiteral *DictionaryLiteral) { 11068 if (!S.NSDictionaryDecl) 11069 return; 11070 11071 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11072 if (!TargetObjCPtr) 11073 return; 11074 11075 if (TargetObjCPtr->isUnspecialized() || 11076 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11077 != S.NSDictionaryDecl->getCanonicalDecl()) 11078 return; 11079 11080 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11081 if (TypeArgs.size() != 2) 11082 return; 11083 11084 QualType TargetKeyType = TypeArgs[0]; 11085 QualType TargetObjectType = TypeArgs[1]; 11086 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11087 auto Element = DictionaryLiteral->getKeyValueElement(I); 11088 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11089 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11090 } 11091 } 11092 11093 // Helper function to filter out cases for constant width constant conversion. 11094 // Don't warn on char array initialization or for non-decimal values. 11095 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11096 SourceLocation CC) { 11097 // If initializing from a constant, and the constant starts with '0', 11098 // then it is a binary, octal, or hexadecimal. Allow these constants 11099 // to fill all the bits, even if there is a sign change. 11100 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11101 const char FirstLiteralCharacter = 11102 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11103 if (FirstLiteralCharacter == '0') 11104 return false; 11105 } 11106 11107 // If the CC location points to a '{', and the type is char, then assume 11108 // assume it is an array initialization. 11109 if (CC.isValid() && T->isCharType()) { 11110 const char FirstContextCharacter = 11111 S.getSourceManager().getCharacterData(CC)[0]; 11112 if (FirstContextCharacter == '{') 11113 return false; 11114 } 11115 11116 return true; 11117 } 11118 11119 static void 11120 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 11121 bool *ICContext = nullptr) { 11122 if (E->isTypeDependent() || E->isValueDependent()) return; 11123 11124 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11125 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11126 if (Source == Target) return; 11127 if (Target->isDependentType()) return; 11128 11129 // If the conversion context location is invalid don't complain. We also 11130 // don't want to emit a warning if the issue occurs from the expansion of 11131 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11132 // delay this check as long as possible. Once we detect we are in that 11133 // scenario, we just return. 11134 if (CC.isInvalid()) 11135 return; 11136 11137 if (Source->isAtomicType()) 11138 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11139 11140 // Diagnose implicit casts to bool. 11141 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11142 if (isa<StringLiteral>(E)) 11143 // Warn on string literal to bool. Checks for string literals in logical 11144 // and expressions, for instance, assert(0 && "error here"), are 11145 // prevented by a check in AnalyzeImplicitConversions(). 11146 return DiagnoseImpCast(S, E, T, CC, 11147 diag::warn_impcast_string_literal_to_bool); 11148 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11149 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11150 // This covers the literal expressions that evaluate to Objective-C 11151 // objects. 11152 return DiagnoseImpCast(S, E, T, CC, 11153 diag::warn_impcast_objective_c_literal_to_bool); 11154 } 11155 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11156 // Warn on pointer to bool conversion that is always true. 11157 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11158 SourceRange(CC)); 11159 } 11160 } 11161 11162 // Check implicit casts from Objective-C collection literals to specialized 11163 // collection types, e.g., NSArray<NSString *> *. 11164 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11165 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11166 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11167 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11168 11169 // Strip vector types. 11170 if (isa<VectorType>(Source)) { 11171 if (!isa<VectorType>(Target)) { 11172 if (S.SourceMgr.isInSystemMacro(CC)) 11173 return; 11174 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11175 } 11176 11177 // If the vector cast is cast between two vectors of the same size, it is 11178 // a bitcast, not a conversion. 11179 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11180 return; 11181 11182 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11183 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11184 } 11185 if (auto VecTy = dyn_cast<VectorType>(Target)) 11186 Target = VecTy->getElementType().getTypePtr(); 11187 11188 // Strip complex types. 11189 if (isa<ComplexType>(Source)) { 11190 if (!isa<ComplexType>(Target)) { 11191 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11192 return; 11193 11194 return DiagnoseImpCast(S, E, T, CC, 11195 S.getLangOpts().CPlusPlus 11196 ? diag::err_impcast_complex_scalar 11197 : diag::warn_impcast_complex_scalar); 11198 } 11199 11200 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11201 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11202 } 11203 11204 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11205 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11206 11207 // If the source is floating point... 11208 if (SourceBT && SourceBT->isFloatingPoint()) { 11209 // ...and the target is floating point... 11210 if (TargetBT && TargetBT->isFloatingPoint()) { 11211 // ...then warn if we're dropping FP rank. 11212 11213 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11214 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11215 if (Order > 0) { 11216 // Don't warn about float constants that are precisely 11217 // representable in the target type. 11218 Expr::EvalResult result; 11219 if (E->EvaluateAsRValue(result, S.Context)) { 11220 // Value might be a float, a float vector, or a float complex. 11221 if (IsSameFloatAfterCast(result.Val, 11222 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11223 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11224 return; 11225 } 11226 11227 if (S.SourceMgr.isInSystemMacro(CC)) 11228 return; 11229 11230 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11231 } 11232 // ... or possibly if we're increasing rank, too 11233 else if (Order < 0) { 11234 if (S.SourceMgr.isInSystemMacro(CC)) 11235 return; 11236 11237 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11238 } 11239 return; 11240 } 11241 11242 // If the target is integral, always warn. 11243 if (TargetBT && TargetBT->isInteger()) { 11244 if (S.SourceMgr.isInSystemMacro(CC)) 11245 return; 11246 11247 DiagnoseFloatingImpCast(S, E, T, CC); 11248 } 11249 11250 // Detect the case where a call result is converted from floating-point to 11251 // to bool, and the final argument to the call is converted from bool, to 11252 // discover this typo: 11253 // 11254 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11255 // 11256 // FIXME: This is an incredibly special case; is there some more general 11257 // way to detect this class of misplaced-parentheses bug? 11258 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11259 // Check last argument of function call to see if it is an 11260 // implicit cast from a type matching the type the result 11261 // is being cast to. 11262 CallExpr *CEx = cast<CallExpr>(E); 11263 if (unsigned NumArgs = CEx->getNumArgs()) { 11264 Expr *LastA = CEx->getArg(NumArgs - 1); 11265 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11266 if (isa<ImplicitCastExpr>(LastA) && 11267 InnerE->getType()->isBooleanType()) { 11268 // Warn on this floating-point to bool conversion 11269 DiagnoseImpCast(S, E, T, CC, 11270 diag::warn_impcast_floating_point_to_bool); 11271 } 11272 } 11273 } 11274 return; 11275 } 11276 11277 // Valid casts involving fixed point types should be accounted for here. 11278 if (Source->isFixedPointType()) { 11279 if (Target->isUnsaturatedFixedPointType()) { 11280 Expr::EvalResult Result; 11281 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11282 S.isConstantEvaluated())) { 11283 APFixedPoint Value = Result.Val.getFixedPoint(); 11284 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11285 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11286 if (Value > MaxVal || Value < MinVal) { 11287 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11288 S.PDiag(diag::warn_impcast_fixed_point_range) 11289 << Value.toString() << T 11290 << E->getSourceRange() 11291 << clang::SourceRange(CC)); 11292 return; 11293 } 11294 } 11295 } else if (Target->isIntegerType()) { 11296 Expr::EvalResult Result; 11297 if (!S.isConstantEvaluated() && 11298 E->EvaluateAsFixedPoint(Result, S.Context, 11299 Expr::SE_AllowSideEffects)) { 11300 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11301 11302 bool Overflowed; 11303 llvm::APSInt IntResult = FXResult.convertToInt( 11304 S.Context.getIntWidth(T), 11305 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11306 11307 if (Overflowed) { 11308 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11309 S.PDiag(diag::warn_impcast_fixed_point_range) 11310 << FXResult.toString() << T 11311 << E->getSourceRange() 11312 << clang::SourceRange(CC)); 11313 return; 11314 } 11315 } 11316 } 11317 } else if (Target->isUnsaturatedFixedPointType()) { 11318 if (Source->isIntegerType()) { 11319 Expr::EvalResult Result; 11320 if (!S.isConstantEvaluated() && 11321 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11322 llvm::APSInt Value = Result.Val.getInt(); 11323 11324 bool Overflowed; 11325 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11326 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11327 11328 if (Overflowed) { 11329 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11330 S.PDiag(diag::warn_impcast_fixed_point_range) 11331 << Value.toString(/*radix=*/10) << T 11332 << E->getSourceRange() 11333 << clang::SourceRange(CC)); 11334 return; 11335 } 11336 } 11337 } 11338 } 11339 11340 DiagnoseNullConversion(S, E, T, CC); 11341 11342 S.DiscardMisalignedMemberAddress(Target, E); 11343 11344 if (!Source->isIntegerType() || !Target->isIntegerType()) 11345 return; 11346 11347 // TODO: remove this early return once the false positives for constant->bool 11348 // in templates, macros, etc, are reduced or removed. 11349 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11350 return; 11351 11352 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11353 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11354 11355 if (SourceRange.Width > TargetRange.Width) { 11356 // If the source is a constant, use a default-on diagnostic. 11357 // TODO: this should happen for bitfield stores, too. 11358 Expr::EvalResult Result; 11359 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11360 S.isConstantEvaluated())) { 11361 llvm::APSInt Value(32); 11362 Value = Result.Val.getInt(); 11363 11364 if (S.SourceMgr.isInSystemMacro(CC)) 11365 return; 11366 11367 std::string PrettySourceValue = Value.toString(10); 11368 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11369 11370 S.DiagRuntimeBehavior( 11371 E->getExprLoc(), E, 11372 S.PDiag(diag::warn_impcast_integer_precision_constant) 11373 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11374 << E->getSourceRange() << clang::SourceRange(CC)); 11375 return; 11376 } 11377 11378 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11379 if (S.SourceMgr.isInSystemMacro(CC)) 11380 return; 11381 11382 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11383 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11384 /* pruneControlFlow */ true); 11385 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11386 } 11387 11388 if (TargetRange.Width > SourceRange.Width) { 11389 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11390 if (UO->getOpcode() == UO_Minus) 11391 if (Source->isUnsignedIntegerType()) { 11392 if (Target->isUnsignedIntegerType()) 11393 return DiagnoseImpCast(S, E, T, CC, 11394 diag::warn_impcast_high_order_zero_bits); 11395 if (Target->isSignedIntegerType()) 11396 return DiagnoseImpCast(S, E, T, CC, 11397 diag::warn_impcast_nonnegative_result); 11398 } 11399 } 11400 11401 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11402 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11403 // Warn when doing a signed to signed conversion, warn if the positive 11404 // source value is exactly the width of the target type, which will 11405 // cause a negative value to be stored. 11406 11407 Expr::EvalResult Result; 11408 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11409 !S.SourceMgr.isInSystemMacro(CC)) { 11410 llvm::APSInt Value = Result.Val.getInt(); 11411 if (isSameWidthConstantConversion(S, E, T, CC)) { 11412 std::string PrettySourceValue = Value.toString(10); 11413 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11414 11415 S.DiagRuntimeBehavior( 11416 E->getExprLoc(), E, 11417 S.PDiag(diag::warn_impcast_integer_precision_constant) 11418 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11419 << E->getSourceRange() << clang::SourceRange(CC)); 11420 return; 11421 } 11422 } 11423 11424 // Fall through for non-constants to give a sign conversion warning. 11425 } 11426 11427 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11428 (!TargetRange.NonNegative && SourceRange.NonNegative && 11429 SourceRange.Width == TargetRange.Width)) { 11430 if (S.SourceMgr.isInSystemMacro(CC)) 11431 return; 11432 11433 unsigned DiagID = diag::warn_impcast_integer_sign; 11434 11435 // Traditionally, gcc has warned about this under -Wsign-compare. 11436 // We also want to warn about it in -Wconversion. 11437 // So if -Wconversion is off, use a completely identical diagnostic 11438 // in the sign-compare group. 11439 // The conditional-checking code will 11440 if (ICContext) { 11441 DiagID = diag::warn_impcast_integer_sign_conditional; 11442 *ICContext = true; 11443 } 11444 11445 return DiagnoseImpCast(S, E, T, CC, DiagID); 11446 } 11447 11448 // Diagnose conversions between different enumeration types. 11449 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11450 // type, to give us better diagnostics. 11451 QualType SourceType = E->getType(); 11452 if (!S.getLangOpts().CPlusPlus) { 11453 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11454 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11455 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11456 SourceType = S.Context.getTypeDeclType(Enum); 11457 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11458 } 11459 } 11460 11461 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11462 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11463 if (SourceEnum->getDecl()->hasNameForLinkage() && 11464 TargetEnum->getDecl()->hasNameForLinkage() && 11465 SourceEnum != TargetEnum) { 11466 if (S.SourceMgr.isInSystemMacro(CC)) 11467 return; 11468 11469 return DiagnoseImpCast(S, E, SourceType, T, CC, 11470 diag::warn_impcast_different_enum_types); 11471 } 11472 } 11473 11474 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11475 SourceLocation CC, QualType T); 11476 11477 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11478 SourceLocation CC, bool &ICContext) { 11479 E = E->IgnoreParenImpCasts(); 11480 11481 if (isa<ConditionalOperator>(E)) 11482 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11483 11484 AnalyzeImplicitConversions(S, E, CC); 11485 if (E->getType() != T) 11486 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11487 } 11488 11489 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11490 SourceLocation CC, QualType T) { 11491 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11492 11493 bool Suspicious = false; 11494 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11495 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11496 11497 // If -Wconversion would have warned about either of the candidates 11498 // for a signedness conversion to the context type... 11499 if (!Suspicious) return; 11500 11501 // ...but it's currently ignored... 11502 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11503 return; 11504 11505 // ...then check whether it would have warned about either of the 11506 // candidates for a signedness conversion to the condition type. 11507 if (E->getType() == T) return; 11508 11509 Suspicious = false; 11510 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11511 E->getType(), CC, &Suspicious); 11512 if (!Suspicious) 11513 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11514 E->getType(), CC, &Suspicious); 11515 } 11516 11517 /// Check conversion of given expression to boolean. 11518 /// Input argument E is a logical expression. 11519 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11520 if (S.getLangOpts().Bool) 11521 return; 11522 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11523 return; 11524 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11525 } 11526 11527 /// AnalyzeImplicitConversions - Find and report any interesting 11528 /// implicit conversions in the given expression. There are a couple 11529 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11530 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11531 SourceLocation CC) { 11532 QualType T = OrigE->getType(); 11533 Expr *E = OrigE->IgnoreParenImpCasts(); 11534 11535 if (E->isTypeDependent() || E->isValueDependent()) 11536 return; 11537 11538 // For conditional operators, we analyze the arguments as if they 11539 // were being fed directly into the output. 11540 if (isa<ConditionalOperator>(E)) { 11541 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11542 CheckConditionalOperator(S, CO, CC, T); 11543 return; 11544 } 11545 11546 // Check implicit argument conversions for function calls. 11547 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11548 CheckImplicitArgumentConversions(S, Call, CC); 11549 11550 // Go ahead and check any implicit conversions we might have skipped. 11551 // The non-canonical typecheck is just an optimization; 11552 // CheckImplicitConversion will filter out dead implicit conversions. 11553 if (E->getType() != T) 11554 CheckImplicitConversion(S, E, T, CC); 11555 11556 // Now continue drilling into this expression. 11557 11558 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11559 // The bound subexpressions in a PseudoObjectExpr are not reachable 11560 // as transitive children. 11561 // FIXME: Use a more uniform representation for this. 11562 for (auto *SE : POE->semantics()) 11563 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11564 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11565 } 11566 11567 // Skip past explicit casts. 11568 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11569 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11570 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11571 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11572 return AnalyzeImplicitConversions(S, E, CC); 11573 } 11574 11575 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11576 // Do a somewhat different check with comparison operators. 11577 if (BO->isComparisonOp()) 11578 return AnalyzeComparison(S, BO); 11579 11580 // And with simple assignments. 11581 if (BO->getOpcode() == BO_Assign) 11582 return AnalyzeAssignment(S, BO); 11583 // And with compound assignments. 11584 if (BO->isAssignmentOp()) 11585 return AnalyzeCompoundAssignment(S, BO); 11586 } 11587 11588 // These break the otherwise-useful invariant below. Fortunately, 11589 // we don't really need to recurse into them, because any internal 11590 // expressions should have been analyzed already when they were 11591 // built into statements. 11592 if (isa<StmtExpr>(E)) return; 11593 11594 // Don't descend into unevaluated contexts. 11595 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11596 11597 // Now just recurse over the expression's children. 11598 CC = E->getExprLoc(); 11599 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11600 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11601 for (Stmt *SubStmt : E->children()) { 11602 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11603 if (!ChildExpr) 11604 continue; 11605 11606 if (IsLogicalAndOperator && 11607 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11608 // Ignore checking string literals that are in logical and operators. 11609 // This is a common pattern for asserts. 11610 continue; 11611 AnalyzeImplicitConversions(S, ChildExpr, CC); 11612 } 11613 11614 if (BO && BO->isLogicalOp()) { 11615 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11616 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11617 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11618 11619 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11620 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11621 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11622 } 11623 11624 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11625 if (U->getOpcode() == UO_LNot) { 11626 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11627 } else if (U->getOpcode() != UO_AddrOf) { 11628 if (U->getSubExpr()->getType()->isAtomicType()) 11629 S.Diag(U->getSubExpr()->getBeginLoc(), 11630 diag::warn_atomic_implicit_seq_cst); 11631 } 11632 } 11633 } 11634 11635 /// Diagnose integer type and any valid implicit conversion to it. 11636 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11637 // Taking into account implicit conversions, 11638 // allow any integer. 11639 if (!E->getType()->isIntegerType()) { 11640 S.Diag(E->getBeginLoc(), 11641 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11642 return true; 11643 } 11644 // Potentially emit standard warnings for implicit conversions if enabled 11645 // using -Wconversion. 11646 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11647 return false; 11648 } 11649 11650 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11651 // Returns true when emitting a warning about taking the address of a reference. 11652 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11653 const PartialDiagnostic &PD) { 11654 E = E->IgnoreParenImpCasts(); 11655 11656 const FunctionDecl *FD = nullptr; 11657 11658 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11659 if (!DRE->getDecl()->getType()->isReferenceType()) 11660 return false; 11661 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11662 if (!M->getMemberDecl()->getType()->isReferenceType()) 11663 return false; 11664 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11665 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11666 return false; 11667 FD = Call->getDirectCallee(); 11668 } else { 11669 return false; 11670 } 11671 11672 SemaRef.Diag(E->getExprLoc(), PD); 11673 11674 // If possible, point to location of function. 11675 if (FD) { 11676 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11677 } 11678 11679 return true; 11680 } 11681 11682 // Returns true if the SourceLocation is expanded from any macro body. 11683 // Returns false if the SourceLocation is invalid, is from not in a macro 11684 // expansion, or is from expanded from a top-level macro argument. 11685 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11686 if (Loc.isInvalid()) 11687 return false; 11688 11689 while (Loc.isMacroID()) { 11690 if (SM.isMacroBodyExpansion(Loc)) 11691 return true; 11692 Loc = SM.getImmediateMacroCallerLoc(Loc); 11693 } 11694 11695 return false; 11696 } 11697 11698 /// Diagnose pointers that are always non-null. 11699 /// \param E the expression containing the pointer 11700 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11701 /// compared to a null pointer 11702 /// \param IsEqual True when the comparison is equal to a null pointer 11703 /// \param Range Extra SourceRange to highlight in the diagnostic 11704 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11705 Expr::NullPointerConstantKind NullKind, 11706 bool IsEqual, SourceRange Range) { 11707 if (!E) 11708 return; 11709 11710 // Don't warn inside macros. 11711 if (E->getExprLoc().isMacroID()) { 11712 const SourceManager &SM = getSourceManager(); 11713 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11714 IsInAnyMacroBody(SM, Range.getBegin())) 11715 return; 11716 } 11717 E = E->IgnoreImpCasts(); 11718 11719 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11720 11721 if (isa<CXXThisExpr>(E)) { 11722 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11723 : diag::warn_this_bool_conversion; 11724 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11725 return; 11726 } 11727 11728 bool IsAddressOf = false; 11729 11730 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11731 if (UO->getOpcode() != UO_AddrOf) 11732 return; 11733 IsAddressOf = true; 11734 E = UO->getSubExpr(); 11735 } 11736 11737 if (IsAddressOf) { 11738 unsigned DiagID = IsCompare 11739 ? diag::warn_address_of_reference_null_compare 11740 : diag::warn_address_of_reference_bool_conversion; 11741 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11742 << IsEqual; 11743 if (CheckForReference(*this, E, PD)) { 11744 return; 11745 } 11746 } 11747 11748 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11749 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11750 std::string Str; 11751 llvm::raw_string_ostream S(Str); 11752 E->printPretty(S, nullptr, getPrintingPolicy()); 11753 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11754 : diag::warn_cast_nonnull_to_bool; 11755 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11756 << E->getSourceRange() << Range << IsEqual; 11757 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11758 }; 11759 11760 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11761 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11762 if (auto *Callee = Call->getDirectCallee()) { 11763 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11764 ComplainAboutNonnullParamOrCall(A); 11765 return; 11766 } 11767 } 11768 } 11769 11770 // Expect to find a single Decl. Skip anything more complicated. 11771 ValueDecl *D = nullptr; 11772 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11773 D = R->getDecl(); 11774 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11775 D = M->getMemberDecl(); 11776 } 11777 11778 // Weak Decls can be null. 11779 if (!D || D->isWeak()) 11780 return; 11781 11782 // Check for parameter decl with nonnull attribute 11783 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11784 if (getCurFunction() && 11785 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11786 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11787 ComplainAboutNonnullParamOrCall(A); 11788 return; 11789 } 11790 11791 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11792 // Skip function template not specialized yet. 11793 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11794 return; 11795 auto ParamIter = llvm::find(FD->parameters(), PV); 11796 assert(ParamIter != FD->param_end()); 11797 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11798 11799 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11800 if (!NonNull->args_size()) { 11801 ComplainAboutNonnullParamOrCall(NonNull); 11802 return; 11803 } 11804 11805 for (const ParamIdx &ArgNo : NonNull->args()) { 11806 if (ArgNo.getASTIndex() == ParamNo) { 11807 ComplainAboutNonnullParamOrCall(NonNull); 11808 return; 11809 } 11810 } 11811 } 11812 } 11813 } 11814 } 11815 11816 QualType T = D->getType(); 11817 const bool IsArray = T->isArrayType(); 11818 const bool IsFunction = T->isFunctionType(); 11819 11820 // Address of function is used to silence the function warning. 11821 if (IsAddressOf && IsFunction) { 11822 return; 11823 } 11824 11825 // Found nothing. 11826 if (!IsAddressOf && !IsFunction && !IsArray) 11827 return; 11828 11829 // Pretty print the expression for the diagnostic. 11830 std::string Str; 11831 llvm::raw_string_ostream S(Str); 11832 E->printPretty(S, nullptr, getPrintingPolicy()); 11833 11834 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11835 : diag::warn_impcast_pointer_to_bool; 11836 enum { 11837 AddressOf, 11838 FunctionPointer, 11839 ArrayPointer 11840 } DiagType; 11841 if (IsAddressOf) 11842 DiagType = AddressOf; 11843 else if (IsFunction) 11844 DiagType = FunctionPointer; 11845 else if (IsArray) 11846 DiagType = ArrayPointer; 11847 else 11848 llvm_unreachable("Could not determine diagnostic."); 11849 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11850 << Range << IsEqual; 11851 11852 if (!IsFunction) 11853 return; 11854 11855 // Suggest '&' to silence the function warning. 11856 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11857 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11858 11859 // Check to see if '()' fixit should be emitted. 11860 QualType ReturnType; 11861 UnresolvedSet<4> NonTemplateOverloads; 11862 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11863 if (ReturnType.isNull()) 11864 return; 11865 11866 if (IsCompare) { 11867 // There are two cases here. If there is null constant, the only suggest 11868 // for a pointer return type. If the null is 0, then suggest if the return 11869 // type is a pointer or an integer type. 11870 if (!ReturnType->isPointerType()) { 11871 if (NullKind == Expr::NPCK_ZeroExpression || 11872 NullKind == Expr::NPCK_ZeroLiteral) { 11873 if (!ReturnType->isIntegerType()) 11874 return; 11875 } else { 11876 return; 11877 } 11878 } 11879 } else { // !IsCompare 11880 // For function to bool, only suggest if the function pointer has bool 11881 // return type. 11882 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11883 return; 11884 } 11885 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11886 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11887 } 11888 11889 /// Diagnoses "dangerous" implicit conversions within the given 11890 /// expression (which is a full expression). Implements -Wconversion 11891 /// and -Wsign-compare. 11892 /// 11893 /// \param CC the "context" location of the implicit conversion, i.e. 11894 /// the most location of the syntactic entity requiring the implicit 11895 /// conversion 11896 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11897 // Don't diagnose in unevaluated contexts. 11898 if (isUnevaluatedContext()) 11899 return; 11900 11901 // Don't diagnose for value- or type-dependent expressions. 11902 if (E->isTypeDependent() || E->isValueDependent()) 11903 return; 11904 11905 // Check for array bounds violations in cases where the check isn't triggered 11906 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11907 // ArraySubscriptExpr is on the RHS of a variable initialization. 11908 CheckArrayAccess(E); 11909 11910 // This is not the right CC for (e.g.) a variable initialization. 11911 AnalyzeImplicitConversions(*this, E, CC); 11912 } 11913 11914 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11915 /// Input argument E is a logical expression. 11916 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11917 ::CheckBoolLikeConversion(*this, E, CC); 11918 } 11919 11920 /// Diagnose when expression is an integer constant expression and its evaluation 11921 /// results in integer overflow 11922 void Sema::CheckForIntOverflow (Expr *E) { 11923 // Use a work list to deal with nested struct initializers. 11924 SmallVector<Expr *, 2> Exprs(1, E); 11925 11926 do { 11927 Expr *OriginalE = Exprs.pop_back_val(); 11928 Expr *E = OriginalE->IgnoreParenCasts(); 11929 11930 if (isa<BinaryOperator>(E)) { 11931 E->EvaluateForOverflow(Context); 11932 continue; 11933 } 11934 11935 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11936 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11937 else if (isa<ObjCBoxedExpr>(OriginalE)) 11938 E->EvaluateForOverflow(Context); 11939 else if (auto Call = dyn_cast<CallExpr>(E)) 11940 Exprs.append(Call->arg_begin(), Call->arg_end()); 11941 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11942 Exprs.append(Message->arg_begin(), Message->arg_end()); 11943 } while (!Exprs.empty()); 11944 } 11945 11946 namespace { 11947 11948 /// Visitor for expressions which looks for unsequenced operations on the 11949 /// same object. 11950 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11951 using Base = EvaluatedExprVisitor<SequenceChecker>; 11952 11953 /// A tree of sequenced regions within an expression. Two regions are 11954 /// unsequenced if one is an ancestor or a descendent of the other. When we 11955 /// finish processing an expression with sequencing, such as a comma 11956 /// expression, we fold its tree nodes into its parent, since they are 11957 /// unsequenced with respect to nodes we will visit later. 11958 class SequenceTree { 11959 struct Value { 11960 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11961 unsigned Parent : 31; 11962 unsigned Merged : 1; 11963 }; 11964 SmallVector<Value, 8> Values; 11965 11966 public: 11967 /// A region within an expression which may be sequenced with respect 11968 /// to some other region. 11969 class Seq { 11970 friend class SequenceTree; 11971 11972 unsigned Index; 11973 11974 explicit Seq(unsigned N) : Index(N) {} 11975 11976 public: 11977 Seq() : Index(0) {} 11978 }; 11979 11980 SequenceTree() { Values.push_back(Value(0)); } 11981 Seq root() const { return Seq(0); } 11982 11983 /// Create a new sequence of operations, which is an unsequenced 11984 /// subset of \p Parent. This sequence of operations is sequenced with 11985 /// respect to other children of \p Parent. 11986 Seq allocate(Seq Parent) { 11987 Values.push_back(Value(Parent.Index)); 11988 return Seq(Values.size() - 1); 11989 } 11990 11991 /// Merge a sequence of operations into its parent. 11992 void merge(Seq S) { 11993 Values[S.Index].Merged = true; 11994 } 11995 11996 /// Determine whether two operations are unsequenced. This operation 11997 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11998 /// should have been merged into its parent as appropriate. 11999 bool isUnsequenced(Seq Cur, Seq Old) { 12000 unsigned C = representative(Cur.Index); 12001 unsigned Target = representative(Old.Index); 12002 while (C >= Target) { 12003 if (C == Target) 12004 return true; 12005 C = Values[C].Parent; 12006 } 12007 return false; 12008 } 12009 12010 private: 12011 /// Pick a representative for a sequence. 12012 unsigned representative(unsigned K) { 12013 if (Values[K].Merged) 12014 // Perform path compression as we go. 12015 return Values[K].Parent = representative(Values[K].Parent); 12016 return K; 12017 } 12018 }; 12019 12020 /// An object for which we can track unsequenced uses. 12021 using Object = NamedDecl *; 12022 12023 /// Different flavors of object usage which we track. We only track the 12024 /// least-sequenced usage of each kind. 12025 enum UsageKind { 12026 /// A read of an object. Multiple unsequenced reads are OK. 12027 UK_Use, 12028 12029 /// A modification of an object which is sequenced before the value 12030 /// computation of the expression, such as ++n in C++. 12031 UK_ModAsValue, 12032 12033 /// A modification of an object which is not sequenced before the value 12034 /// computation of the expression, such as n++. 12035 UK_ModAsSideEffect, 12036 12037 UK_Count = UK_ModAsSideEffect + 1 12038 }; 12039 12040 struct Usage { 12041 Expr *Use; 12042 SequenceTree::Seq Seq; 12043 12044 Usage() : Use(nullptr), Seq() {} 12045 }; 12046 12047 struct UsageInfo { 12048 Usage Uses[UK_Count]; 12049 12050 /// Have we issued a diagnostic for this variable already? 12051 bool Diagnosed; 12052 12053 UsageInfo() : Uses(), Diagnosed(false) {} 12054 }; 12055 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12056 12057 Sema &SemaRef; 12058 12059 /// Sequenced regions within the expression. 12060 SequenceTree Tree; 12061 12062 /// Declaration modifications and references which we have seen. 12063 UsageInfoMap UsageMap; 12064 12065 /// The region we are currently within. 12066 SequenceTree::Seq Region; 12067 12068 /// Filled in with declarations which were modified as a side-effect 12069 /// (that is, post-increment operations). 12070 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12071 12072 /// Expressions to check later. We defer checking these to reduce 12073 /// stack usage. 12074 SmallVectorImpl<Expr *> &WorkList; 12075 12076 /// RAII object wrapping the visitation of a sequenced subexpression of an 12077 /// expression. At the end of this process, the side-effects of the evaluation 12078 /// become sequenced with respect to the value computation of the result, so 12079 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12080 /// UK_ModAsValue. 12081 struct SequencedSubexpression { 12082 SequencedSubexpression(SequenceChecker &Self) 12083 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12084 Self.ModAsSideEffect = &ModAsSideEffect; 12085 } 12086 12087 ~SequencedSubexpression() { 12088 for (auto &M : llvm::reverse(ModAsSideEffect)) { 12089 UsageInfo &U = Self.UsageMap[M.first]; 12090 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 12091 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 12092 SideEffectUsage = M.second; 12093 } 12094 Self.ModAsSideEffect = OldModAsSideEffect; 12095 } 12096 12097 SequenceChecker &Self; 12098 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12099 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12100 }; 12101 12102 /// RAII object wrapping the visitation of a subexpression which we might 12103 /// choose to evaluate as a constant. If any subexpression is evaluated and 12104 /// found to be non-constant, this allows us to suppress the evaluation of 12105 /// the outer expression. 12106 class EvaluationTracker { 12107 public: 12108 EvaluationTracker(SequenceChecker &Self) 12109 : Self(Self), Prev(Self.EvalTracker) { 12110 Self.EvalTracker = this; 12111 } 12112 12113 ~EvaluationTracker() { 12114 Self.EvalTracker = Prev; 12115 if (Prev) 12116 Prev->EvalOK &= EvalOK; 12117 } 12118 12119 bool evaluate(const Expr *E, bool &Result) { 12120 if (!EvalOK || E->isValueDependent()) 12121 return false; 12122 EvalOK = E->EvaluateAsBooleanCondition( 12123 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12124 return EvalOK; 12125 } 12126 12127 private: 12128 SequenceChecker &Self; 12129 EvaluationTracker *Prev; 12130 bool EvalOK = true; 12131 } *EvalTracker = nullptr; 12132 12133 /// Find the object which is produced by the specified expression, 12134 /// if any. 12135 Object getObject(Expr *E, bool Mod) const { 12136 E = E->IgnoreParenCasts(); 12137 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12138 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12139 return getObject(UO->getSubExpr(), Mod); 12140 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12141 if (BO->getOpcode() == BO_Comma) 12142 return getObject(BO->getRHS(), Mod); 12143 if (Mod && BO->isAssignmentOp()) 12144 return getObject(BO->getLHS(), Mod); 12145 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12146 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12147 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12148 return ME->getMemberDecl(); 12149 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12150 // FIXME: If this is a reference, map through to its value. 12151 return DRE->getDecl(); 12152 return nullptr; 12153 } 12154 12155 /// Note that an object was modified or used by an expression. 12156 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 12157 Usage &U = UI.Uses[UK]; 12158 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 12159 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12160 ModAsSideEffect->push_back(std::make_pair(O, U)); 12161 U.Use = Ref; 12162 U.Seq = Region; 12163 } 12164 } 12165 12166 /// Check whether a modification or use conflicts with a prior usage. 12167 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 12168 bool IsModMod) { 12169 if (UI.Diagnosed) 12170 return; 12171 12172 const Usage &U = UI.Uses[OtherKind]; 12173 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 12174 return; 12175 12176 Expr *Mod = U.Use; 12177 Expr *ModOrUse = Ref; 12178 if (OtherKind == UK_Use) 12179 std::swap(Mod, ModOrUse); 12180 12181 SemaRef.DiagRuntimeBehavior( 12182 Mod->getExprLoc(), {Mod, ModOrUse}, 12183 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12184 : diag::warn_unsequenced_mod_use) 12185 << O << SourceRange(ModOrUse->getExprLoc())); 12186 UI.Diagnosed = true; 12187 } 12188 12189 void notePreUse(Object O, Expr *Use) { 12190 UsageInfo &U = UsageMap[O]; 12191 // Uses conflict with other modifications. 12192 checkUsage(O, U, Use, UK_ModAsValue, false); 12193 } 12194 12195 void notePostUse(Object O, Expr *Use) { 12196 UsageInfo &U = UsageMap[O]; 12197 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 12198 addUsage(U, O, Use, UK_Use); 12199 } 12200 12201 void notePreMod(Object O, Expr *Mod) { 12202 UsageInfo &U = UsageMap[O]; 12203 // Modifications conflict with other modifications and with uses. 12204 checkUsage(O, U, Mod, UK_ModAsValue, true); 12205 checkUsage(O, U, Mod, UK_Use, false); 12206 } 12207 12208 void notePostMod(Object O, Expr *Use, UsageKind UK) { 12209 UsageInfo &U = UsageMap[O]; 12210 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 12211 addUsage(U, O, Use, UK); 12212 } 12213 12214 public: 12215 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 12216 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12217 Visit(E); 12218 } 12219 12220 void VisitStmt(Stmt *S) { 12221 // Skip all statements which aren't expressions for now. 12222 } 12223 12224 void VisitExpr(Expr *E) { 12225 // By default, just recurse to evaluated subexpressions. 12226 Base::VisitStmt(E); 12227 } 12228 12229 void VisitCastExpr(CastExpr *E) { 12230 Object O = Object(); 12231 if (E->getCastKind() == CK_LValueToRValue) 12232 O = getObject(E->getSubExpr(), false); 12233 12234 if (O) 12235 notePreUse(O, E); 12236 VisitExpr(E); 12237 if (O) 12238 notePostUse(O, E); 12239 } 12240 12241 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) { 12242 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12243 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12244 SequenceTree::Seq OldRegion = Region; 12245 12246 { 12247 SequencedSubexpression SeqBefore(*this); 12248 Region = BeforeRegion; 12249 Visit(SequencedBefore); 12250 } 12251 12252 Region = AfterRegion; 12253 Visit(SequencedAfter); 12254 12255 Region = OldRegion; 12256 12257 Tree.merge(BeforeRegion); 12258 Tree.merge(AfterRegion); 12259 } 12260 12261 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) { 12262 // C++17 [expr.sub]p1: 12263 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12264 // expression E1 is sequenced before the expression E2. 12265 if (SemaRef.getLangOpts().CPlusPlus17) 12266 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12267 else 12268 Base::VisitStmt(ASE); 12269 } 12270 12271 void VisitBinComma(BinaryOperator *BO) { 12272 // C++11 [expr.comma]p1: 12273 // Every value computation and side effect associated with the left 12274 // expression is sequenced before every value computation and side 12275 // effect associated with the right expression. 12276 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12277 } 12278 12279 void VisitBinAssign(BinaryOperator *BO) { 12280 // The modification is sequenced after the value computation of the LHS 12281 // and RHS, so check it before inspecting the operands and update the 12282 // map afterwards. 12283 Object O = getObject(BO->getLHS(), true); 12284 if (!O) 12285 return VisitExpr(BO); 12286 12287 notePreMod(O, BO); 12288 12289 // C++11 [expr.ass]p7: 12290 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 12291 // only once. 12292 // 12293 // Therefore, for a compound assignment operator, O is considered used 12294 // everywhere except within the evaluation of E1 itself. 12295 if (isa<CompoundAssignOperator>(BO)) 12296 notePreUse(O, BO); 12297 12298 Visit(BO->getLHS()); 12299 12300 if (isa<CompoundAssignOperator>(BO)) 12301 notePostUse(O, BO); 12302 12303 Visit(BO->getRHS()); 12304 12305 // C++11 [expr.ass]p1: 12306 // the assignment is sequenced [...] before the value computation of the 12307 // assignment expression. 12308 // C11 6.5.16/3 has no such rule. 12309 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12310 : UK_ModAsSideEffect); 12311 } 12312 12313 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 12314 VisitBinAssign(CAO); 12315 } 12316 12317 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12318 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12319 void VisitUnaryPreIncDec(UnaryOperator *UO) { 12320 Object O = getObject(UO->getSubExpr(), true); 12321 if (!O) 12322 return VisitExpr(UO); 12323 12324 notePreMod(O, UO); 12325 Visit(UO->getSubExpr()); 12326 // C++11 [expr.pre.incr]p1: 12327 // the expression ++x is equivalent to x+=1 12328 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12329 : UK_ModAsSideEffect); 12330 } 12331 12332 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12333 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12334 void VisitUnaryPostIncDec(UnaryOperator *UO) { 12335 Object O = getObject(UO->getSubExpr(), true); 12336 if (!O) 12337 return VisitExpr(UO); 12338 12339 notePreMod(O, UO); 12340 Visit(UO->getSubExpr()); 12341 notePostMod(O, UO, UK_ModAsSideEffect); 12342 } 12343 12344 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 12345 void VisitBinLOr(BinaryOperator *BO) { 12346 // The side-effects of the LHS of an '&&' are sequenced before the 12347 // value computation of the RHS, and hence before the value computation 12348 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 12349 // as if they were unconditionally sequenced. 12350 EvaluationTracker Eval(*this); 12351 { 12352 SequencedSubexpression Sequenced(*this); 12353 Visit(BO->getLHS()); 12354 } 12355 12356 bool Result; 12357 if (Eval.evaluate(BO->getLHS(), Result)) { 12358 if (!Result) 12359 Visit(BO->getRHS()); 12360 } else { 12361 // Check for unsequenced operations in the RHS, treating it as an 12362 // entirely separate evaluation. 12363 // 12364 // FIXME: If there are operations in the RHS which are unsequenced 12365 // with respect to operations outside the RHS, and those operations 12366 // are unconditionally evaluated, diagnose them. 12367 WorkList.push_back(BO->getRHS()); 12368 } 12369 } 12370 void VisitBinLAnd(BinaryOperator *BO) { 12371 EvaluationTracker Eval(*this); 12372 { 12373 SequencedSubexpression Sequenced(*this); 12374 Visit(BO->getLHS()); 12375 } 12376 12377 bool Result; 12378 if (Eval.evaluate(BO->getLHS(), Result)) { 12379 if (Result) 12380 Visit(BO->getRHS()); 12381 } else { 12382 WorkList.push_back(BO->getRHS()); 12383 } 12384 } 12385 12386 // Only visit the condition, unless we can be sure which subexpression will 12387 // be chosen. 12388 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 12389 EvaluationTracker Eval(*this); 12390 { 12391 SequencedSubexpression Sequenced(*this); 12392 Visit(CO->getCond()); 12393 } 12394 12395 bool Result; 12396 if (Eval.evaluate(CO->getCond(), Result)) 12397 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 12398 else { 12399 WorkList.push_back(CO->getTrueExpr()); 12400 WorkList.push_back(CO->getFalseExpr()); 12401 } 12402 } 12403 12404 void VisitCallExpr(CallExpr *CE) { 12405 // C++11 [intro.execution]p15: 12406 // When calling a function [...], every value computation and side effect 12407 // associated with any argument expression, or with the postfix expression 12408 // designating the called function, is sequenced before execution of every 12409 // expression or statement in the body of the function [and thus before 12410 // the value computation of its result]. 12411 SequencedSubexpression Sequenced(*this); 12412 Base::VisitCallExpr(CE); 12413 12414 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12415 } 12416 12417 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 12418 // This is a call, so all subexpressions are sequenced before the result. 12419 SequencedSubexpression Sequenced(*this); 12420 12421 if (!CCE->isListInitialization()) 12422 return VisitExpr(CCE); 12423 12424 // In C++11, list initializations are sequenced. 12425 SmallVector<SequenceTree::Seq, 32> Elts; 12426 SequenceTree::Seq Parent = Region; 12427 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12428 E = CCE->arg_end(); 12429 I != E; ++I) { 12430 Region = Tree.allocate(Parent); 12431 Elts.push_back(Region); 12432 Visit(*I); 12433 } 12434 12435 // Forget that the initializers are sequenced. 12436 Region = Parent; 12437 for (unsigned I = 0; I < Elts.size(); ++I) 12438 Tree.merge(Elts[I]); 12439 } 12440 12441 void VisitInitListExpr(InitListExpr *ILE) { 12442 if (!SemaRef.getLangOpts().CPlusPlus11) 12443 return VisitExpr(ILE); 12444 12445 // In C++11, list initializations are sequenced. 12446 SmallVector<SequenceTree::Seq, 32> Elts; 12447 SequenceTree::Seq Parent = Region; 12448 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12449 Expr *E = ILE->getInit(I); 12450 if (!E) continue; 12451 Region = Tree.allocate(Parent); 12452 Elts.push_back(Region); 12453 Visit(E); 12454 } 12455 12456 // Forget that the initializers are sequenced. 12457 Region = Parent; 12458 for (unsigned I = 0; I < Elts.size(); ++I) 12459 Tree.merge(Elts[I]); 12460 } 12461 }; 12462 12463 } // namespace 12464 12465 void Sema::CheckUnsequencedOperations(Expr *E) { 12466 SmallVector<Expr *, 8> WorkList; 12467 WorkList.push_back(E); 12468 while (!WorkList.empty()) { 12469 Expr *Item = WorkList.pop_back_val(); 12470 SequenceChecker(*this, Item, WorkList); 12471 } 12472 } 12473 12474 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12475 bool IsConstexpr) { 12476 llvm::SaveAndRestore<bool> ConstantContext( 12477 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12478 CheckImplicitConversions(E, CheckLoc); 12479 if (!E->isInstantiationDependent()) 12480 CheckUnsequencedOperations(E); 12481 if (!IsConstexpr && !E->isValueDependent()) 12482 CheckForIntOverflow(E); 12483 DiagnoseMisalignedMembers(); 12484 } 12485 12486 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12487 FieldDecl *BitField, 12488 Expr *Init) { 12489 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12490 } 12491 12492 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12493 SourceLocation Loc) { 12494 if (!PType->isVariablyModifiedType()) 12495 return; 12496 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12497 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12498 return; 12499 } 12500 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12501 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12502 return; 12503 } 12504 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12505 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12506 return; 12507 } 12508 12509 const ArrayType *AT = S.Context.getAsArrayType(PType); 12510 if (!AT) 12511 return; 12512 12513 if (AT->getSizeModifier() != ArrayType::Star) { 12514 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12515 return; 12516 } 12517 12518 S.Diag(Loc, diag::err_array_star_in_function_definition); 12519 } 12520 12521 /// CheckParmsForFunctionDef - Check that the parameters of the given 12522 /// function are appropriate for the definition of a function. This 12523 /// takes care of any checks that cannot be performed on the 12524 /// declaration itself, e.g., that the types of each of the function 12525 /// parameters are complete. 12526 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12527 bool CheckParameterNames) { 12528 bool HasInvalidParm = false; 12529 for (ParmVarDecl *Param : Parameters) { 12530 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12531 // function declarator that is part of a function definition of 12532 // that function shall not have incomplete type. 12533 // 12534 // This is also C++ [dcl.fct]p6. 12535 if (!Param->isInvalidDecl() && 12536 RequireCompleteType(Param->getLocation(), Param->getType(), 12537 diag::err_typecheck_decl_incomplete_type)) { 12538 Param->setInvalidDecl(); 12539 HasInvalidParm = true; 12540 } 12541 12542 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12543 // declaration of each parameter shall include an identifier. 12544 if (CheckParameterNames && 12545 Param->getIdentifier() == nullptr && 12546 !Param->isImplicit() && 12547 !getLangOpts().CPlusPlus) 12548 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12549 12550 // C99 6.7.5.3p12: 12551 // If the function declarator is not part of a definition of that 12552 // function, parameters may have incomplete type and may use the [*] 12553 // notation in their sequences of declarator specifiers to specify 12554 // variable length array types. 12555 QualType PType = Param->getOriginalType(); 12556 // FIXME: This diagnostic should point the '[*]' if source-location 12557 // information is added for it. 12558 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12559 12560 // If the parameter is a c++ class type and it has to be destructed in the 12561 // callee function, declare the destructor so that it can be called by the 12562 // callee function. Do not perform any direct access check on the dtor here. 12563 if (!Param->isInvalidDecl()) { 12564 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12565 if (!ClassDecl->isInvalidDecl() && 12566 !ClassDecl->hasIrrelevantDestructor() && 12567 !ClassDecl->isDependentContext() && 12568 ClassDecl->isParamDestroyedInCallee()) { 12569 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12570 MarkFunctionReferenced(Param->getLocation(), Destructor); 12571 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12572 } 12573 } 12574 } 12575 12576 // Parameters with the pass_object_size attribute only need to be marked 12577 // constant at function definitions. Because we lack information about 12578 // whether we're on a declaration or definition when we're instantiating the 12579 // attribute, we need to check for constness here. 12580 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12581 if (!Param->getType().isConstQualified()) 12582 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12583 << Attr->getSpelling() << 1; 12584 12585 // Check for parameter names shadowing fields from the class. 12586 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12587 // The owning context for the parameter should be the function, but we 12588 // want to see if this function's declaration context is a record. 12589 DeclContext *DC = Param->getDeclContext(); 12590 if (DC && DC->isFunctionOrMethod()) { 12591 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12592 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12593 RD, /*DeclIsField*/ false); 12594 } 12595 } 12596 } 12597 12598 return HasInvalidParm; 12599 } 12600 12601 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12602 /// or MemberExpr. 12603 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12604 ASTContext &Context) { 12605 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12606 return Context.getDeclAlign(DRE->getDecl()); 12607 12608 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12609 return Context.getDeclAlign(ME->getMemberDecl()); 12610 12611 return TypeAlign; 12612 } 12613 12614 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12615 /// pointer cast increases the alignment requirements. 12616 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12617 // This is actually a lot of work to potentially be doing on every 12618 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12619 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12620 return; 12621 12622 // Ignore dependent types. 12623 if (T->isDependentType() || Op->getType()->isDependentType()) 12624 return; 12625 12626 // Require that the destination be a pointer type. 12627 const PointerType *DestPtr = T->getAs<PointerType>(); 12628 if (!DestPtr) return; 12629 12630 // If the destination has alignment 1, we're done. 12631 QualType DestPointee = DestPtr->getPointeeType(); 12632 if (DestPointee->isIncompleteType()) return; 12633 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12634 if (DestAlign.isOne()) return; 12635 12636 // Require that the source be a pointer type. 12637 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12638 if (!SrcPtr) return; 12639 QualType SrcPointee = SrcPtr->getPointeeType(); 12640 12641 // Whitelist casts from cv void*. We already implicitly 12642 // whitelisted casts to cv void*, since they have alignment 1. 12643 // Also whitelist casts involving incomplete types, which implicitly 12644 // includes 'void'. 12645 if (SrcPointee->isIncompleteType()) return; 12646 12647 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12648 12649 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12650 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12651 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12652 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12653 if (UO->getOpcode() == UO_AddrOf) 12654 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12655 } 12656 12657 if (SrcAlign >= DestAlign) return; 12658 12659 Diag(TRange.getBegin(), diag::warn_cast_align) 12660 << Op->getType() << T 12661 << static_cast<unsigned>(SrcAlign.getQuantity()) 12662 << static_cast<unsigned>(DestAlign.getQuantity()) 12663 << TRange << Op->getSourceRange(); 12664 } 12665 12666 /// Check whether this array fits the idiom of a size-one tail padded 12667 /// array member of a struct. 12668 /// 12669 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12670 /// commonly used to emulate flexible arrays in C89 code. 12671 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12672 const NamedDecl *ND) { 12673 if (Size != 1 || !ND) return false; 12674 12675 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12676 if (!FD) return false; 12677 12678 // Don't consider sizes resulting from macro expansions or template argument 12679 // substitution to form C89 tail-padded arrays. 12680 12681 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12682 while (TInfo) { 12683 TypeLoc TL = TInfo->getTypeLoc(); 12684 // Look through typedefs. 12685 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12686 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12687 TInfo = TDL->getTypeSourceInfo(); 12688 continue; 12689 } 12690 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12691 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12692 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12693 return false; 12694 } 12695 break; 12696 } 12697 12698 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12699 if (!RD) return false; 12700 if (RD->isUnion()) return false; 12701 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12702 if (!CRD->isStandardLayout()) return false; 12703 } 12704 12705 // See if this is the last field decl in the record. 12706 const Decl *D = FD; 12707 while ((D = D->getNextDeclInContext())) 12708 if (isa<FieldDecl>(D)) 12709 return false; 12710 return true; 12711 } 12712 12713 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12714 const ArraySubscriptExpr *ASE, 12715 bool AllowOnePastEnd, bool IndexNegated) { 12716 // Already diagnosed by the constant evaluator. 12717 if (isConstantEvaluated()) 12718 return; 12719 12720 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12721 if (IndexExpr->isValueDependent()) 12722 return; 12723 12724 const Type *EffectiveType = 12725 BaseExpr->getType()->getPointeeOrArrayElementType(); 12726 BaseExpr = BaseExpr->IgnoreParenCasts(); 12727 const ConstantArrayType *ArrayTy = 12728 Context.getAsConstantArrayType(BaseExpr->getType()); 12729 12730 if (!ArrayTy) 12731 return; 12732 12733 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 12734 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 12735 return; 12736 12737 Expr::EvalResult Result; 12738 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12739 return; 12740 12741 llvm::APSInt index = Result.Val.getInt(); 12742 if (IndexNegated) 12743 index = -index; 12744 12745 const NamedDecl *ND = nullptr; 12746 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12747 ND = DRE->getDecl(); 12748 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12749 ND = ME->getMemberDecl(); 12750 12751 if (index.isUnsigned() || !index.isNegative()) { 12752 // It is possible that the type of the base expression after 12753 // IgnoreParenCasts is incomplete, even though the type of the base 12754 // expression before IgnoreParenCasts is complete (see PR39746 for an 12755 // example). In this case we have no information about whether the array 12756 // access exceeds the array bounds. However we can still diagnose an array 12757 // access which precedes the array bounds. 12758 if (BaseType->isIncompleteType()) 12759 return; 12760 12761 llvm::APInt size = ArrayTy->getSize(); 12762 if (!size.isStrictlyPositive()) 12763 return; 12764 12765 if (BaseType != EffectiveType) { 12766 // Make sure we're comparing apples to apples when comparing index to size 12767 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12768 uint64_t array_typesize = Context.getTypeSize(BaseType); 12769 // Handle ptrarith_typesize being zero, such as when casting to void* 12770 if (!ptrarith_typesize) ptrarith_typesize = 1; 12771 if (ptrarith_typesize != array_typesize) { 12772 // There's a cast to a different size type involved 12773 uint64_t ratio = array_typesize / ptrarith_typesize; 12774 // TODO: Be smarter about handling cases where array_typesize is not a 12775 // multiple of ptrarith_typesize 12776 if (ptrarith_typesize * ratio == array_typesize) 12777 size *= llvm::APInt(size.getBitWidth(), ratio); 12778 } 12779 } 12780 12781 if (size.getBitWidth() > index.getBitWidth()) 12782 index = index.zext(size.getBitWidth()); 12783 else if (size.getBitWidth() < index.getBitWidth()) 12784 size = size.zext(index.getBitWidth()); 12785 12786 // For array subscripting the index must be less than size, but for pointer 12787 // arithmetic also allow the index (offset) to be equal to size since 12788 // computing the next address after the end of the array is legal and 12789 // commonly done e.g. in C++ iterators and range-based for loops. 12790 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12791 return; 12792 12793 // Also don't warn for arrays of size 1 which are members of some 12794 // structure. These are often used to approximate flexible arrays in C89 12795 // code. 12796 if (IsTailPaddedMemberArray(*this, size, ND)) 12797 return; 12798 12799 // Suppress the warning if the subscript expression (as identified by the 12800 // ']' location) and the index expression are both from macro expansions 12801 // within a system header. 12802 if (ASE) { 12803 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12804 ASE->getRBracketLoc()); 12805 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12806 SourceLocation IndexLoc = 12807 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12808 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12809 return; 12810 } 12811 } 12812 12813 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12814 if (ASE) 12815 DiagID = diag::warn_array_index_exceeds_bounds; 12816 12817 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12818 PDiag(DiagID) << index.toString(10, true) 12819 << size.toString(10, true) 12820 << (unsigned)size.getLimitedValue(~0U) 12821 << IndexExpr->getSourceRange()); 12822 } else { 12823 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12824 if (!ASE) { 12825 DiagID = diag::warn_ptr_arith_precedes_bounds; 12826 if (index.isNegative()) index = -index; 12827 } 12828 12829 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12830 PDiag(DiagID) << index.toString(10, true) 12831 << IndexExpr->getSourceRange()); 12832 } 12833 12834 if (!ND) { 12835 // Try harder to find a NamedDecl to point at in the note. 12836 while (const ArraySubscriptExpr *ASE = 12837 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12838 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12839 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12840 ND = DRE->getDecl(); 12841 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12842 ND = ME->getMemberDecl(); 12843 } 12844 12845 if (ND) 12846 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12847 PDiag(diag::note_array_index_out_of_bounds) 12848 << ND->getDeclName()); 12849 } 12850 12851 void Sema::CheckArrayAccess(const Expr *expr) { 12852 int AllowOnePastEnd = 0; 12853 while (expr) { 12854 expr = expr->IgnoreParenImpCasts(); 12855 switch (expr->getStmtClass()) { 12856 case Stmt::ArraySubscriptExprClass: { 12857 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12858 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12859 AllowOnePastEnd > 0); 12860 expr = ASE->getBase(); 12861 break; 12862 } 12863 case Stmt::MemberExprClass: { 12864 expr = cast<MemberExpr>(expr)->getBase(); 12865 break; 12866 } 12867 case Stmt::OMPArraySectionExprClass: { 12868 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12869 if (ASE->getLowerBound()) 12870 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12871 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12872 return; 12873 } 12874 case Stmt::UnaryOperatorClass: { 12875 // Only unwrap the * and & unary operators 12876 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12877 expr = UO->getSubExpr(); 12878 switch (UO->getOpcode()) { 12879 case UO_AddrOf: 12880 AllowOnePastEnd++; 12881 break; 12882 case UO_Deref: 12883 AllowOnePastEnd--; 12884 break; 12885 default: 12886 return; 12887 } 12888 break; 12889 } 12890 case Stmt::ConditionalOperatorClass: { 12891 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12892 if (const Expr *lhs = cond->getLHS()) 12893 CheckArrayAccess(lhs); 12894 if (const Expr *rhs = cond->getRHS()) 12895 CheckArrayAccess(rhs); 12896 return; 12897 } 12898 case Stmt::CXXOperatorCallExprClass: { 12899 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12900 for (const auto *Arg : OCE->arguments()) 12901 CheckArrayAccess(Arg); 12902 return; 12903 } 12904 default: 12905 return; 12906 } 12907 } 12908 } 12909 12910 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12911 12912 namespace { 12913 12914 struct RetainCycleOwner { 12915 VarDecl *Variable = nullptr; 12916 SourceRange Range; 12917 SourceLocation Loc; 12918 bool Indirect = false; 12919 12920 RetainCycleOwner() = default; 12921 12922 void setLocsFrom(Expr *e) { 12923 Loc = e->getExprLoc(); 12924 Range = e->getSourceRange(); 12925 } 12926 }; 12927 12928 } // namespace 12929 12930 /// Consider whether capturing the given variable can possibly lead to 12931 /// a retain cycle. 12932 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12933 // In ARC, it's captured strongly iff the variable has __strong 12934 // lifetime. In MRR, it's captured strongly if the variable is 12935 // __block and has an appropriate type. 12936 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12937 return false; 12938 12939 owner.Variable = var; 12940 if (ref) 12941 owner.setLocsFrom(ref); 12942 return true; 12943 } 12944 12945 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12946 while (true) { 12947 e = e->IgnoreParens(); 12948 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12949 switch (cast->getCastKind()) { 12950 case CK_BitCast: 12951 case CK_LValueBitCast: 12952 case CK_LValueToRValue: 12953 case CK_ARCReclaimReturnedObject: 12954 e = cast->getSubExpr(); 12955 continue; 12956 12957 default: 12958 return false; 12959 } 12960 } 12961 12962 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12963 ObjCIvarDecl *ivar = ref->getDecl(); 12964 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12965 return false; 12966 12967 // Try to find a retain cycle in the base. 12968 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12969 return false; 12970 12971 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12972 owner.Indirect = true; 12973 return true; 12974 } 12975 12976 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12977 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12978 if (!var) return false; 12979 return considerVariable(var, ref, owner); 12980 } 12981 12982 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12983 if (member->isArrow()) return false; 12984 12985 // Don't count this as an indirect ownership. 12986 e = member->getBase(); 12987 continue; 12988 } 12989 12990 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12991 // Only pay attention to pseudo-objects on property references. 12992 ObjCPropertyRefExpr *pre 12993 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12994 ->IgnoreParens()); 12995 if (!pre) return false; 12996 if (pre->isImplicitProperty()) return false; 12997 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12998 if (!property->isRetaining() && 12999 !(property->getPropertyIvarDecl() && 13000 property->getPropertyIvarDecl()->getType() 13001 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13002 return false; 13003 13004 owner.Indirect = true; 13005 if (pre->isSuperReceiver()) { 13006 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13007 if (!owner.Variable) 13008 return false; 13009 owner.Loc = pre->getLocation(); 13010 owner.Range = pre->getSourceRange(); 13011 return true; 13012 } 13013 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13014 ->getSourceExpr()); 13015 continue; 13016 } 13017 13018 // Array ivars? 13019 13020 return false; 13021 } 13022 } 13023 13024 namespace { 13025 13026 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13027 ASTContext &Context; 13028 VarDecl *Variable; 13029 Expr *Capturer = nullptr; 13030 bool VarWillBeReased = false; 13031 13032 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13033 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13034 Context(Context), Variable(variable) {} 13035 13036 void VisitDeclRefExpr(DeclRefExpr *ref) { 13037 if (ref->getDecl() == Variable && !Capturer) 13038 Capturer = ref; 13039 } 13040 13041 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13042 if (Capturer) return; 13043 Visit(ref->getBase()); 13044 if (Capturer && ref->isFreeIvar()) 13045 Capturer = ref; 13046 } 13047 13048 void VisitBlockExpr(BlockExpr *block) { 13049 // Look inside nested blocks 13050 if (block->getBlockDecl()->capturesVariable(Variable)) 13051 Visit(block->getBlockDecl()->getBody()); 13052 } 13053 13054 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13055 if (Capturer) return; 13056 if (OVE->getSourceExpr()) 13057 Visit(OVE->getSourceExpr()); 13058 } 13059 13060 void VisitBinaryOperator(BinaryOperator *BinOp) { 13061 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13062 return; 13063 Expr *LHS = BinOp->getLHS(); 13064 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13065 if (DRE->getDecl() != Variable) 13066 return; 13067 if (Expr *RHS = BinOp->getRHS()) { 13068 RHS = RHS->IgnoreParenCasts(); 13069 llvm::APSInt Value; 13070 VarWillBeReased = 13071 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13072 } 13073 } 13074 } 13075 }; 13076 13077 } // namespace 13078 13079 /// Check whether the given argument is a block which captures a 13080 /// variable. 13081 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13082 assert(owner.Variable && owner.Loc.isValid()); 13083 13084 e = e->IgnoreParenCasts(); 13085 13086 // Look through [^{...} copy] and Block_copy(^{...}). 13087 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13088 Selector Cmd = ME->getSelector(); 13089 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13090 e = ME->getInstanceReceiver(); 13091 if (!e) 13092 return nullptr; 13093 e = e->IgnoreParenCasts(); 13094 } 13095 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13096 if (CE->getNumArgs() == 1) { 13097 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13098 if (Fn) { 13099 const IdentifierInfo *FnI = Fn->getIdentifier(); 13100 if (FnI && FnI->isStr("_Block_copy")) { 13101 e = CE->getArg(0)->IgnoreParenCasts(); 13102 } 13103 } 13104 } 13105 } 13106 13107 BlockExpr *block = dyn_cast<BlockExpr>(e); 13108 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13109 return nullptr; 13110 13111 FindCaptureVisitor visitor(S.Context, owner.Variable); 13112 visitor.Visit(block->getBlockDecl()->getBody()); 13113 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13114 } 13115 13116 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13117 RetainCycleOwner &owner) { 13118 assert(capturer); 13119 assert(owner.Variable && owner.Loc.isValid()); 13120 13121 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13122 << owner.Variable << capturer->getSourceRange(); 13123 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13124 << owner.Indirect << owner.Range; 13125 } 13126 13127 /// Check for a keyword selector that starts with the word 'add' or 13128 /// 'set'. 13129 static bool isSetterLikeSelector(Selector sel) { 13130 if (sel.isUnarySelector()) return false; 13131 13132 StringRef str = sel.getNameForSlot(0); 13133 while (!str.empty() && str.front() == '_') str = str.substr(1); 13134 if (str.startswith("set")) 13135 str = str.substr(3); 13136 else if (str.startswith("add")) { 13137 // Specially whitelist 'addOperationWithBlock:'. 13138 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13139 return false; 13140 str = str.substr(3); 13141 } 13142 else 13143 return false; 13144 13145 if (str.empty()) return true; 13146 return !isLowercase(str.front()); 13147 } 13148 13149 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13150 ObjCMessageExpr *Message) { 13151 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13152 Message->getReceiverInterface(), 13153 NSAPI::ClassId_NSMutableArray); 13154 if (!IsMutableArray) { 13155 return None; 13156 } 13157 13158 Selector Sel = Message->getSelector(); 13159 13160 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13161 S.NSAPIObj->getNSArrayMethodKind(Sel); 13162 if (!MKOpt) { 13163 return None; 13164 } 13165 13166 NSAPI::NSArrayMethodKind MK = *MKOpt; 13167 13168 switch (MK) { 13169 case NSAPI::NSMutableArr_addObject: 13170 case NSAPI::NSMutableArr_insertObjectAtIndex: 13171 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13172 return 0; 13173 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13174 return 1; 13175 13176 default: 13177 return None; 13178 } 13179 13180 return None; 13181 } 13182 13183 static 13184 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13185 ObjCMessageExpr *Message) { 13186 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13187 Message->getReceiverInterface(), 13188 NSAPI::ClassId_NSMutableDictionary); 13189 if (!IsMutableDictionary) { 13190 return None; 13191 } 13192 13193 Selector Sel = Message->getSelector(); 13194 13195 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13196 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13197 if (!MKOpt) { 13198 return None; 13199 } 13200 13201 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13202 13203 switch (MK) { 13204 case NSAPI::NSMutableDict_setObjectForKey: 13205 case NSAPI::NSMutableDict_setValueForKey: 13206 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13207 return 0; 13208 13209 default: 13210 return None; 13211 } 13212 13213 return None; 13214 } 13215 13216 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13217 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13218 Message->getReceiverInterface(), 13219 NSAPI::ClassId_NSMutableSet); 13220 13221 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13222 Message->getReceiverInterface(), 13223 NSAPI::ClassId_NSMutableOrderedSet); 13224 if (!IsMutableSet && !IsMutableOrderedSet) { 13225 return None; 13226 } 13227 13228 Selector Sel = Message->getSelector(); 13229 13230 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13231 if (!MKOpt) { 13232 return None; 13233 } 13234 13235 NSAPI::NSSetMethodKind MK = *MKOpt; 13236 13237 switch (MK) { 13238 case NSAPI::NSMutableSet_addObject: 13239 case NSAPI::NSOrderedSet_setObjectAtIndex: 13240 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13241 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13242 return 0; 13243 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13244 return 1; 13245 } 13246 13247 return None; 13248 } 13249 13250 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13251 if (!Message->isInstanceMessage()) { 13252 return; 13253 } 13254 13255 Optional<int> ArgOpt; 13256 13257 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13258 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13259 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13260 return; 13261 } 13262 13263 int ArgIndex = *ArgOpt; 13264 13265 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13266 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13267 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13268 } 13269 13270 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13271 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13272 if (ArgRE->isObjCSelfExpr()) { 13273 Diag(Message->getSourceRange().getBegin(), 13274 diag::warn_objc_circular_container) 13275 << ArgRE->getDecl() << StringRef("'super'"); 13276 } 13277 } 13278 } else { 13279 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13280 13281 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13282 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13283 } 13284 13285 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13286 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13287 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13288 ValueDecl *Decl = ReceiverRE->getDecl(); 13289 Diag(Message->getSourceRange().getBegin(), 13290 diag::warn_objc_circular_container) 13291 << Decl << Decl; 13292 if (!ArgRE->isObjCSelfExpr()) { 13293 Diag(Decl->getLocation(), 13294 diag::note_objc_circular_container_declared_here) 13295 << Decl; 13296 } 13297 } 13298 } 13299 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13300 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13301 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13302 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13303 Diag(Message->getSourceRange().getBegin(), 13304 diag::warn_objc_circular_container) 13305 << Decl << Decl; 13306 Diag(Decl->getLocation(), 13307 diag::note_objc_circular_container_declared_here) 13308 << Decl; 13309 } 13310 } 13311 } 13312 } 13313 } 13314 13315 /// Check a message send to see if it's likely to cause a retain cycle. 13316 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13317 // Only check instance methods whose selector looks like a setter. 13318 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13319 return; 13320 13321 // Try to find a variable that the receiver is strongly owned by. 13322 RetainCycleOwner owner; 13323 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13324 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13325 return; 13326 } else { 13327 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13328 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13329 owner.Loc = msg->getSuperLoc(); 13330 owner.Range = msg->getSuperLoc(); 13331 } 13332 13333 // Check whether the receiver is captured by any of the arguments. 13334 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13335 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13336 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13337 // noescape blocks should not be retained by the method. 13338 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13339 continue; 13340 return diagnoseRetainCycle(*this, capturer, owner); 13341 } 13342 } 13343 } 13344 13345 /// Check a property assign to see if it's likely to cause a retain cycle. 13346 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13347 RetainCycleOwner owner; 13348 if (!findRetainCycleOwner(*this, receiver, owner)) 13349 return; 13350 13351 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13352 diagnoseRetainCycle(*this, capturer, owner); 13353 } 13354 13355 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13356 RetainCycleOwner Owner; 13357 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13358 return; 13359 13360 // Because we don't have an expression for the variable, we have to set the 13361 // location explicitly here. 13362 Owner.Loc = Var->getLocation(); 13363 Owner.Range = Var->getSourceRange(); 13364 13365 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13366 diagnoseRetainCycle(*this, Capturer, Owner); 13367 } 13368 13369 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13370 Expr *RHS, bool isProperty) { 13371 // Check if RHS is an Objective-C object literal, which also can get 13372 // immediately zapped in a weak reference. Note that we explicitly 13373 // allow ObjCStringLiterals, since those are designed to never really die. 13374 RHS = RHS->IgnoreParenImpCasts(); 13375 13376 // This enum needs to match with the 'select' in 13377 // warn_objc_arc_literal_assign (off-by-1). 13378 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13379 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13380 return false; 13381 13382 S.Diag(Loc, diag::warn_arc_literal_assign) 13383 << (unsigned) Kind 13384 << (isProperty ? 0 : 1) 13385 << RHS->getSourceRange(); 13386 13387 return true; 13388 } 13389 13390 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13391 Qualifiers::ObjCLifetime LT, 13392 Expr *RHS, bool isProperty) { 13393 // Strip off any implicit cast added to get to the one ARC-specific. 13394 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13395 if (cast->getCastKind() == CK_ARCConsumeObject) { 13396 S.Diag(Loc, diag::warn_arc_retained_assign) 13397 << (LT == Qualifiers::OCL_ExplicitNone) 13398 << (isProperty ? 0 : 1) 13399 << RHS->getSourceRange(); 13400 return true; 13401 } 13402 RHS = cast->getSubExpr(); 13403 } 13404 13405 if (LT == Qualifiers::OCL_Weak && 13406 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13407 return true; 13408 13409 return false; 13410 } 13411 13412 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13413 QualType LHS, Expr *RHS) { 13414 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13415 13416 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13417 return false; 13418 13419 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13420 return true; 13421 13422 return false; 13423 } 13424 13425 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13426 Expr *LHS, Expr *RHS) { 13427 QualType LHSType; 13428 // PropertyRef on LHS type need be directly obtained from 13429 // its declaration as it has a PseudoType. 13430 ObjCPropertyRefExpr *PRE 13431 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13432 if (PRE && !PRE->isImplicitProperty()) { 13433 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13434 if (PD) 13435 LHSType = PD->getType(); 13436 } 13437 13438 if (LHSType.isNull()) 13439 LHSType = LHS->getType(); 13440 13441 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13442 13443 if (LT == Qualifiers::OCL_Weak) { 13444 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13445 getCurFunction()->markSafeWeakUse(LHS); 13446 } 13447 13448 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13449 return; 13450 13451 // FIXME. Check for other life times. 13452 if (LT != Qualifiers::OCL_None) 13453 return; 13454 13455 if (PRE) { 13456 if (PRE->isImplicitProperty()) 13457 return; 13458 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13459 if (!PD) 13460 return; 13461 13462 unsigned Attributes = PD->getPropertyAttributes(); 13463 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13464 // when 'assign' attribute was not explicitly specified 13465 // by user, ignore it and rely on property type itself 13466 // for lifetime info. 13467 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13468 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13469 LHSType->isObjCRetainableType()) 13470 return; 13471 13472 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13473 if (cast->getCastKind() == CK_ARCConsumeObject) { 13474 Diag(Loc, diag::warn_arc_retained_property_assign) 13475 << RHS->getSourceRange(); 13476 return; 13477 } 13478 RHS = cast->getSubExpr(); 13479 } 13480 } 13481 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13482 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13483 return; 13484 } 13485 } 13486 } 13487 13488 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13489 13490 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13491 SourceLocation StmtLoc, 13492 const NullStmt *Body) { 13493 // Do not warn if the body is a macro that expands to nothing, e.g: 13494 // 13495 // #define CALL(x) 13496 // if (condition) 13497 // CALL(0); 13498 if (Body->hasLeadingEmptyMacro()) 13499 return false; 13500 13501 // Get line numbers of statement and body. 13502 bool StmtLineInvalid; 13503 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13504 &StmtLineInvalid); 13505 if (StmtLineInvalid) 13506 return false; 13507 13508 bool BodyLineInvalid; 13509 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13510 &BodyLineInvalid); 13511 if (BodyLineInvalid) 13512 return false; 13513 13514 // Warn if null statement and body are on the same line. 13515 if (StmtLine != BodyLine) 13516 return false; 13517 13518 return true; 13519 } 13520 13521 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13522 const Stmt *Body, 13523 unsigned DiagID) { 13524 // Since this is a syntactic check, don't emit diagnostic for template 13525 // instantiations, this just adds noise. 13526 if (CurrentInstantiationScope) 13527 return; 13528 13529 // The body should be a null statement. 13530 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13531 if (!NBody) 13532 return; 13533 13534 // Do the usual checks. 13535 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13536 return; 13537 13538 Diag(NBody->getSemiLoc(), DiagID); 13539 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13540 } 13541 13542 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13543 const Stmt *PossibleBody) { 13544 assert(!CurrentInstantiationScope); // Ensured by caller 13545 13546 SourceLocation StmtLoc; 13547 const Stmt *Body; 13548 unsigned DiagID; 13549 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13550 StmtLoc = FS->getRParenLoc(); 13551 Body = FS->getBody(); 13552 DiagID = diag::warn_empty_for_body; 13553 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13554 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13555 Body = WS->getBody(); 13556 DiagID = diag::warn_empty_while_body; 13557 } else 13558 return; // Neither `for' nor `while'. 13559 13560 // The body should be a null statement. 13561 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13562 if (!NBody) 13563 return; 13564 13565 // Skip expensive checks if diagnostic is disabled. 13566 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13567 return; 13568 13569 // Do the usual checks. 13570 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13571 return; 13572 13573 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13574 // noise level low, emit diagnostics only if for/while is followed by a 13575 // CompoundStmt, e.g.: 13576 // for (int i = 0; i < n; i++); 13577 // { 13578 // a(i); 13579 // } 13580 // or if for/while is followed by a statement with more indentation 13581 // than for/while itself: 13582 // for (int i = 0; i < n; i++); 13583 // a(i); 13584 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13585 if (!ProbableTypo) { 13586 bool BodyColInvalid; 13587 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13588 PossibleBody->getBeginLoc(), &BodyColInvalid); 13589 if (BodyColInvalid) 13590 return; 13591 13592 bool StmtColInvalid; 13593 unsigned StmtCol = 13594 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13595 if (StmtColInvalid) 13596 return; 13597 13598 if (BodyCol > StmtCol) 13599 ProbableTypo = true; 13600 } 13601 13602 if (ProbableTypo) { 13603 Diag(NBody->getSemiLoc(), DiagID); 13604 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13605 } 13606 } 13607 13608 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13609 13610 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13611 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13612 SourceLocation OpLoc) { 13613 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13614 return; 13615 13616 if (inTemplateInstantiation()) 13617 return; 13618 13619 // Strip parens and casts away. 13620 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13621 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13622 13623 // Check for a call expression 13624 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13625 if (!CE || CE->getNumArgs() != 1) 13626 return; 13627 13628 // Check for a call to std::move 13629 if (!CE->isCallToStdMove()) 13630 return; 13631 13632 // Get argument from std::move 13633 RHSExpr = CE->getArg(0); 13634 13635 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13636 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13637 13638 // Two DeclRefExpr's, check that the decls are the same. 13639 if (LHSDeclRef && RHSDeclRef) { 13640 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13641 return; 13642 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13643 RHSDeclRef->getDecl()->getCanonicalDecl()) 13644 return; 13645 13646 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13647 << LHSExpr->getSourceRange() 13648 << RHSExpr->getSourceRange(); 13649 return; 13650 } 13651 13652 // Member variables require a different approach to check for self moves. 13653 // MemberExpr's are the same if every nested MemberExpr refers to the same 13654 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13655 // the base Expr's are CXXThisExpr's. 13656 const Expr *LHSBase = LHSExpr; 13657 const Expr *RHSBase = RHSExpr; 13658 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13659 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13660 if (!LHSME || !RHSME) 13661 return; 13662 13663 while (LHSME && RHSME) { 13664 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13665 RHSME->getMemberDecl()->getCanonicalDecl()) 13666 return; 13667 13668 LHSBase = LHSME->getBase(); 13669 RHSBase = RHSME->getBase(); 13670 LHSME = dyn_cast<MemberExpr>(LHSBase); 13671 RHSME = dyn_cast<MemberExpr>(RHSBase); 13672 } 13673 13674 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13675 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13676 if (LHSDeclRef && RHSDeclRef) { 13677 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13678 return; 13679 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13680 RHSDeclRef->getDecl()->getCanonicalDecl()) 13681 return; 13682 13683 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13684 << LHSExpr->getSourceRange() 13685 << RHSExpr->getSourceRange(); 13686 return; 13687 } 13688 13689 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13690 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13691 << LHSExpr->getSourceRange() 13692 << RHSExpr->getSourceRange(); 13693 } 13694 13695 //===--- Layout compatibility ----------------------------------------------// 13696 13697 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13698 13699 /// Check if two enumeration types are layout-compatible. 13700 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13701 // C++11 [dcl.enum] p8: 13702 // Two enumeration types are layout-compatible if they have the same 13703 // underlying type. 13704 return ED1->isComplete() && ED2->isComplete() && 13705 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13706 } 13707 13708 /// Check if two fields are layout-compatible. 13709 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13710 FieldDecl *Field2) { 13711 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13712 return false; 13713 13714 if (Field1->isBitField() != Field2->isBitField()) 13715 return false; 13716 13717 if (Field1->isBitField()) { 13718 // Make sure that the bit-fields are the same length. 13719 unsigned Bits1 = Field1->getBitWidthValue(C); 13720 unsigned Bits2 = Field2->getBitWidthValue(C); 13721 13722 if (Bits1 != Bits2) 13723 return false; 13724 } 13725 13726 return true; 13727 } 13728 13729 /// Check if two standard-layout structs are layout-compatible. 13730 /// (C++11 [class.mem] p17) 13731 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13732 RecordDecl *RD2) { 13733 // If both records are C++ classes, check that base classes match. 13734 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13735 // If one of records is a CXXRecordDecl we are in C++ mode, 13736 // thus the other one is a CXXRecordDecl, too. 13737 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13738 // Check number of base classes. 13739 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13740 return false; 13741 13742 // Check the base classes. 13743 for (CXXRecordDecl::base_class_const_iterator 13744 Base1 = D1CXX->bases_begin(), 13745 BaseEnd1 = D1CXX->bases_end(), 13746 Base2 = D2CXX->bases_begin(); 13747 Base1 != BaseEnd1; 13748 ++Base1, ++Base2) { 13749 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13750 return false; 13751 } 13752 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13753 // If only RD2 is a C++ class, it should have zero base classes. 13754 if (D2CXX->getNumBases() > 0) 13755 return false; 13756 } 13757 13758 // Check the fields. 13759 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13760 Field2End = RD2->field_end(), 13761 Field1 = RD1->field_begin(), 13762 Field1End = RD1->field_end(); 13763 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13764 if (!isLayoutCompatible(C, *Field1, *Field2)) 13765 return false; 13766 } 13767 if (Field1 != Field1End || Field2 != Field2End) 13768 return false; 13769 13770 return true; 13771 } 13772 13773 /// Check if two standard-layout unions are layout-compatible. 13774 /// (C++11 [class.mem] p18) 13775 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13776 RecordDecl *RD2) { 13777 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13778 for (auto *Field2 : RD2->fields()) 13779 UnmatchedFields.insert(Field2); 13780 13781 for (auto *Field1 : RD1->fields()) { 13782 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13783 I = UnmatchedFields.begin(), 13784 E = UnmatchedFields.end(); 13785 13786 for ( ; I != E; ++I) { 13787 if (isLayoutCompatible(C, Field1, *I)) { 13788 bool Result = UnmatchedFields.erase(*I); 13789 (void) Result; 13790 assert(Result); 13791 break; 13792 } 13793 } 13794 if (I == E) 13795 return false; 13796 } 13797 13798 return UnmatchedFields.empty(); 13799 } 13800 13801 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13802 RecordDecl *RD2) { 13803 if (RD1->isUnion() != RD2->isUnion()) 13804 return false; 13805 13806 if (RD1->isUnion()) 13807 return isLayoutCompatibleUnion(C, RD1, RD2); 13808 else 13809 return isLayoutCompatibleStruct(C, RD1, RD2); 13810 } 13811 13812 /// Check if two types are layout-compatible in C++11 sense. 13813 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13814 if (T1.isNull() || T2.isNull()) 13815 return false; 13816 13817 // C++11 [basic.types] p11: 13818 // If two types T1 and T2 are the same type, then T1 and T2 are 13819 // layout-compatible types. 13820 if (C.hasSameType(T1, T2)) 13821 return true; 13822 13823 T1 = T1.getCanonicalType().getUnqualifiedType(); 13824 T2 = T2.getCanonicalType().getUnqualifiedType(); 13825 13826 const Type::TypeClass TC1 = T1->getTypeClass(); 13827 const Type::TypeClass TC2 = T2->getTypeClass(); 13828 13829 if (TC1 != TC2) 13830 return false; 13831 13832 if (TC1 == Type::Enum) { 13833 return isLayoutCompatible(C, 13834 cast<EnumType>(T1)->getDecl(), 13835 cast<EnumType>(T2)->getDecl()); 13836 } else if (TC1 == Type::Record) { 13837 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13838 return false; 13839 13840 return isLayoutCompatible(C, 13841 cast<RecordType>(T1)->getDecl(), 13842 cast<RecordType>(T2)->getDecl()); 13843 } 13844 13845 return false; 13846 } 13847 13848 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13849 13850 /// Given a type tag expression find the type tag itself. 13851 /// 13852 /// \param TypeExpr Type tag expression, as it appears in user's code. 13853 /// 13854 /// \param VD Declaration of an identifier that appears in a type tag. 13855 /// 13856 /// \param MagicValue Type tag magic value. 13857 /// 13858 /// \param isConstantEvaluated wether the evalaution should be performed in 13859 13860 /// constant context. 13861 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13862 const ValueDecl **VD, uint64_t *MagicValue, 13863 bool isConstantEvaluated) { 13864 while(true) { 13865 if (!TypeExpr) 13866 return false; 13867 13868 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13869 13870 switch (TypeExpr->getStmtClass()) { 13871 case Stmt::UnaryOperatorClass: { 13872 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13873 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13874 TypeExpr = UO->getSubExpr(); 13875 continue; 13876 } 13877 return false; 13878 } 13879 13880 case Stmt::DeclRefExprClass: { 13881 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13882 *VD = DRE->getDecl(); 13883 return true; 13884 } 13885 13886 case Stmt::IntegerLiteralClass: { 13887 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13888 llvm::APInt MagicValueAPInt = IL->getValue(); 13889 if (MagicValueAPInt.getActiveBits() <= 64) { 13890 *MagicValue = MagicValueAPInt.getZExtValue(); 13891 return true; 13892 } else 13893 return false; 13894 } 13895 13896 case Stmt::BinaryConditionalOperatorClass: 13897 case Stmt::ConditionalOperatorClass: { 13898 const AbstractConditionalOperator *ACO = 13899 cast<AbstractConditionalOperator>(TypeExpr); 13900 bool Result; 13901 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 13902 isConstantEvaluated)) { 13903 if (Result) 13904 TypeExpr = ACO->getTrueExpr(); 13905 else 13906 TypeExpr = ACO->getFalseExpr(); 13907 continue; 13908 } 13909 return false; 13910 } 13911 13912 case Stmt::BinaryOperatorClass: { 13913 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13914 if (BO->getOpcode() == BO_Comma) { 13915 TypeExpr = BO->getRHS(); 13916 continue; 13917 } 13918 return false; 13919 } 13920 13921 default: 13922 return false; 13923 } 13924 } 13925 } 13926 13927 /// Retrieve the C type corresponding to type tag TypeExpr. 13928 /// 13929 /// \param TypeExpr Expression that specifies a type tag. 13930 /// 13931 /// \param MagicValues Registered magic values. 13932 /// 13933 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13934 /// kind. 13935 /// 13936 /// \param TypeInfo Information about the corresponding C type. 13937 /// 13938 /// \param isConstantEvaluated wether the evalaution should be performed in 13939 /// constant context. 13940 /// 13941 /// \returns true if the corresponding C type was found. 13942 static bool GetMatchingCType( 13943 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 13944 const ASTContext &Ctx, 13945 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 13946 *MagicValues, 13947 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 13948 bool isConstantEvaluated) { 13949 FoundWrongKind = false; 13950 13951 // Variable declaration that has type_tag_for_datatype attribute. 13952 const ValueDecl *VD = nullptr; 13953 13954 uint64_t MagicValue; 13955 13956 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 13957 return false; 13958 13959 if (VD) { 13960 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13961 if (I->getArgumentKind() != ArgumentKind) { 13962 FoundWrongKind = true; 13963 return false; 13964 } 13965 TypeInfo.Type = I->getMatchingCType(); 13966 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13967 TypeInfo.MustBeNull = I->getMustBeNull(); 13968 return true; 13969 } 13970 return false; 13971 } 13972 13973 if (!MagicValues) 13974 return false; 13975 13976 llvm::DenseMap<Sema::TypeTagMagicValue, 13977 Sema::TypeTagData>::const_iterator I = 13978 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13979 if (I == MagicValues->end()) 13980 return false; 13981 13982 TypeInfo = I->second; 13983 return true; 13984 } 13985 13986 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13987 uint64_t MagicValue, QualType Type, 13988 bool LayoutCompatible, 13989 bool MustBeNull) { 13990 if (!TypeTagForDatatypeMagicValues) 13991 TypeTagForDatatypeMagicValues.reset( 13992 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13993 13994 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13995 (*TypeTagForDatatypeMagicValues)[Magic] = 13996 TypeTagData(Type, LayoutCompatible, MustBeNull); 13997 } 13998 13999 static bool IsSameCharType(QualType T1, QualType T2) { 14000 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14001 if (!BT1) 14002 return false; 14003 14004 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14005 if (!BT2) 14006 return false; 14007 14008 BuiltinType::Kind T1Kind = BT1->getKind(); 14009 BuiltinType::Kind T2Kind = BT2->getKind(); 14010 14011 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14012 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14013 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14014 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14015 } 14016 14017 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14018 const ArrayRef<const Expr *> ExprArgs, 14019 SourceLocation CallSiteLoc) { 14020 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14021 bool IsPointerAttr = Attr->getIsPointer(); 14022 14023 // Retrieve the argument representing the 'type_tag'. 14024 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14025 if (TypeTagIdxAST >= ExprArgs.size()) { 14026 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14027 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14028 return; 14029 } 14030 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14031 bool FoundWrongKind; 14032 TypeTagData TypeInfo; 14033 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14034 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14035 TypeInfo, isConstantEvaluated())) { 14036 if (FoundWrongKind) 14037 Diag(TypeTagExpr->getExprLoc(), 14038 diag::warn_type_tag_for_datatype_wrong_kind) 14039 << TypeTagExpr->getSourceRange(); 14040 return; 14041 } 14042 14043 // Retrieve the argument representing the 'arg_idx'. 14044 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14045 if (ArgumentIdxAST >= ExprArgs.size()) { 14046 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14047 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14048 return; 14049 } 14050 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14051 if (IsPointerAttr) { 14052 // Skip implicit cast of pointer to `void *' (as a function argument). 14053 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14054 if (ICE->getType()->isVoidPointerType() && 14055 ICE->getCastKind() == CK_BitCast) 14056 ArgumentExpr = ICE->getSubExpr(); 14057 } 14058 QualType ArgumentType = ArgumentExpr->getType(); 14059 14060 // Passing a `void*' pointer shouldn't trigger a warning. 14061 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14062 return; 14063 14064 if (TypeInfo.MustBeNull) { 14065 // Type tag with matching void type requires a null pointer. 14066 if (!ArgumentExpr->isNullPointerConstant(Context, 14067 Expr::NPC_ValueDependentIsNotNull)) { 14068 Diag(ArgumentExpr->getExprLoc(), 14069 diag::warn_type_safety_null_pointer_required) 14070 << ArgumentKind->getName() 14071 << ArgumentExpr->getSourceRange() 14072 << TypeTagExpr->getSourceRange(); 14073 } 14074 return; 14075 } 14076 14077 QualType RequiredType = TypeInfo.Type; 14078 if (IsPointerAttr) 14079 RequiredType = Context.getPointerType(RequiredType); 14080 14081 bool mismatch = false; 14082 if (!TypeInfo.LayoutCompatible) { 14083 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14084 14085 // C++11 [basic.fundamental] p1: 14086 // Plain char, signed char, and unsigned char are three distinct types. 14087 // 14088 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14089 // char' depending on the current char signedness mode. 14090 if (mismatch) 14091 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14092 RequiredType->getPointeeType())) || 14093 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14094 mismatch = false; 14095 } else 14096 if (IsPointerAttr) 14097 mismatch = !isLayoutCompatible(Context, 14098 ArgumentType->getPointeeType(), 14099 RequiredType->getPointeeType()); 14100 else 14101 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14102 14103 if (mismatch) 14104 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14105 << ArgumentType << ArgumentKind 14106 << TypeInfo.LayoutCompatible << RequiredType 14107 << ArgumentExpr->getSourceRange() 14108 << TypeTagExpr->getSourceRange(); 14109 } 14110 14111 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14112 CharUnits Alignment) { 14113 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14114 } 14115 14116 void Sema::DiagnoseMisalignedMembers() { 14117 for (MisalignedMember &m : MisalignedMembers) { 14118 const NamedDecl *ND = m.RD; 14119 if (ND->getName().empty()) { 14120 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14121 ND = TD; 14122 } 14123 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14124 << m.MD << ND << m.E->getSourceRange(); 14125 } 14126 MisalignedMembers.clear(); 14127 } 14128 14129 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14130 E = E->IgnoreParens(); 14131 if (!T->isPointerType() && !T->isIntegerType()) 14132 return; 14133 if (isa<UnaryOperator>(E) && 14134 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14135 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14136 if (isa<MemberExpr>(Op)) { 14137 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14138 if (MA != MisalignedMembers.end() && 14139 (T->isIntegerType() || 14140 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14141 Context.getTypeAlignInChars( 14142 T->getPointeeType()) <= MA->Alignment)))) 14143 MisalignedMembers.erase(MA); 14144 } 14145 } 14146 } 14147 14148 void Sema::RefersToMemberWithReducedAlignment( 14149 Expr *E, 14150 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14151 Action) { 14152 const auto *ME = dyn_cast<MemberExpr>(E); 14153 if (!ME) 14154 return; 14155 14156 // No need to check expressions with an __unaligned-qualified type. 14157 if (E->getType().getQualifiers().hasUnaligned()) 14158 return; 14159 14160 // For a chain of MemberExpr like "a.b.c.d" this list 14161 // will keep FieldDecl's like [d, c, b]. 14162 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14163 const MemberExpr *TopME = nullptr; 14164 bool AnyIsPacked = false; 14165 do { 14166 QualType BaseType = ME->getBase()->getType(); 14167 if (ME->isArrow()) 14168 BaseType = BaseType->getPointeeType(); 14169 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 14170 if (RD->isInvalidDecl()) 14171 return; 14172 14173 ValueDecl *MD = ME->getMemberDecl(); 14174 auto *FD = dyn_cast<FieldDecl>(MD); 14175 // We do not care about non-data members. 14176 if (!FD || FD->isInvalidDecl()) 14177 return; 14178 14179 AnyIsPacked = 14180 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14181 ReverseMemberChain.push_back(FD); 14182 14183 TopME = ME; 14184 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14185 } while (ME); 14186 assert(TopME && "We did not compute a topmost MemberExpr!"); 14187 14188 // Not the scope of this diagnostic. 14189 if (!AnyIsPacked) 14190 return; 14191 14192 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14193 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14194 // TODO: The innermost base of the member expression may be too complicated. 14195 // For now, just disregard these cases. This is left for future 14196 // improvement. 14197 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14198 return; 14199 14200 // Alignment expected by the whole expression. 14201 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14202 14203 // No need to do anything else with this case. 14204 if (ExpectedAlignment.isOne()) 14205 return; 14206 14207 // Synthesize offset of the whole access. 14208 CharUnits Offset; 14209 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14210 I++) { 14211 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14212 } 14213 14214 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14215 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14216 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14217 14218 // The base expression of the innermost MemberExpr may give 14219 // stronger guarantees than the class containing the member. 14220 if (DRE && !TopME->isArrow()) { 14221 const ValueDecl *VD = DRE->getDecl(); 14222 if (!VD->getType()->isReferenceType()) 14223 CompleteObjectAlignment = 14224 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14225 } 14226 14227 // Check if the synthesized offset fulfills the alignment. 14228 if (Offset % ExpectedAlignment != 0 || 14229 // It may fulfill the offset it but the effective alignment may still be 14230 // lower than the expected expression alignment. 14231 CompleteObjectAlignment < ExpectedAlignment) { 14232 // If this happens, we want to determine a sensible culprit of this. 14233 // Intuitively, watching the chain of member expressions from right to 14234 // left, we start with the required alignment (as required by the field 14235 // type) but some packed attribute in that chain has reduced the alignment. 14236 // It may happen that another packed structure increases it again. But if 14237 // we are here such increase has not been enough. So pointing the first 14238 // FieldDecl that either is packed or else its RecordDecl is, 14239 // seems reasonable. 14240 FieldDecl *FD = nullptr; 14241 CharUnits Alignment; 14242 for (FieldDecl *FDI : ReverseMemberChain) { 14243 if (FDI->hasAttr<PackedAttr>() || 14244 FDI->getParent()->hasAttr<PackedAttr>()) { 14245 FD = FDI; 14246 Alignment = std::min( 14247 Context.getTypeAlignInChars(FD->getType()), 14248 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14249 break; 14250 } 14251 } 14252 assert(FD && "We did not find a packed FieldDecl!"); 14253 Action(E, FD->getParent(), FD, Alignment); 14254 } 14255 } 14256 14257 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14258 using namespace std::placeholders; 14259 14260 RefersToMemberWithReducedAlignment( 14261 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14262 _2, _3, _4)); 14263 } 14264