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/raw_ostream.h" 88 #include <algorithm> 89 #include <cassert> 90 #include <cstddef> 91 #include <cstdint> 92 #include <functional> 93 #include <limits> 94 #include <string> 95 #include <tuple> 96 #include <utility> 97 98 using namespace clang; 99 using namespace sema; 100 101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 102 unsigned ByteNo) const { 103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 104 Context.getTargetInfo()); 105 } 106 107 /// Checks that a call expression's argument count is the desired number. 108 /// This is useful when doing custom type-checking. Returns true on error. 109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 110 unsigned argCount = call->getNumArgs(); 111 if (argCount == desiredArgCount) return false; 112 113 if (argCount < desiredArgCount) 114 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 115 << 0 /*function call*/ << desiredArgCount << argCount 116 << call->getSourceRange(); 117 118 // Highlight all the excess arguments. 119 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 120 call->getArg(argCount - 1)->getEndLoc()); 121 122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 123 << 0 /*function call*/ << desiredArgCount << argCount 124 << call->getArg(1)->getSourceRange(); 125 } 126 127 /// Check that the first argument to __builtin_annotation is an integer 128 /// and the second argument is a non-wide string literal. 129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 130 if (checkArgCount(S, TheCall, 2)) 131 return true; 132 133 // First argument should be an integer. 134 Expr *ValArg = TheCall->getArg(0); 135 QualType Ty = ValArg->getType(); 136 if (!Ty->isIntegerType()) { 137 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 138 << ValArg->getSourceRange(); 139 return true; 140 } 141 142 // Second argument should be a constant string. 143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 145 if (!Literal || !Literal->isAscii()) { 146 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 147 << StrArg->getSourceRange(); 148 return true; 149 } 150 151 TheCall->setType(Ty); 152 return false; 153 } 154 155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 156 // We need at least one argument. 157 if (TheCall->getNumArgs() < 1) { 158 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 159 << 0 << 1 << TheCall->getNumArgs() 160 << TheCall->getCallee()->getSourceRange(); 161 return true; 162 } 163 164 // All arguments should be wide string literals. 165 for (Expr *Arg : TheCall->arguments()) { 166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 167 if (!Literal || !Literal->isWide()) { 168 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 169 << Arg->getSourceRange(); 170 return true; 171 } 172 } 173 174 return false; 175 } 176 177 /// Check that the argument to __builtin_addressof is a glvalue, and set the 178 /// result type to the corresponding pointer type. 179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 180 if (checkArgCount(S, TheCall, 1)) 181 return true; 182 183 ExprResult Arg(TheCall->getArg(0)); 184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 185 if (ResultType.isNull()) 186 return true; 187 188 TheCall->setArg(0, Arg.get()); 189 TheCall->setType(ResultType); 190 return false; 191 } 192 193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 194 if (checkArgCount(S, TheCall, 3)) 195 return true; 196 197 // First two arguments should be integers. 198 for (unsigned I = 0; I < 2; ++I) { 199 ExprResult Arg = TheCall->getArg(I); 200 QualType Ty = Arg.get()->getType(); 201 if (!Ty->isIntegerType()) { 202 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 203 << Ty << Arg.get()->getSourceRange(); 204 return true; 205 } 206 InitializedEntity Entity = InitializedEntity::InitializeParameter( 207 S.getASTContext(), Ty, /*consume*/ false); 208 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 209 if (Arg.isInvalid()) 210 return true; 211 TheCall->setArg(I, Arg.get()); 212 } 213 214 // Third argument should be a pointer to a non-const integer. 215 // IRGen correctly handles volatile, restrict, and address spaces, and 216 // the other qualifiers aren't possible. 217 { 218 ExprResult Arg = TheCall->getArg(2); 219 QualType Ty = Arg.get()->getType(); 220 const auto *PtrTy = Ty->getAs<PointerType>(); 221 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 222 !PtrTy->getPointeeType().isConstQualified())) { 223 S.Diag(Arg.get()->getBeginLoc(), 224 diag::err_overflow_builtin_must_be_ptr_int) 225 << Ty << Arg.get()->getSourceRange(); 226 return true; 227 } 228 InitializedEntity Entity = InitializedEntity::InitializeParameter( 229 S.getASTContext(), Ty, /*consume*/ false); 230 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 231 if (Arg.isInvalid()) 232 return true; 233 TheCall->setArg(2, Arg.get()); 234 } 235 return false; 236 } 237 238 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 239 if (checkArgCount(S, BuiltinCall, 2)) 240 return true; 241 242 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 243 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 244 Expr *Call = BuiltinCall->getArg(0); 245 Expr *Chain = BuiltinCall->getArg(1); 246 247 if (Call->getStmtClass() != Stmt::CallExprClass) { 248 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 249 << Call->getSourceRange(); 250 return true; 251 } 252 253 auto CE = cast<CallExpr>(Call); 254 if (CE->getCallee()->getType()->isBlockPointerType()) { 255 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 256 << Call->getSourceRange(); 257 return true; 258 } 259 260 const Decl *TargetDecl = CE->getCalleeDecl(); 261 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 262 if (FD->getBuiltinID()) { 263 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 264 << Call->getSourceRange(); 265 return true; 266 } 267 268 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 269 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 270 << Call->getSourceRange(); 271 return true; 272 } 273 274 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 275 if (ChainResult.isInvalid()) 276 return true; 277 if (!ChainResult.get()->getType()->isPointerType()) { 278 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 279 << Chain->getSourceRange(); 280 return true; 281 } 282 283 QualType ReturnTy = CE->getCallReturnType(S.Context); 284 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 285 QualType BuiltinTy = S.Context.getFunctionType( 286 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 287 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 288 289 Builtin = 290 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 291 292 BuiltinCall->setType(CE->getType()); 293 BuiltinCall->setValueKind(CE->getValueKind()); 294 BuiltinCall->setObjectKind(CE->getObjectKind()); 295 BuiltinCall->setCallee(Builtin); 296 BuiltinCall->setArg(1, ChainResult.get()); 297 298 return false; 299 } 300 301 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 302 /// __builtin_*_chk function, then use the object size argument specified in the 303 /// source. Otherwise, infer the object size using __builtin_object_size. 304 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 305 CallExpr *TheCall) { 306 // FIXME: There are some more useful checks we could be doing here: 307 // - Analyze the format string of sprintf to see how much of buffer is used. 308 // - Evaluate strlen of strcpy arguments, use as object size. 309 310 if (TheCall->isValueDependent() || TheCall->isTypeDependent()) 311 return; 312 313 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 314 if (!BuiltinID) 315 return; 316 317 unsigned DiagID = 0; 318 bool IsChkVariant = false; 319 unsigned SizeIndex, ObjectIndex; 320 switch (BuiltinID) { 321 default: 322 return; 323 case Builtin::BI__builtin___memcpy_chk: 324 case Builtin::BI__builtin___memmove_chk: 325 case Builtin::BI__builtin___memset_chk: 326 case Builtin::BI__builtin___strlcat_chk: 327 case Builtin::BI__builtin___strlcpy_chk: 328 case Builtin::BI__builtin___strncat_chk: 329 case Builtin::BI__builtin___strncpy_chk: 330 case Builtin::BI__builtin___stpncpy_chk: 331 case Builtin::BI__builtin___memccpy_chk: { 332 DiagID = diag::warn_builtin_chk_overflow; 333 IsChkVariant = true; 334 SizeIndex = TheCall->getNumArgs() - 2; 335 ObjectIndex = TheCall->getNumArgs() - 1; 336 break; 337 } 338 339 case Builtin::BI__builtin___snprintf_chk: 340 case Builtin::BI__builtin___vsnprintf_chk: { 341 DiagID = diag::warn_builtin_chk_overflow; 342 IsChkVariant = true; 343 SizeIndex = 1; 344 ObjectIndex = 3; 345 break; 346 } 347 348 case Builtin::BIstrncat: 349 case Builtin::BI__builtin_strncat: 350 case Builtin::BIstrncpy: 351 case Builtin::BI__builtin_strncpy: 352 case Builtin::BIstpncpy: 353 case Builtin::BI__builtin_stpncpy: { 354 // Whether these functions overflow depends on the runtime strlen of the 355 // string, not just the buffer size, so emitting the "always overflow" 356 // diagnostic isn't quite right. We should still diagnose passing a buffer 357 // size larger than the destination buffer though; this is a runtime abort 358 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 359 DiagID = diag::warn_fortify_source_size_mismatch; 360 SizeIndex = TheCall->getNumArgs() - 1; 361 ObjectIndex = 0; 362 break; 363 } 364 365 case Builtin::BImemcpy: 366 case Builtin::BI__builtin_memcpy: 367 case Builtin::BImemmove: 368 case Builtin::BI__builtin_memmove: 369 case Builtin::BImemset: 370 case Builtin::BI__builtin_memset: { 371 DiagID = diag::warn_fortify_source_overflow; 372 SizeIndex = TheCall->getNumArgs() - 1; 373 ObjectIndex = 0; 374 break; 375 } 376 case Builtin::BIsnprintf: 377 case Builtin::BI__builtin_snprintf: 378 case Builtin::BIvsnprintf: 379 case Builtin::BI__builtin_vsnprintf: { 380 DiagID = diag::warn_fortify_source_size_mismatch; 381 SizeIndex = 1; 382 ObjectIndex = 0; 383 break; 384 } 385 } 386 387 llvm::APSInt ObjectSize; 388 // For __builtin___*_chk, the object size is explicitly provided by the caller 389 // (usually using __builtin_object_size). Use that value to check this call. 390 if (IsChkVariant) { 391 Expr::EvalResult Result; 392 Expr *SizeArg = TheCall->getArg(ObjectIndex); 393 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 394 return; 395 ObjectSize = Result.Val.getInt(); 396 397 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 398 } else { 399 // If the parameter has a pass_object_size attribute, then we should use its 400 // (potentially) more strict checking mode. Otherwise, conservatively assume 401 // type 0. 402 int BOSType = 0; 403 if (const auto *POS = 404 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 405 BOSType = POS->getType(); 406 407 Expr *ObjArg = TheCall->getArg(ObjectIndex); 408 uint64_t Result; 409 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 410 return; 411 // Get the object size in the target's size_t width. 412 const TargetInfo &TI = getASTContext().getTargetInfo(); 413 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 414 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 415 } 416 417 // Evaluate the number of bytes of the object that this call will use. 418 Expr::EvalResult Result; 419 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 420 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 421 return; 422 llvm::APSInt UsedSize = Result.Val.getInt(); 423 424 if (UsedSize.ule(ObjectSize)) 425 return; 426 427 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 428 // Skim off the details of whichever builtin was called to produce a better 429 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 430 if (IsChkVariant) { 431 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 432 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 433 } else if (FunctionName.startswith("__builtin_")) { 434 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 435 } 436 437 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 438 PDiag(DiagID) 439 << FunctionName << ObjectSize.toString(/*Radix=*/10) 440 << UsedSize.toString(/*Radix=*/10)); 441 } 442 443 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 444 Scope::ScopeFlags NeededScopeFlags, 445 unsigned DiagID) { 446 // Scopes aren't available during instantiation. Fortunately, builtin 447 // functions cannot be template args so they cannot be formed through template 448 // instantiation. Therefore checking once during the parse is sufficient. 449 if (SemaRef.inTemplateInstantiation()) 450 return false; 451 452 Scope *S = SemaRef.getCurScope(); 453 while (S && !S->isSEHExceptScope()) 454 S = S->getParent(); 455 if (!S || !(S->getFlags() & NeededScopeFlags)) { 456 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 457 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 458 << DRE->getDecl()->getIdentifier(); 459 return true; 460 } 461 462 return false; 463 } 464 465 static inline bool isBlockPointer(Expr *Arg) { 466 return Arg->getType()->isBlockPointerType(); 467 } 468 469 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 470 /// void*, which is a requirement of device side enqueue. 471 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 472 const BlockPointerType *BPT = 473 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 474 ArrayRef<QualType> Params = 475 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes(); 476 unsigned ArgCounter = 0; 477 bool IllegalParams = false; 478 // Iterate through the block parameters until either one is found that is not 479 // a local void*, or the block is valid. 480 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 481 I != E; ++I, ++ArgCounter) { 482 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 483 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 484 LangAS::opencl_local) { 485 // Get the location of the error. If a block literal has been passed 486 // (BlockExpr) then we can point straight to the offending argument, 487 // else we just point to the variable reference. 488 SourceLocation ErrorLoc; 489 if (isa<BlockExpr>(BlockArg)) { 490 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 491 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 492 } else if (isa<DeclRefExpr>(BlockArg)) { 493 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 494 } 495 S.Diag(ErrorLoc, 496 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 497 IllegalParams = true; 498 } 499 } 500 501 return IllegalParams; 502 } 503 504 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 505 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 506 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 507 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 508 return true; 509 } 510 return false; 511 } 512 513 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 514 if (checkArgCount(S, TheCall, 2)) 515 return true; 516 517 if (checkOpenCLSubgroupExt(S, TheCall)) 518 return true; 519 520 // First argument is an ndrange_t type. 521 Expr *NDRangeArg = TheCall->getArg(0); 522 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 523 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 524 << TheCall->getDirectCallee() << "'ndrange_t'"; 525 return true; 526 } 527 528 Expr *BlockArg = TheCall->getArg(1); 529 if (!isBlockPointer(BlockArg)) { 530 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 531 << TheCall->getDirectCallee() << "block"; 532 return true; 533 } 534 return checkOpenCLBlockArgs(S, BlockArg); 535 } 536 537 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 538 /// get_kernel_work_group_size 539 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 540 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 541 if (checkArgCount(S, TheCall, 1)) 542 return true; 543 544 Expr *BlockArg = TheCall->getArg(0); 545 if (!isBlockPointer(BlockArg)) { 546 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 547 << TheCall->getDirectCallee() << "block"; 548 return true; 549 } 550 return checkOpenCLBlockArgs(S, BlockArg); 551 } 552 553 /// Diagnose integer type and any valid implicit conversion to it. 554 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 555 const QualType &IntType); 556 557 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 558 unsigned Start, unsigned End) { 559 bool IllegalParams = false; 560 for (unsigned I = Start; I <= End; ++I) 561 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 562 S.Context.getSizeType()); 563 return IllegalParams; 564 } 565 566 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 567 /// 'local void*' parameter of passed block. 568 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 569 Expr *BlockArg, 570 unsigned NumNonVarArgs) { 571 const BlockPointerType *BPT = 572 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 573 unsigned NumBlockParams = 574 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams(); 575 unsigned TotalNumArgs = TheCall->getNumArgs(); 576 577 // For each argument passed to the block, a corresponding uint needs to 578 // be passed to describe the size of the local memory. 579 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 580 S.Diag(TheCall->getBeginLoc(), 581 diag::err_opencl_enqueue_kernel_local_size_args); 582 return true; 583 } 584 585 // Check that the sizes of the local memory are specified by integers. 586 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 587 TotalNumArgs - 1); 588 } 589 590 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 591 /// overload formats specified in Table 6.13.17.1. 592 /// int enqueue_kernel(queue_t queue, 593 /// kernel_enqueue_flags_t flags, 594 /// const ndrange_t ndrange, 595 /// void (^block)(void)) 596 /// int enqueue_kernel(queue_t queue, 597 /// kernel_enqueue_flags_t flags, 598 /// const ndrange_t ndrange, 599 /// uint num_events_in_wait_list, 600 /// clk_event_t *event_wait_list, 601 /// clk_event_t *event_ret, 602 /// void (^block)(void)) 603 /// int enqueue_kernel(queue_t queue, 604 /// kernel_enqueue_flags_t flags, 605 /// const ndrange_t ndrange, 606 /// void (^block)(local void*, ...), 607 /// uint size0, ...) 608 /// int enqueue_kernel(queue_t queue, 609 /// kernel_enqueue_flags_t flags, 610 /// const ndrange_t ndrange, 611 /// uint num_events_in_wait_list, 612 /// clk_event_t *event_wait_list, 613 /// clk_event_t *event_ret, 614 /// void (^block)(local void*, ...), 615 /// uint size0, ...) 616 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 617 unsigned NumArgs = TheCall->getNumArgs(); 618 619 if (NumArgs < 4) { 620 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args); 621 return true; 622 } 623 624 Expr *Arg0 = TheCall->getArg(0); 625 Expr *Arg1 = TheCall->getArg(1); 626 Expr *Arg2 = TheCall->getArg(2); 627 Expr *Arg3 = TheCall->getArg(3); 628 629 // First argument always needs to be a queue_t type. 630 if (!Arg0->getType()->isQueueT()) { 631 S.Diag(TheCall->getArg(0)->getBeginLoc(), 632 diag::err_opencl_builtin_expected_type) 633 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 634 return true; 635 } 636 637 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 638 if (!Arg1->getType()->isIntegerType()) { 639 S.Diag(TheCall->getArg(1)->getBeginLoc(), 640 diag::err_opencl_builtin_expected_type) 641 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 642 return true; 643 } 644 645 // Third argument is always an ndrange_t type. 646 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 647 S.Diag(TheCall->getArg(2)->getBeginLoc(), 648 diag::err_opencl_builtin_expected_type) 649 << TheCall->getDirectCallee() << "'ndrange_t'"; 650 return true; 651 } 652 653 // With four arguments, there is only one form that the function could be 654 // called in: no events and no variable arguments. 655 if (NumArgs == 4) { 656 // check that the last argument is the right block type. 657 if (!isBlockPointer(Arg3)) { 658 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 659 << TheCall->getDirectCallee() << "block"; 660 return true; 661 } 662 // we have a block type, check the prototype 663 const BlockPointerType *BPT = 664 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 665 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 666 S.Diag(Arg3->getBeginLoc(), 667 diag::err_opencl_enqueue_kernel_blocks_no_args); 668 return true; 669 } 670 return false; 671 } 672 // we can have block + varargs. 673 if (isBlockPointer(Arg3)) 674 return (checkOpenCLBlockArgs(S, Arg3) || 675 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 676 // last two cases with either exactly 7 args or 7 args and varargs. 677 if (NumArgs >= 7) { 678 // check common block argument. 679 Expr *Arg6 = TheCall->getArg(6); 680 if (!isBlockPointer(Arg6)) { 681 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 682 << TheCall->getDirectCallee() << "block"; 683 return true; 684 } 685 if (checkOpenCLBlockArgs(S, Arg6)) 686 return true; 687 688 // Forth argument has to be any integer type. 689 if (!Arg3->getType()->isIntegerType()) { 690 S.Diag(TheCall->getArg(3)->getBeginLoc(), 691 diag::err_opencl_builtin_expected_type) 692 << TheCall->getDirectCallee() << "integer"; 693 return true; 694 } 695 // check remaining common arguments. 696 Expr *Arg4 = TheCall->getArg(4); 697 Expr *Arg5 = TheCall->getArg(5); 698 699 // Fifth argument is always passed as a pointer to clk_event_t. 700 if (!Arg4->isNullPointerConstant(S.Context, 701 Expr::NPC_ValueDependentIsNotNull) && 702 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 703 S.Diag(TheCall->getArg(4)->getBeginLoc(), 704 diag::err_opencl_builtin_expected_type) 705 << TheCall->getDirectCallee() 706 << S.Context.getPointerType(S.Context.OCLClkEventTy); 707 return true; 708 } 709 710 // Sixth argument is always passed as a pointer to clk_event_t. 711 if (!Arg5->isNullPointerConstant(S.Context, 712 Expr::NPC_ValueDependentIsNotNull) && 713 !(Arg5->getType()->isPointerType() && 714 Arg5->getType()->getPointeeType()->isClkEventT())) { 715 S.Diag(TheCall->getArg(5)->getBeginLoc(), 716 diag::err_opencl_builtin_expected_type) 717 << TheCall->getDirectCallee() 718 << S.Context.getPointerType(S.Context.OCLClkEventTy); 719 return true; 720 } 721 722 if (NumArgs == 7) 723 return false; 724 725 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 726 } 727 728 // None of the specific case has been detected, give generic error 729 S.Diag(TheCall->getBeginLoc(), 730 diag::err_opencl_enqueue_kernel_incorrect_args); 731 return true; 732 } 733 734 /// Returns OpenCL access qual. 735 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 736 return D->getAttr<OpenCLAccessAttr>(); 737 } 738 739 /// Returns true if pipe element type is different from the pointer. 740 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 741 const Expr *Arg0 = Call->getArg(0); 742 // First argument type should always be pipe. 743 if (!Arg0->getType()->isPipeType()) { 744 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 745 << Call->getDirectCallee() << Arg0->getSourceRange(); 746 return true; 747 } 748 OpenCLAccessAttr *AccessQual = 749 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 750 // Validates the access qualifier is compatible with the call. 751 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 752 // read_only and write_only, and assumed to be read_only if no qualifier is 753 // specified. 754 switch (Call->getDirectCallee()->getBuiltinID()) { 755 case Builtin::BIread_pipe: 756 case Builtin::BIreserve_read_pipe: 757 case Builtin::BIcommit_read_pipe: 758 case Builtin::BIwork_group_reserve_read_pipe: 759 case Builtin::BIsub_group_reserve_read_pipe: 760 case Builtin::BIwork_group_commit_read_pipe: 761 case Builtin::BIsub_group_commit_read_pipe: 762 if (!(!AccessQual || AccessQual->isReadOnly())) { 763 S.Diag(Arg0->getBeginLoc(), 764 diag::err_opencl_builtin_pipe_invalid_access_modifier) 765 << "read_only" << Arg0->getSourceRange(); 766 return true; 767 } 768 break; 769 case Builtin::BIwrite_pipe: 770 case Builtin::BIreserve_write_pipe: 771 case Builtin::BIcommit_write_pipe: 772 case Builtin::BIwork_group_reserve_write_pipe: 773 case Builtin::BIsub_group_reserve_write_pipe: 774 case Builtin::BIwork_group_commit_write_pipe: 775 case Builtin::BIsub_group_commit_write_pipe: 776 if (!(AccessQual && AccessQual->isWriteOnly())) { 777 S.Diag(Arg0->getBeginLoc(), 778 diag::err_opencl_builtin_pipe_invalid_access_modifier) 779 << "write_only" << Arg0->getSourceRange(); 780 return true; 781 } 782 break; 783 default: 784 break; 785 } 786 return false; 787 } 788 789 /// Returns true if pipe element type is different from the pointer. 790 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 791 const Expr *Arg0 = Call->getArg(0); 792 const Expr *ArgIdx = Call->getArg(Idx); 793 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 794 const QualType EltTy = PipeTy->getElementType(); 795 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 796 // The Idx argument should be a pointer and the type of the pointer and 797 // the type of pipe element should also be the same. 798 if (!ArgTy || 799 !S.Context.hasSameType( 800 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 801 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 802 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 803 << ArgIdx->getType() << ArgIdx->getSourceRange(); 804 return true; 805 } 806 return false; 807 } 808 809 // Performs semantic analysis for the read/write_pipe call. 810 // \param S Reference to the semantic analyzer. 811 // \param Call A pointer to the builtin call. 812 // \return True if a semantic error has been found, false otherwise. 813 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 814 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 815 // functions have two forms. 816 switch (Call->getNumArgs()) { 817 case 2: 818 if (checkOpenCLPipeArg(S, Call)) 819 return true; 820 // The call with 2 arguments should be 821 // read/write_pipe(pipe T, T*). 822 // Check packet type T. 823 if (checkOpenCLPipePacketType(S, Call, 1)) 824 return true; 825 break; 826 827 case 4: { 828 if (checkOpenCLPipeArg(S, Call)) 829 return true; 830 // The call with 4 arguments should be 831 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 832 // Check reserve_id_t. 833 if (!Call->getArg(1)->getType()->isReserveIDT()) { 834 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 835 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 836 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 837 return true; 838 } 839 840 // Check the index. 841 const Expr *Arg2 = Call->getArg(2); 842 if (!Arg2->getType()->isIntegerType() && 843 !Arg2->getType()->isUnsignedIntegerType()) { 844 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 845 << Call->getDirectCallee() << S.Context.UnsignedIntTy 846 << Arg2->getType() << Arg2->getSourceRange(); 847 return true; 848 } 849 850 // Check packet type T. 851 if (checkOpenCLPipePacketType(S, Call, 3)) 852 return true; 853 } break; 854 default: 855 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 856 << Call->getDirectCallee() << Call->getSourceRange(); 857 return true; 858 } 859 860 return false; 861 } 862 863 // Performs a semantic analysis on the {work_group_/sub_group_ 864 // /_}reserve_{read/write}_pipe 865 // \param S Reference to the semantic analyzer. 866 // \param Call The call to the builtin function to be analyzed. 867 // \return True if a semantic error was found, false otherwise. 868 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 869 if (checkArgCount(S, Call, 2)) 870 return true; 871 872 if (checkOpenCLPipeArg(S, Call)) 873 return true; 874 875 // Check the reserve size. 876 if (!Call->getArg(1)->getType()->isIntegerType() && 877 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 878 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 879 << Call->getDirectCallee() << S.Context.UnsignedIntTy 880 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 881 return true; 882 } 883 884 // Since return type of reserve_read/write_pipe built-in function is 885 // reserve_id_t, which is not defined in the builtin def file , we used int 886 // as return type and need to override the return type of these functions. 887 Call->setType(S.Context.OCLReserveIDTy); 888 889 return false; 890 } 891 892 // Performs a semantic analysis on {work_group_/sub_group_ 893 // /_}commit_{read/write}_pipe 894 // \param S Reference to the semantic analyzer. 895 // \param Call The call to the builtin function to be analyzed. 896 // \return True if a semantic error was found, false otherwise. 897 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 898 if (checkArgCount(S, Call, 2)) 899 return true; 900 901 if (checkOpenCLPipeArg(S, Call)) 902 return true; 903 904 // Check reserve_id_t. 905 if (!Call->getArg(1)->getType()->isReserveIDT()) { 906 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 907 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 908 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 909 return true; 910 } 911 912 return false; 913 } 914 915 // Performs a semantic analysis on the call to built-in Pipe 916 // Query Functions. 917 // \param S Reference to the semantic analyzer. 918 // \param Call The call to the builtin function to be analyzed. 919 // \return True if a semantic error was found, false otherwise. 920 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 921 if (checkArgCount(S, Call, 1)) 922 return true; 923 924 if (!Call->getArg(0)->getType()->isPipeType()) { 925 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 926 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 927 return true; 928 } 929 930 return false; 931 } 932 933 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 934 // Performs semantic analysis for the to_global/local/private call. 935 // \param S Reference to the semantic analyzer. 936 // \param BuiltinID ID of the builtin function. 937 // \param Call A pointer to the builtin call. 938 // \return True if a semantic error has been found, false otherwise. 939 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 940 CallExpr *Call) { 941 if (Call->getNumArgs() != 1) { 942 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 943 << Call->getDirectCallee() << Call->getSourceRange(); 944 return true; 945 } 946 947 auto RT = Call->getArg(0)->getType(); 948 if (!RT->isPointerType() || RT->getPointeeType() 949 .getAddressSpace() == LangAS::opencl_constant) { 950 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 951 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 952 return true; 953 } 954 955 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 956 S.Diag(Call->getArg(0)->getBeginLoc(), 957 diag::warn_opencl_generic_address_space_arg) 958 << Call->getDirectCallee()->getNameInfo().getAsString() 959 << Call->getArg(0)->getSourceRange(); 960 } 961 962 RT = RT->getPointeeType(); 963 auto Qual = RT.getQualifiers(); 964 switch (BuiltinID) { 965 case Builtin::BIto_global: 966 Qual.setAddressSpace(LangAS::opencl_global); 967 break; 968 case Builtin::BIto_local: 969 Qual.setAddressSpace(LangAS::opencl_local); 970 break; 971 case Builtin::BIto_private: 972 Qual.setAddressSpace(LangAS::opencl_private); 973 break; 974 default: 975 llvm_unreachable("Invalid builtin function"); 976 } 977 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 978 RT.getUnqualifiedType(), Qual))); 979 980 return false; 981 } 982 983 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 984 if (checkArgCount(S, TheCall, 1)) 985 return ExprError(); 986 987 // Compute __builtin_launder's parameter type from the argument. 988 // The parameter type is: 989 // * The type of the argument if it's not an array or function type, 990 // Otherwise, 991 // * The decayed argument type. 992 QualType ParamTy = [&]() { 993 QualType ArgTy = TheCall->getArg(0)->getType(); 994 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 995 return S.Context.getPointerType(Ty->getElementType()); 996 if (ArgTy->isFunctionType()) { 997 return S.Context.getPointerType(ArgTy); 998 } 999 return ArgTy; 1000 }(); 1001 1002 TheCall->setType(ParamTy); 1003 1004 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1005 if (!ParamTy->isPointerType()) 1006 return 0; 1007 if (ParamTy->isFunctionPointerType()) 1008 return 1; 1009 if (ParamTy->isVoidPointerType()) 1010 return 2; 1011 return llvm::Optional<unsigned>{}; 1012 }(); 1013 if (DiagSelect.hasValue()) { 1014 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1015 << DiagSelect.getValue() << TheCall->getSourceRange(); 1016 return ExprError(); 1017 } 1018 1019 // We either have an incomplete class type, or we have a class template 1020 // whose instantiation has not been forced. Example: 1021 // 1022 // template <class T> struct Foo { T value; }; 1023 // Foo<int> *p = nullptr; 1024 // auto *d = __builtin_launder(p); 1025 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1026 diag::err_incomplete_type)) 1027 return ExprError(); 1028 1029 assert(ParamTy->getPointeeType()->isObjectType() && 1030 "Unhandled non-object pointer case"); 1031 1032 InitializedEntity Entity = 1033 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1034 ExprResult Arg = 1035 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1036 if (Arg.isInvalid()) 1037 return ExprError(); 1038 TheCall->setArg(0, Arg.get()); 1039 1040 return TheCall; 1041 } 1042 1043 // Emit an error and return true if the current architecture is not in the list 1044 // of supported architectures. 1045 static bool 1046 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1047 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1048 llvm::Triple::ArchType CurArch = 1049 S.getASTContext().getTargetInfo().getTriple().getArch(); 1050 if (llvm::is_contained(SupportedArchs, CurArch)) 1051 return false; 1052 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1053 << TheCall->getSourceRange(); 1054 return true; 1055 } 1056 1057 ExprResult 1058 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1059 CallExpr *TheCall) { 1060 ExprResult TheCallResult(TheCall); 1061 1062 // Find out if any arguments are required to be integer constant expressions. 1063 unsigned ICEArguments = 0; 1064 ASTContext::GetBuiltinTypeError Error; 1065 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1066 if (Error != ASTContext::GE_None) 1067 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1068 1069 // If any arguments are required to be ICE's, check and diagnose. 1070 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1071 // Skip arguments not required to be ICE's. 1072 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1073 1074 llvm::APSInt Result; 1075 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1076 return true; 1077 ICEArguments &= ~(1 << ArgNo); 1078 } 1079 1080 switch (BuiltinID) { 1081 case Builtin::BI__builtin___CFStringMakeConstantString: 1082 assert(TheCall->getNumArgs() == 1 && 1083 "Wrong # arguments to builtin CFStringMakeConstantString"); 1084 if (CheckObjCString(TheCall->getArg(0))) 1085 return ExprError(); 1086 break; 1087 case Builtin::BI__builtin_ms_va_start: 1088 case Builtin::BI__builtin_stdarg_start: 1089 case Builtin::BI__builtin_va_start: 1090 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1091 return ExprError(); 1092 break; 1093 case Builtin::BI__va_start: { 1094 switch (Context.getTargetInfo().getTriple().getArch()) { 1095 case llvm::Triple::aarch64: 1096 case llvm::Triple::arm: 1097 case llvm::Triple::thumb: 1098 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1099 return ExprError(); 1100 break; 1101 default: 1102 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1103 return ExprError(); 1104 break; 1105 } 1106 break; 1107 } 1108 1109 // The acquire, release, and no fence variants are ARM and AArch64 only. 1110 case Builtin::BI_interlockedbittestandset_acq: 1111 case Builtin::BI_interlockedbittestandset_rel: 1112 case Builtin::BI_interlockedbittestandset_nf: 1113 case Builtin::BI_interlockedbittestandreset_acq: 1114 case Builtin::BI_interlockedbittestandreset_rel: 1115 case Builtin::BI_interlockedbittestandreset_nf: 1116 if (CheckBuiltinTargetSupport( 1117 *this, BuiltinID, TheCall, 1118 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1119 return ExprError(); 1120 break; 1121 1122 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1123 case Builtin::BI_bittest64: 1124 case Builtin::BI_bittestandcomplement64: 1125 case Builtin::BI_bittestandreset64: 1126 case Builtin::BI_bittestandset64: 1127 case Builtin::BI_interlockedbittestandreset64: 1128 case Builtin::BI_interlockedbittestandset64: 1129 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1130 {llvm::Triple::x86_64, llvm::Triple::arm, 1131 llvm::Triple::thumb, llvm::Triple::aarch64})) 1132 return ExprError(); 1133 break; 1134 1135 case Builtin::BI__builtin_isgreater: 1136 case Builtin::BI__builtin_isgreaterequal: 1137 case Builtin::BI__builtin_isless: 1138 case Builtin::BI__builtin_islessequal: 1139 case Builtin::BI__builtin_islessgreater: 1140 case Builtin::BI__builtin_isunordered: 1141 if (SemaBuiltinUnorderedCompare(TheCall)) 1142 return ExprError(); 1143 break; 1144 case Builtin::BI__builtin_fpclassify: 1145 if (SemaBuiltinFPClassification(TheCall, 6)) 1146 return ExprError(); 1147 break; 1148 case Builtin::BI__builtin_isfinite: 1149 case Builtin::BI__builtin_isinf: 1150 case Builtin::BI__builtin_isinf_sign: 1151 case Builtin::BI__builtin_isnan: 1152 case Builtin::BI__builtin_isnormal: 1153 case Builtin::BI__builtin_signbit: 1154 case Builtin::BI__builtin_signbitf: 1155 case Builtin::BI__builtin_signbitl: 1156 if (SemaBuiltinFPClassification(TheCall, 1)) 1157 return ExprError(); 1158 break; 1159 case Builtin::BI__builtin_shufflevector: 1160 return SemaBuiltinShuffleVector(TheCall); 1161 // TheCall will be freed by the smart pointer here, but that's fine, since 1162 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1163 case Builtin::BI__builtin_prefetch: 1164 if (SemaBuiltinPrefetch(TheCall)) 1165 return ExprError(); 1166 break; 1167 case Builtin::BI__builtin_alloca_with_align: 1168 if (SemaBuiltinAllocaWithAlign(TheCall)) 1169 return ExprError(); 1170 break; 1171 case Builtin::BI__assume: 1172 case Builtin::BI__builtin_assume: 1173 if (SemaBuiltinAssume(TheCall)) 1174 return ExprError(); 1175 break; 1176 case Builtin::BI__builtin_assume_aligned: 1177 if (SemaBuiltinAssumeAligned(TheCall)) 1178 return ExprError(); 1179 break; 1180 case Builtin::BI__builtin_dynamic_object_size: 1181 case Builtin::BI__builtin_object_size: 1182 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1183 return ExprError(); 1184 break; 1185 case Builtin::BI__builtin_longjmp: 1186 if (SemaBuiltinLongjmp(TheCall)) 1187 return ExprError(); 1188 break; 1189 case Builtin::BI__builtin_setjmp: 1190 if (SemaBuiltinSetjmp(TheCall)) 1191 return ExprError(); 1192 break; 1193 case Builtin::BI_setjmp: 1194 case Builtin::BI_setjmpex: 1195 if (checkArgCount(*this, TheCall, 1)) 1196 return true; 1197 break; 1198 case Builtin::BI__builtin_classify_type: 1199 if (checkArgCount(*this, TheCall, 1)) return true; 1200 TheCall->setType(Context.IntTy); 1201 break; 1202 case Builtin::BI__builtin_constant_p: { 1203 if (checkArgCount(*this, TheCall, 1)) return true; 1204 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1205 if (Arg.isInvalid()) return true; 1206 TheCall->setArg(0, Arg.get()); 1207 TheCall->setType(Context.IntTy); 1208 break; 1209 } 1210 case Builtin::BI__builtin_launder: 1211 return SemaBuiltinLaunder(*this, TheCall); 1212 case Builtin::BI__sync_fetch_and_add: 1213 case Builtin::BI__sync_fetch_and_add_1: 1214 case Builtin::BI__sync_fetch_and_add_2: 1215 case Builtin::BI__sync_fetch_and_add_4: 1216 case Builtin::BI__sync_fetch_and_add_8: 1217 case Builtin::BI__sync_fetch_and_add_16: 1218 case Builtin::BI__sync_fetch_and_sub: 1219 case Builtin::BI__sync_fetch_and_sub_1: 1220 case Builtin::BI__sync_fetch_and_sub_2: 1221 case Builtin::BI__sync_fetch_and_sub_4: 1222 case Builtin::BI__sync_fetch_and_sub_8: 1223 case Builtin::BI__sync_fetch_and_sub_16: 1224 case Builtin::BI__sync_fetch_and_or: 1225 case Builtin::BI__sync_fetch_and_or_1: 1226 case Builtin::BI__sync_fetch_and_or_2: 1227 case Builtin::BI__sync_fetch_and_or_4: 1228 case Builtin::BI__sync_fetch_and_or_8: 1229 case Builtin::BI__sync_fetch_and_or_16: 1230 case Builtin::BI__sync_fetch_and_and: 1231 case Builtin::BI__sync_fetch_and_and_1: 1232 case Builtin::BI__sync_fetch_and_and_2: 1233 case Builtin::BI__sync_fetch_and_and_4: 1234 case Builtin::BI__sync_fetch_and_and_8: 1235 case Builtin::BI__sync_fetch_and_and_16: 1236 case Builtin::BI__sync_fetch_and_xor: 1237 case Builtin::BI__sync_fetch_and_xor_1: 1238 case Builtin::BI__sync_fetch_and_xor_2: 1239 case Builtin::BI__sync_fetch_and_xor_4: 1240 case Builtin::BI__sync_fetch_and_xor_8: 1241 case Builtin::BI__sync_fetch_and_xor_16: 1242 case Builtin::BI__sync_fetch_and_nand: 1243 case Builtin::BI__sync_fetch_and_nand_1: 1244 case Builtin::BI__sync_fetch_and_nand_2: 1245 case Builtin::BI__sync_fetch_and_nand_4: 1246 case Builtin::BI__sync_fetch_and_nand_8: 1247 case Builtin::BI__sync_fetch_and_nand_16: 1248 case Builtin::BI__sync_add_and_fetch: 1249 case Builtin::BI__sync_add_and_fetch_1: 1250 case Builtin::BI__sync_add_and_fetch_2: 1251 case Builtin::BI__sync_add_and_fetch_4: 1252 case Builtin::BI__sync_add_and_fetch_8: 1253 case Builtin::BI__sync_add_and_fetch_16: 1254 case Builtin::BI__sync_sub_and_fetch: 1255 case Builtin::BI__sync_sub_and_fetch_1: 1256 case Builtin::BI__sync_sub_and_fetch_2: 1257 case Builtin::BI__sync_sub_and_fetch_4: 1258 case Builtin::BI__sync_sub_and_fetch_8: 1259 case Builtin::BI__sync_sub_and_fetch_16: 1260 case Builtin::BI__sync_and_and_fetch: 1261 case Builtin::BI__sync_and_and_fetch_1: 1262 case Builtin::BI__sync_and_and_fetch_2: 1263 case Builtin::BI__sync_and_and_fetch_4: 1264 case Builtin::BI__sync_and_and_fetch_8: 1265 case Builtin::BI__sync_and_and_fetch_16: 1266 case Builtin::BI__sync_or_and_fetch: 1267 case Builtin::BI__sync_or_and_fetch_1: 1268 case Builtin::BI__sync_or_and_fetch_2: 1269 case Builtin::BI__sync_or_and_fetch_4: 1270 case Builtin::BI__sync_or_and_fetch_8: 1271 case Builtin::BI__sync_or_and_fetch_16: 1272 case Builtin::BI__sync_xor_and_fetch: 1273 case Builtin::BI__sync_xor_and_fetch_1: 1274 case Builtin::BI__sync_xor_and_fetch_2: 1275 case Builtin::BI__sync_xor_and_fetch_4: 1276 case Builtin::BI__sync_xor_and_fetch_8: 1277 case Builtin::BI__sync_xor_and_fetch_16: 1278 case Builtin::BI__sync_nand_and_fetch: 1279 case Builtin::BI__sync_nand_and_fetch_1: 1280 case Builtin::BI__sync_nand_and_fetch_2: 1281 case Builtin::BI__sync_nand_and_fetch_4: 1282 case Builtin::BI__sync_nand_and_fetch_8: 1283 case Builtin::BI__sync_nand_and_fetch_16: 1284 case Builtin::BI__sync_val_compare_and_swap: 1285 case Builtin::BI__sync_val_compare_and_swap_1: 1286 case Builtin::BI__sync_val_compare_and_swap_2: 1287 case Builtin::BI__sync_val_compare_and_swap_4: 1288 case Builtin::BI__sync_val_compare_and_swap_8: 1289 case Builtin::BI__sync_val_compare_and_swap_16: 1290 case Builtin::BI__sync_bool_compare_and_swap: 1291 case Builtin::BI__sync_bool_compare_and_swap_1: 1292 case Builtin::BI__sync_bool_compare_and_swap_2: 1293 case Builtin::BI__sync_bool_compare_and_swap_4: 1294 case Builtin::BI__sync_bool_compare_and_swap_8: 1295 case Builtin::BI__sync_bool_compare_and_swap_16: 1296 case Builtin::BI__sync_lock_test_and_set: 1297 case Builtin::BI__sync_lock_test_and_set_1: 1298 case Builtin::BI__sync_lock_test_and_set_2: 1299 case Builtin::BI__sync_lock_test_and_set_4: 1300 case Builtin::BI__sync_lock_test_and_set_8: 1301 case Builtin::BI__sync_lock_test_and_set_16: 1302 case Builtin::BI__sync_lock_release: 1303 case Builtin::BI__sync_lock_release_1: 1304 case Builtin::BI__sync_lock_release_2: 1305 case Builtin::BI__sync_lock_release_4: 1306 case Builtin::BI__sync_lock_release_8: 1307 case Builtin::BI__sync_lock_release_16: 1308 case Builtin::BI__sync_swap: 1309 case Builtin::BI__sync_swap_1: 1310 case Builtin::BI__sync_swap_2: 1311 case Builtin::BI__sync_swap_4: 1312 case Builtin::BI__sync_swap_8: 1313 case Builtin::BI__sync_swap_16: 1314 return SemaBuiltinAtomicOverloaded(TheCallResult); 1315 case Builtin::BI__sync_synchronize: 1316 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1317 << TheCall->getCallee()->getSourceRange(); 1318 break; 1319 case Builtin::BI__builtin_nontemporal_load: 1320 case Builtin::BI__builtin_nontemporal_store: 1321 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1322 #define BUILTIN(ID, TYPE, ATTRS) 1323 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1324 case Builtin::BI##ID: \ 1325 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1326 #include "clang/Basic/Builtins.def" 1327 case Builtin::BI__annotation: 1328 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1329 return ExprError(); 1330 break; 1331 case Builtin::BI__builtin_annotation: 1332 if (SemaBuiltinAnnotation(*this, TheCall)) 1333 return ExprError(); 1334 break; 1335 case Builtin::BI__builtin_addressof: 1336 if (SemaBuiltinAddressof(*this, TheCall)) 1337 return ExprError(); 1338 break; 1339 case Builtin::BI__builtin_add_overflow: 1340 case Builtin::BI__builtin_sub_overflow: 1341 case Builtin::BI__builtin_mul_overflow: 1342 if (SemaBuiltinOverflow(*this, TheCall)) 1343 return ExprError(); 1344 break; 1345 case Builtin::BI__builtin_operator_new: 1346 case Builtin::BI__builtin_operator_delete: { 1347 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1348 ExprResult Res = 1349 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1350 if (Res.isInvalid()) 1351 CorrectDelayedTyposInExpr(TheCallResult.get()); 1352 return Res; 1353 } 1354 case Builtin::BI__builtin_dump_struct: { 1355 // We first want to ensure we are called with 2 arguments 1356 if (checkArgCount(*this, TheCall, 2)) 1357 return ExprError(); 1358 // Ensure that the first argument is of type 'struct XX *' 1359 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1360 const QualType PtrArgType = PtrArg->getType(); 1361 if (!PtrArgType->isPointerType() || 1362 !PtrArgType->getPointeeType()->isRecordType()) { 1363 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1364 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1365 << "structure pointer"; 1366 return ExprError(); 1367 } 1368 1369 // Ensure that the second argument is of type 'FunctionType' 1370 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1371 const QualType FnPtrArgType = FnPtrArg->getType(); 1372 if (!FnPtrArgType->isPointerType()) { 1373 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1374 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1375 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1376 return ExprError(); 1377 } 1378 1379 const auto *FuncType = 1380 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1381 1382 if (!FuncType) { 1383 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1384 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1385 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1386 return ExprError(); 1387 } 1388 1389 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1390 if (!FT->getNumParams()) { 1391 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1392 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1393 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1394 return ExprError(); 1395 } 1396 QualType PT = FT->getParamType(0); 1397 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1398 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1399 !PT->getPointeeType().isConstQualified()) { 1400 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1401 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1402 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1403 return ExprError(); 1404 } 1405 } 1406 1407 TheCall->setType(Context.IntTy); 1408 break; 1409 } 1410 case Builtin::BI__builtin_call_with_static_chain: 1411 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1412 return ExprError(); 1413 break; 1414 case Builtin::BI__exception_code: 1415 case Builtin::BI_exception_code: 1416 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1417 diag::err_seh___except_block)) 1418 return ExprError(); 1419 break; 1420 case Builtin::BI__exception_info: 1421 case Builtin::BI_exception_info: 1422 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1423 diag::err_seh___except_filter)) 1424 return ExprError(); 1425 break; 1426 case Builtin::BI__GetExceptionInfo: 1427 if (checkArgCount(*this, TheCall, 1)) 1428 return ExprError(); 1429 1430 if (CheckCXXThrowOperand( 1431 TheCall->getBeginLoc(), 1432 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1433 TheCall)) 1434 return ExprError(); 1435 1436 TheCall->setType(Context.VoidPtrTy); 1437 break; 1438 // OpenCL v2.0, s6.13.16 - Pipe functions 1439 case Builtin::BIread_pipe: 1440 case Builtin::BIwrite_pipe: 1441 // Since those two functions are declared with var args, we need a semantic 1442 // check for the argument. 1443 if (SemaBuiltinRWPipe(*this, TheCall)) 1444 return ExprError(); 1445 break; 1446 case Builtin::BIreserve_read_pipe: 1447 case Builtin::BIreserve_write_pipe: 1448 case Builtin::BIwork_group_reserve_read_pipe: 1449 case Builtin::BIwork_group_reserve_write_pipe: 1450 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1451 return ExprError(); 1452 break; 1453 case Builtin::BIsub_group_reserve_read_pipe: 1454 case Builtin::BIsub_group_reserve_write_pipe: 1455 if (checkOpenCLSubgroupExt(*this, TheCall) || 1456 SemaBuiltinReserveRWPipe(*this, TheCall)) 1457 return ExprError(); 1458 break; 1459 case Builtin::BIcommit_read_pipe: 1460 case Builtin::BIcommit_write_pipe: 1461 case Builtin::BIwork_group_commit_read_pipe: 1462 case Builtin::BIwork_group_commit_write_pipe: 1463 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1464 return ExprError(); 1465 break; 1466 case Builtin::BIsub_group_commit_read_pipe: 1467 case Builtin::BIsub_group_commit_write_pipe: 1468 if (checkOpenCLSubgroupExt(*this, TheCall) || 1469 SemaBuiltinCommitRWPipe(*this, TheCall)) 1470 return ExprError(); 1471 break; 1472 case Builtin::BIget_pipe_num_packets: 1473 case Builtin::BIget_pipe_max_packets: 1474 if (SemaBuiltinPipePackets(*this, TheCall)) 1475 return ExprError(); 1476 break; 1477 case Builtin::BIto_global: 1478 case Builtin::BIto_local: 1479 case Builtin::BIto_private: 1480 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1481 return ExprError(); 1482 break; 1483 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1484 case Builtin::BIenqueue_kernel: 1485 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1486 return ExprError(); 1487 break; 1488 case Builtin::BIget_kernel_work_group_size: 1489 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1490 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1491 return ExprError(); 1492 break; 1493 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1494 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1495 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1496 return ExprError(); 1497 break; 1498 case Builtin::BI__builtin_os_log_format: 1499 case Builtin::BI__builtin_os_log_format_buffer_size: 1500 if (SemaBuiltinOSLogFormat(TheCall)) 1501 return ExprError(); 1502 break; 1503 } 1504 1505 // Since the target specific builtins for each arch overlap, only check those 1506 // of the arch we are compiling for. 1507 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1508 switch (Context.getTargetInfo().getTriple().getArch()) { 1509 case llvm::Triple::arm: 1510 case llvm::Triple::armeb: 1511 case llvm::Triple::thumb: 1512 case llvm::Triple::thumbeb: 1513 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1514 return ExprError(); 1515 break; 1516 case llvm::Triple::aarch64: 1517 case llvm::Triple::aarch64_be: 1518 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1519 return ExprError(); 1520 break; 1521 case llvm::Triple::hexagon: 1522 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1523 return ExprError(); 1524 break; 1525 case llvm::Triple::mips: 1526 case llvm::Triple::mipsel: 1527 case llvm::Triple::mips64: 1528 case llvm::Triple::mips64el: 1529 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1530 return ExprError(); 1531 break; 1532 case llvm::Triple::systemz: 1533 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1534 return ExprError(); 1535 break; 1536 case llvm::Triple::x86: 1537 case llvm::Triple::x86_64: 1538 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1539 return ExprError(); 1540 break; 1541 case llvm::Triple::ppc: 1542 case llvm::Triple::ppc64: 1543 case llvm::Triple::ppc64le: 1544 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1545 return ExprError(); 1546 break; 1547 default: 1548 break; 1549 } 1550 } 1551 1552 return TheCallResult; 1553 } 1554 1555 // Get the valid immediate range for the specified NEON type code. 1556 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1557 NeonTypeFlags Type(t); 1558 int IsQuad = ForceQuad ? true : Type.isQuad(); 1559 switch (Type.getEltType()) { 1560 case NeonTypeFlags::Int8: 1561 case NeonTypeFlags::Poly8: 1562 return shift ? 7 : (8 << IsQuad) - 1; 1563 case NeonTypeFlags::Int16: 1564 case NeonTypeFlags::Poly16: 1565 return shift ? 15 : (4 << IsQuad) - 1; 1566 case NeonTypeFlags::Int32: 1567 return shift ? 31 : (2 << IsQuad) - 1; 1568 case NeonTypeFlags::Int64: 1569 case NeonTypeFlags::Poly64: 1570 return shift ? 63 : (1 << IsQuad) - 1; 1571 case NeonTypeFlags::Poly128: 1572 return shift ? 127 : (1 << IsQuad) - 1; 1573 case NeonTypeFlags::Float16: 1574 assert(!shift && "cannot shift float types!"); 1575 return (4 << IsQuad) - 1; 1576 case NeonTypeFlags::Float32: 1577 assert(!shift && "cannot shift float types!"); 1578 return (2 << IsQuad) - 1; 1579 case NeonTypeFlags::Float64: 1580 assert(!shift && "cannot shift float types!"); 1581 return (1 << IsQuad) - 1; 1582 } 1583 llvm_unreachable("Invalid NeonTypeFlag!"); 1584 } 1585 1586 /// getNeonEltType - Return the QualType corresponding to the elements of 1587 /// the vector type specified by the NeonTypeFlags. This is used to check 1588 /// the pointer arguments for Neon load/store intrinsics. 1589 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1590 bool IsPolyUnsigned, bool IsInt64Long) { 1591 switch (Flags.getEltType()) { 1592 case NeonTypeFlags::Int8: 1593 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1594 case NeonTypeFlags::Int16: 1595 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1596 case NeonTypeFlags::Int32: 1597 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1598 case NeonTypeFlags::Int64: 1599 if (IsInt64Long) 1600 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1601 else 1602 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1603 : Context.LongLongTy; 1604 case NeonTypeFlags::Poly8: 1605 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1606 case NeonTypeFlags::Poly16: 1607 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1608 case NeonTypeFlags::Poly64: 1609 if (IsInt64Long) 1610 return Context.UnsignedLongTy; 1611 else 1612 return Context.UnsignedLongLongTy; 1613 case NeonTypeFlags::Poly128: 1614 break; 1615 case NeonTypeFlags::Float16: 1616 return Context.HalfTy; 1617 case NeonTypeFlags::Float32: 1618 return Context.FloatTy; 1619 case NeonTypeFlags::Float64: 1620 return Context.DoubleTy; 1621 } 1622 llvm_unreachable("Invalid NeonTypeFlag!"); 1623 } 1624 1625 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1626 llvm::APSInt Result; 1627 uint64_t mask = 0; 1628 unsigned TV = 0; 1629 int PtrArgNum = -1; 1630 bool HasConstPtr = false; 1631 switch (BuiltinID) { 1632 #define GET_NEON_OVERLOAD_CHECK 1633 #include "clang/Basic/arm_neon.inc" 1634 #include "clang/Basic/arm_fp16.inc" 1635 #undef GET_NEON_OVERLOAD_CHECK 1636 } 1637 1638 // For NEON intrinsics which are overloaded on vector element type, validate 1639 // the immediate which specifies which variant to emit. 1640 unsigned ImmArg = TheCall->getNumArgs()-1; 1641 if (mask) { 1642 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1643 return true; 1644 1645 TV = Result.getLimitedValue(64); 1646 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1647 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1648 << TheCall->getArg(ImmArg)->getSourceRange(); 1649 } 1650 1651 if (PtrArgNum >= 0) { 1652 // Check that pointer arguments have the specified type. 1653 Expr *Arg = TheCall->getArg(PtrArgNum); 1654 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1655 Arg = ICE->getSubExpr(); 1656 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1657 QualType RHSTy = RHS.get()->getType(); 1658 1659 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1660 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1661 Arch == llvm::Triple::aarch64_be; 1662 bool IsInt64Long = 1663 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1664 QualType EltTy = 1665 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1666 if (HasConstPtr) 1667 EltTy = EltTy.withConst(); 1668 QualType LHSTy = Context.getPointerType(EltTy); 1669 AssignConvertType ConvTy; 1670 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1671 if (RHS.isInvalid()) 1672 return true; 1673 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1674 RHS.get(), AA_Assigning)) 1675 return true; 1676 } 1677 1678 // For NEON intrinsics which take an immediate value as part of the 1679 // instruction, range check them here. 1680 unsigned i = 0, l = 0, u = 0; 1681 switch (BuiltinID) { 1682 default: 1683 return false; 1684 #define GET_NEON_IMMEDIATE_CHECK 1685 #include "clang/Basic/arm_neon.inc" 1686 #include "clang/Basic/arm_fp16.inc" 1687 #undef GET_NEON_IMMEDIATE_CHECK 1688 } 1689 1690 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1691 } 1692 1693 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1694 unsigned MaxWidth) { 1695 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1696 BuiltinID == ARM::BI__builtin_arm_ldaex || 1697 BuiltinID == ARM::BI__builtin_arm_strex || 1698 BuiltinID == ARM::BI__builtin_arm_stlex || 1699 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1700 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1701 BuiltinID == AArch64::BI__builtin_arm_strex || 1702 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1703 "unexpected ARM builtin"); 1704 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1705 BuiltinID == ARM::BI__builtin_arm_ldaex || 1706 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1707 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1708 1709 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1710 1711 // Ensure that we have the proper number of arguments. 1712 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1713 return true; 1714 1715 // Inspect the pointer argument of the atomic builtin. This should always be 1716 // a pointer type, whose element is an integral scalar or pointer type. 1717 // Because it is a pointer type, we don't have to worry about any implicit 1718 // casts here. 1719 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1720 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1721 if (PointerArgRes.isInvalid()) 1722 return true; 1723 PointerArg = PointerArgRes.get(); 1724 1725 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1726 if (!pointerType) { 1727 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1728 << PointerArg->getType() << PointerArg->getSourceRange(); 1729 return true; 1730 } 1731 1732 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1733 // task is to insert the appropriate casts into the AST. First work out just 1734 // what the appropriate type is. 1735 QualType ValType = pointerType->getPointeeType(); 1736 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1737 if (IsLdrex) 1738 AddrType.addConst(); 1739 1740 // Issue a warning if the cast is dodgy. 1741 CastKind CastNeeded = CK_NoOp; 1742 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1743 CastNeeded = CK_BitCast; 1744 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1745 << PointerArg->getType() << Context.getPointerType(AddrType) 1746 << AA_Passing << PointerArg->getSourceRange(); 1747 } 1748 1749 // Finally, do the cast and replace the argument with the corrected version. 1750 AddrType = Context.getPointerType(AddrType); 1751 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1752 if (PointerArgRes.isInvalid()) 1753 return true; 1754 PointerArg = PointerArgRes.get(); 1755 1756 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1757 1758 // In general, we allow ints, floats and pointers to be loaded and stored. 1759 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1760 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1761 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1762 << PointerArg->getType() << PointerArg->getSourceRange(); 1763 return true; 1764 } 1765 1766 // But ARM doesn't have instructions to deal with 128-bit versions. 1767 if (Context.getTypeSize(ValType) > MaxWidth) { 1768 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1769 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1770 << PointerArg->getType() << PointerArg->getSourceRange(); 1771 return true; 1772 } 1773 1774 switch (ValType.getObjCLifetime()) { 1775 case Qualifiers::OCL_None: 1776 case Qualifiers::OCL_ExplicitNone: 1777 // okay 1778 break; 1779 1780 case Qualifiers::OCL_Weak: 1781 case Qualifiers::OCL_Strong: 1782 case Qualifiers::OCL_Autoreleasing: 1783 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1784 << ValType << PointerArg->getSourceRange(); 1785 return true; 1786 } 1787 1788 if (IsLdrex) { 1789 TheCall->setType(ValType); 1790 return false; 1791 } 1792 1793 // Initialize the argument to be stored. 1794 ExprResult ValArg = TheCall->getArg(0); 1795 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1796 Context, ValType, /*consume*/ false); 1797 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1798 if (ValArg.isInvalid()) 1799 return true; 1800 TheCall->setArg(0, ValArg.get()); 1801 1802 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1803 // but the custom checker bypasses all default analysis. 1804 TheCall->setType(Context.IntTy); 1805 return false; 1806 } 1807 1808 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1809 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1810 BuiltinID == ARM::BI__builtin_arm_ldaex || 1811 BuiltinID == ARM::BI__builtin_arm_strex || 1812 BuiltinID == ARM::BI__builtin_arm_stlex) { 1813 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1814 } 1815 1816 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1817 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1818 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1819 } 1820 1821 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1822 BuiltinID == ARM::BI__builtin_arm_wsr64) 1823 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1824 1825 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1826 BuiltinID == ARM::BI__builtin_arm_rsrp || 1827 BuiltinID == ARM::BI__builtin_arm_wsr || 1828 BuiltinID == ARM::BI__builtin_arm_wsrp) 1829 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1830 1831 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1832 return true; 1833 1834 // For intrinsics which take an immediate value as part of the instruction, 1835 // range check them here. 1836 // FIXME: VFP Intrinsics should error if VFP not present. 1837 switch (BuiltinID) { 1838 default: return false; 1839 case ARM::BI__builtin_arm_ssat: 1840 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1841 case ARM::BI__builtin_arm_usat: 1842 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1843 case ARM::BI__builtin_arm_ssat16: 1844 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1845 case ARM::BI__builtin_arm_usat16: 1846 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1847 case ARM::BI__builtin_arm_vcvtr_f: 1848 case ARM::BI__builtin_arm_vcvtr_d: 1849 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1850 case ARM::BI__builtin_arm_dmb: 1851 case ARM::BI__builtin_arm_dsb: 1852 case ARM::BI__builtin_arm_isb: 1853 case ARM::BI__builtin_arm_dbg: 1854 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1855 } 1856 } 1857 1858 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1859 CallExpr *TheCall) { 1860 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1861 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1862 BuiltinID == AArch64::BI__builtin_arm_strex || 1863 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1864 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1865 } 1866 1867 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1868 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1869 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1870 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1871 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1872 } 1873 1874 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1875 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1876 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1877 1878 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1879 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1880 BuiltinID == AArch64::BI__builtin_arm_wsr || 1881 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1882 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1883 1884 // Only check the valid encoding range. Any constant in this range would be 1885 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1886 // an exception for incorrect registers. This matches MSVC behavior. 1887 if (BuiltinID == AArch64::BI_ReadStatusReg || 1888 BuiltinID == AArch64::BI_WriteStatusReg) 1889 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1890 1891 if (BuiltinID == AArch64::BI__getReg) 1892 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1893 1894 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1895 return true; 1896 1897 // For intrinsics which take an immediate value as part of the instruction, 1898 // range check them here. 1899 unsigned i = 0, l = 0, u = 0; 1900 switch (BuiltinID) { 1901 default: return false; 1902 case AArch64::BI__builtin_arm_dmb: 1903 case AArch64::BI__builtin_arm_dsb: 1904 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1905 } 1906 1907 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1908 } 1909 1910 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1911 struct BuiltinAndString { 1912 unsigned BuiltinID; 1913 const char *Str; 1914 }; 1915 1916 static BuiltinAndString ValidCPU[] = { 1917 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 1918 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 1919 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 1920 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 1921 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 1922 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 1923 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 1924 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 1925 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 1926 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 1927 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 1928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 1929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 1930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 1931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 1932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 1933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 1934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 1935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 1936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 1937 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 1938 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 1939 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 1940 }; 1941 1942 static BuiltinAndString ValidHVX[] = { 1943 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 1944 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 1945 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 1946 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 1947 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 1948 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 1949 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 1950 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 1951 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 1952 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 1953 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 1954 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 1955 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 1956 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 1957 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 1958 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 1959 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 1960 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 1961 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 1962 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 1963 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 1964 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 1965 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 1966 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 1967 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 1968 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 1969 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2605 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2606 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2607 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2608 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2609 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2610 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2611 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2612 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2613 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2614 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2615 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2616 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2617 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2618 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2619 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2620 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2621 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2622 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2623 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2624 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2625 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2626 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2627 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2628 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2629 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2630 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2631 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2632 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2633 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2634 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2635 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2636 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2637 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2638 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2639 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2640 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2641 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2642 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2643 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2644 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2645 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2646 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2647 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2648 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2649 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2650 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2651 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2652 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2653 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2654 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2655 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2656 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2657 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2658 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2659 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2660 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2661 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2662 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2663 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2664 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2665 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2666 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2667 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2668 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2669 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2670 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2671 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2672 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2673 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2674 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2675 }; 2676 2677 // Sort the tables on first execution so we can binary search them. 2678 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2679 return LHS.BuiltinID < RHS.BuiltinID; 2680 }; 2681 static const bool SortOnce = 2682 (llvm::sort(ValidCPU, SortCmp), 2683 llvm::sort(ValidHVX, SortCmp), true); 2684 (void)SortOnce; 2685 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2686 return BI.BuiltinID < BuiltinID; 2687 }; 2688 2689 const TargetInfo &TI = Context.getTargetInfo(); 2690 2691 const BuiltinAndString *FC = 2692 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID, 2693 LowerBoundCmp); 2694 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2695 const TargetOptions &Opts = TI.getTargetOpts(); 2696 StringRef CPU = Opts.CPU; 2697 if (!CPU.empty()) { 2698 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2699 CPU.consume_front("hexagon"); 2700 SmallVector<StringRef, 3> CPUs; 2701 StringRef(FC->Str).split(CPUs, ','); 2702 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2703 return Diag(TheCall->getBeginLoc(), 2704 diag::err_hexagon_builtin_unsupported_cpu); 2705 } 2706 } 2707 2708 const BuiltinAndString *FH = 2709 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID, 2710 LowerBoundCmp); 2711 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2712 if (!TI.hasFeature("hvx")) 2713 return Diag(TheCall->getBeginLoc(), 2714 diag::err_hexagon_builtin_requires_hvx); 2715 2716 SmallVector<StringRef, 3> HVXs; 2717 StringRef(FH->Str).split(HVXs, ','); 2718 bool IsValid = llvm::any_of(HVXs, 2719 [&TI] (StringRef V) { 2720 std::string F = "hvx" + V.str(); 2721 return TI.hasFeature(F); 2722 }); 2723 if (!IsValid) 2724 return Diag(TheCall->getBeginLoc(), 2725 diag::err_hexagon_builtin_unsupported_hvx); 2726 } 2727 2728 return false; 2729 } 2730 2731 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2732 struct ArgInfo { 2733 uint8_t OpNum; 2734 bool IsSigned; 2735 uint8_t BitWidth; 2736 uint8_t Align; 2737 }; 2738 struct BuiltinInfo { 2739 unsigned BuiltinID; 2740 ArgInfo Infos[2]; 2741 }; 2742 2743 static BuiltinInfo Infos[] = { 2744 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2745 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2746 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2747 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2748 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2749 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2750 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2751 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2752 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2753 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2754 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2755 2756 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2761 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2763 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2767 2768 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2773 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2776 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2820 {{ 1, false, 6, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2828 {{ 1, false, 5, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2835 { 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2837 { 2, false, 6, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2839 { 3, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2841 { 3, false, 6, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2858 {{ 2, false, 4, 0 }, 2859 { 3, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2861 {{ 2, false, 4, 0 }, 2862 { 3, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2864 {{ 2, false, 4, 0 }, 2865 { 3, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2867 {{ 2, false, 4, 0 }, 2868 { 3, false, 5, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2880 { 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2882 { 2, false, 6, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2892 {{ 1, false, 4, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2895 {{ 1, false, 4, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2916 {{ 3, false, 1, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2921 {{ 3, false, 1, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2926 {{ 3, false, 1, 0 }} }, 2927 }; 2928 2929 // Use a dynamically initialized static to sort the table exactly once on 2930 // first run. 2931 static const bool SortOnce = 2932 (llvm::sort(Infos, 2933 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2934 return LHS.BuiltinID < RHS.BuiltinID; 2935 }), 2936 true); 2937 (void)SortOnce; 2938 2939 const BuiltinInfo *F = 2940 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID, 2941 [](const BuiltinInfo &BI, unsigned BuiltinID) { 2942 return BI.BuiltinID < BuiltinID; 2943 }); 2944 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2945 return false; 2946 2947 bool Error = false; 2948 2949 for (const ArgInfo &A : F->Infos) { 2950 // Ignore empty ArgInfo elements. 2951 if (A.BitWidth == 0) 2952 continue; 2953 2954 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2955 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2956 if (!A.Align) { 2957 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2958 } else { 2959 unsigned M = 1 << A.Align; 2960 Min *= M; 2961 Max *= M; 2962 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2963 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2964 } 2965 } 2966 return Error; 2967 } 2968 2969 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2970 CallExpr *TheCall) { 2971 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2972 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2973 } 2974 2975 2976 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2977 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2978 // ordering for DSP is unspecified. MSA is ordered by the data format used 2979 // by the underlying instruction i.e., df/m, df/n and then by size. 2980 // 2981 // FIXME: The size tests here should instead be tablegen'd along with the 2982 // definitions from include/clang/Basic/BuiltinsMips.def. 2983 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2984 // be too. 2985 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2986 unsigned i = 0, l = 0, u = 0, m = 0; 2987 switch (BuiltinID) { 2988 default: return false; 2989 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2990 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2991 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2992 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2993 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2994 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2995 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2996 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2997 // df/m field. 2998 // These intrinsics take an unsigned 3 bit immediate. 2999 case Mips::BI__builtin_msa_bclri_b: 3000 case Mips::BI__builtin_msa_bnegi_b: 3001 case Mips::BI__builtin_msa_bseti_b: 3002 case Mips::BI__builtin_msa_sat_s_b: 3003 case Mips::BI__builtin_msa_sat_u_b: 3004 case Mips::BI__builtin_msa_slli_b: 3005 case Mips::BI__builtin_msa_srai_b: 3006 case Mips::BI__builtin_msa_srari_b: 3007 case Mips::BI__builtin_msa_srli_b: 3008 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3009 case Mips::BI__builtin_msa_binsli_b: 3010 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3011 // These intrinsics take an unsigned 4 bit immediate. 3012 case Mips::BI__builtin_msa_bclri_h: 3013 case Mips::BI__builtin_msa_bnegi_h: 3014 case Mips::BI__builtin_msa_bseti_h: 3015 case Mips::BI__builtin_msa_sat_s_h: 3016 case Mips::BI__builtin_msa_sat_u_h: 3017 case Mips::BI__builtin_msa_slli_h: 3018 case Mips::BI__builtin_msa_srai_h: 3019 case Mips::BI__builtin_msa_srari_h: 3020 case Mips::BI__builtin_msa_srli_h: 3021 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3022 case Mips::BI__builtin_msa_binsli_h: 3023 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3024 // These intrinsics take an unsigned 5 bit immediate. 3025 // The first block of intrinsics actually have an unsigned 5 bit field, 3026 // not a df/n field. 3027 case Mips::BI__builtin_msa_clei_u_b: 3028 case Mips::BI__builtin_msa_clei_u_h: 3029 case Mips::BI__builtin_msa_clei_u_w: 3030 case Mips::BI__builtin_msa_clei_u_d: 3031 case Mips::BI__builtin_msa_clti_u_b: 3032 case Mips::BI__builtin_msa_clti_u_h: 3033 case Mips::BI__builtin_msa_clti_u_w: 3034 case Mips::BI__builtin_msa_clti_u_d: 3035 case Mips::BI__builtin_msa_maxi_u_b: 3036 case Mips::BI__builtin_msa_maxi_u_h: 3037 case Mips::BI__builtin_msa_maxi_u_w: 3038 case Mips::BI__builtin_msa_maxi_u_d: 3039 case Mips::BI__builtin_msa_mini_u_b: 3040 case Mips::BI__builtin_msa_mini_u_h: 3041 case Mips::BI__builtin_msa_mini_u_w: 3042 case Mips::BI__builtin_msa_mini_u_d: 3043 case Mips::BI__builtin_msa_addvi_b: 3044 case Mips::BI__builtin_msa_addvi_h: 3045 case Mips::BI__builtin_msa_addvi_w: 3046 case Mips::BI__builtin_msa_addvi_d: 3047 case Mips::BI__builtin_msa_bclri_w: 3048 case Mips::BI__builtin_msa_bnegi_w: 3049 case Mips::BI__builtin_msa_bseti_w: 3050 case Mips::BI__builtin_msa_sat_s_w: 3051 case Mips::BI__builtin_msa_sat_u_w: 3052 case Mips::BI__builtin_msa_slli_w: 3053 case Mips::BI__builtin_msa_srai_w: 3054 case Mips::BI__builtin_msa_srari_w: 3055 case Mips::BI__builtin_msa_srli_w: 3056 case Mips::BI__builtin_msa_srlri_w: 3057 case Mips::BI__builtin_msa_subvi_b: 3058 case Mips::BI__builtin_msa_subvi_h: 3059 case Mips::BI__builtin_msa_subvi_w: 3060 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3061 case Mips::BI__builtin_msa_binsli_w: 3062 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3063 // These intrinsics take an unsigned 6 bit immediate. 3064 case Mips::BI__builtin_msa_bclri_d: 3065 case Mips::BI__builtin_msa_bnegi_d: 3066 case Mips::BI__builtin_msa_bseti_d: 3067 case Mips::BI__builtin_msa_sat_s_d: 3068 case Mips::BI__builtin_msa_sat_u_d: 3069 case Mips::BI__builtin_msa_slli_d: 3070 case Mips::BI__builtin_msa_srai_d: 3071 case Mips::BI__builtin_msa_srari_d: 3072 case Mips::BI__builtin_msa_srli_d: 3073 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3074 case Mips::BI__builtin_msa_binsli_d: 3075 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3076 // These intrinsics take a signed 5 bit immediate. 3077 case Mips::BI__builtin_msa_ceqi_b: 3078 case Mips::BI__builtin_msa_ceqi_h: 3079 case Mips::BI__builtin_msa_ceqi_w: 3080 case Mips::BI__builtin_msa_ceqi_d: 3081 case Mips::BI__builtin_msa_clti_s_b: 3082 case Mips::BI__builtin_msa_clti_s_h: 3083 case Mips::BI__builtin_msa_clti_s_w: 3084 case Mips::BI__builtin_msa_clti_s_d: 3085 case Mips::BI__builtin_msa_clei_s_b: 3086 case Mips::BI__builtin_msa_clei_s_h: 3087 case Mips::BI__builtin_msa_clei_s_w: 3088 case Mips::BI__builtin_msa_clei_s_d: 3089 case Mips::BI__builtin_msa_maxi_s_b: 3090 case Mips::BI__builtin_msa_maxi_s_h: 3091 case Mips::BI__builtin_msa_maxi_s_w: 3092 case Mips::BI__builtin_msa_maxi_s_d: 3093 case Mips::BI__builtin_msa_mini_s_b: 3094 case Mips::BI__builtin_msa_mini_s_h: 3095 case Mips::BI__builtin_msa_mini_s_w: 3096 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3097 // These intrinsics take an unsigned 8 bit immediate. 3098 case Mips::BI__builtin_msa_andi_b: 3099 case Mips::BI__builtin_msa_nori_b: 3100 case Mips::BI__builtin_msa_ori_b: 3101 case Mips::BI__builtin_msa_shf_b: 3102 case Mips::BI__builtin_msa_shf_h: 3103 case Mips::BI__builtin_msa_shf_w: 3104 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3105 case Mips::BI__builtin_msa_bseli_b: 3106 case Mips::BI__builtin_msa_bmnzi_b: 3107 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3108 // df/n format 3109 // These intrinsics take an unsigned 4 bit immediate. 3110 case Mips::BI__builtin_msa_copy_s_b: 3111 case Mips::BI__builtin_msa_copy_u_b: 3112 case Mips::BI__builtin_msa_insve_b: 3113 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3114 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3115 // These intrinsics take an unsigned 3 bit immediate. 3116 case Mips::BI__builtin_msa_copy_s_h: 3117 case Mips::BI__builtin_msa_copy_u_h: 3118 case Mips::BI__builtin_msa_insve_h: 3119 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3120 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3121 // These intrinsics take an unsigned 2 bit immediate. 3122 case Mips::BI__builtin_msa_copy_s_w: 3123 case Mips::BI__builtin_msa_copy_u_w: 3124 case Mips::BI__builtin_msa_insve_w: 3125 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3126 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3127 // These intrinsics take an unsigned 1 bit immediate. 3128 case Mips::BI__builtin_msa_copy_s_d: 3129 case Mips::BI__builtin_msa_copy_u_d: 3130 case Mips::BI__builtin_msa_insve_d: 3131 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3132 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3133 // Memory offsets and immediate loads. 3134 // These intrinsics take a signed 10 bit immediate. 3135 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3136 case Mips::BI__builtin_msa_ldi_h: 3137 case Mips::BI__builtin_msa_ldi_w: 3138 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3139 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3140 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3141 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3142 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3143 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3144 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3145 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3146 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3147 } 3148 3149 if (!m) 3150 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3151 3152 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3153 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3154 } 3155 3156 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3157 unsigned i = 0, l = 0, u = 0; 3158 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3159 BuiltinID == PPC::BI__builtin_divdeu || 3160 BuiltinID == PPC::BI__builtin_bpermd; 3161 bool IsTarget64Bit = Context.getTargetInfo() 3162 .getTypeWidth(Context 3163 .getTargetInfo() 3164 .getIntPtrType()) == 64; 3165 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3166 BuiltinID == PPC::BI__builtin_divweu || 3167 BuiltinID == PPC::BI__builtin_divde || 3168 BuiltinID == PPC::BI__builtin_divdeu; 3169 3170 if (Is64BitBltin && !IsTarget64Bit) 3171 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3172 << TheCall->getSourceRange(); 3173 3174 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3175 (BuiltinID == PPC::BI__builtin_bpermd && 3176 !Context.getTargetInfo().hasFeature("bpermd"))) 3177 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3178 << TheCall->getSourceRange(); 3179 3180 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3181 if (!Context.getTargetInfo().hasFeature("vsx")) 3182 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3183 << TheCall->getSourceRange(); 3184 return false; 3185 }; 3186 3187 switch (BuiltinID) { 3188 default: return false; 3189 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3190 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3191 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3192 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3193 case PPC::BI__builtin_tbegin: 3194 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3195 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3196 case PPC::BI__builtin_tabortwc: 3197 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3198 case PPC::BI__builtin_tabortwci: 3199 case PPC::BI__builtin_tabortdci: 3200 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3201 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3202 case PPC::BI__builtin_vsx_xxpermdi: 3203 case PPC::BI__builtin_vsx_xxsldwi: 3204 return SemaBuiltinVSX(TheCall); 3205 case PPC::BI__builtin_unpack_vector_int128: 3206 return SemaVSXCheck(TheCall) || 3207 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3208 case PPC::BI__builtin_pack_vector_int128: 3209 return SemaVSXCheck(TheCall); 3210 } 3211 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3212 } 3213 3214 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3215 CallExpr *TheCall) { 3216 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3217 Expr *Arg = TheCall->getArg(0); 3218 llvm::APSInt AbortCode(32); 3219 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3220 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3221 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3222 << Arg->getSourceRange(); 3223 } 3224 3225 // For intrinsics which take an immediate value as part of the instruction, 3226 // range check them here. 3227 unsigned i = 0, l = 0, u = 0; 3228 switch (BuiltinID) { 3229 default: return false; 3230 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3231 case SystemZ::BI__builtin_s390_verimb: 3232 case SystemZ::BI__builtin_s390_verimh: 3233 case SystemZ::BI__builtin_s390_verimf: 3234 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3235 case SystemZ::BI__builtin_s390_vfaeb: 3236 case SystemZ::BI__builtin_s390_vfaeh: 3237 case SystemZ::BI__builtin_s390_vfaef: 3238 case SystemZ::BI__builtin_s390_vfaebs: 3239 case SystemZ::BI__builtin_s390_vfaehs: 3240 case SystemZ::BI__builtin_s390_vfaefs: 3241 case SystemZ::BI__builtin_s390_vfaezb: 3242 case SystemZ::BI__builtin_s390_vfaezh: 3243 case SystemZ::BI__builtin_s390_vfaezf: 3244 case SystemZ::BI__builtin_s390_vfaezbs: 3245 case SystemZ::BI__builtin_s390_vfaezhs: 3246 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3247 case SystemZ::BI__builtin_s390_vfisb: 3248 case SystemZ::BI__builtin_s390_vfidb: 3249 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3250 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3251 case SystemZ::BI__builtin_s390_vftcisb: 3252 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3253 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3254 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3255 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3256 case SystemZ::BI__builtin_s390_vstrcb: 3257 case SystemZ::BI__builtin_s390_vstrch: 3258 case SystemZ::BI__builtin_s390_vstrcf: 3259 case SystemZ::BI__builtin_s390_vstrczb: 3260 case SystemZ::BI__builtin_s390_vstrczh: 3261 case SystemZ::BI__builtin_s390_vstrczf: 3262 case SystemZ::BI__builtin_s390_vstrcbs: 3263 case SystemZ::BI__builtin_s390_vstrchs: 3264 case SystemZ::BI__builtin_s390_vstrcfs: 3265 case SystemZ::BI__builtin_s390_vstrczbs: 3266 case SystemZ::BI__builtin_s390_vstrczhs: 3267 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3268 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3269 case SystemZ::BI__builtin_s390_vfminsb: 3270 case SystemZ::BI__builtin_s390_vfmaxsb: 3271 case SystemZ::BI__builtin_s390_vfmindb: 3272 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3273 } 3274 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3275 } 3276 3277 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3278 /// This checks that the target supports __builtin_cpu_supports and 3279 /// that the string argument is constant and valid. 3280 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3281 Expr *Arg = TheCall->getArg(0); 3282 3283 // Check if the argument is a string literal. 3284 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3285 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3286 << Arg->getSourceRange(); 3287 3288 // Check the contents of the string. 3289 StringRef Feature = 3290 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3291 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3292 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3293 << Arg->getSourceRange(); 3294 return false; 3295 } 3296 3297 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3298 /// This checks that the target supports __builtin_cpu_is and 3299 /// that the string argument is constant and valid. 3300 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3301 Expr *Arg = TheCall->getArg(0); 3302 3303 // Check if the argument is a string literal. 3304 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3305 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3306 << Arg->getSourceRange(); 3307 3308 // Check the contents of the string. 3309 StringRef Feature = 3310 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3311 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3312 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3313 << Arg->getSourceRange(); 3314 return false; 3315 } 3316 3317 // Check if the rounding mode is legal. 3318 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3319 // Indicates if this instruction has rounding control or just SAE. 3320 bool HasRC = false; 3321 3322 unsigned ArgNum = 0; 3323 switch (BuiltinID) { 3324 default: 3325 return false; 3326 case X86::BI__builtin_ia32_vcvttsd2si32: 3327 case X86::BI__builtin_ia32_vcvttsd2si64: 3328 case X86::BI__builtin_ia32_vcvttsd2usi32: 3329 case X86::BI__builtin_ia32_vcvttsd2usi64: 3330 case X86::BI__builtin_ia32_vcvttss2si32: 3331 case X86::BI__builtin_ia32_vcvttss2si64: 3332 case X86::BI__builtin_ia32_vcvttss2usi32: 3333 case X86::BI__builtin_ia32_vcvttss2usi64: 3334 ArgNum = 1; 3335 break; 3336 case X86::BI__builtin_ia32_maxpd512: 3337 case X86::BI__builtin_ia32_maxps512: 3338 case X86::BI__builtin_ia32_minpd512: 3339 case X86::BI__builtin_ia32_minps512: 3340 ArgNum = 2; 3341 break; 3342 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3343 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3344 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3345 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3346 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3347 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3348 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3349 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3350 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3351 case X86::BI__builtin_ia32_exp2pd_mask: 3352 case X86::BI__builtin_ia32_exp2ps_mask: 3353 case X86::BI__builtin_ia32_getexppd512_mask: 3354 case X86::BI__builtin_ia32_getexpps512_mask: 3355 case X86::BI__builtin_ia32_rcp28pd_mask: 3356 case X86::BI__builtin_ia32_rcp28ps_mask: 3357 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3358 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3359 case X86::BI__builtin_ia32_vcomisd: 3360 case X86::BI__builtin_ia32_vcomiss: 3361 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3362 ArgNum = 3; 3363 break; 3364 case X86::BI__builtin_ia32_cmppd512_mask: 3365 case X86::BI__builtin_ia32_cmpps512_mask: 3366 case X86::BI__builtin_ia32_cmpsd_mask: 3367 case X86::BI__builtin_ia32_cmpss_mask: 3368 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3369 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3370 case X86::BI__builtin_ia32_getexpss128_round_mask: 3371 case X86::BI__builtin_ia32_maxsd_round_mask: 3372 case X86::BI__builtin_ia32_maxss_round_mask: 3373 case X86::BI__builtin_ia32_minsd_round_mask: 3374 case X86::BI__builtin_ia32_minss_round_mask: 3375 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3376 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3377 case X86::BI__builtin_ia32_reducepd512_mask: 3378 case X86::BI__builtin_ia32_reduceps512_mask: 3379 case X86::BI__builtin_ia32_rndscalepd_mask: 3380 case X86::BI__builtin_ia32_rndscaleps_mask: 3381 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3382 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3383 ArgNum = 4; 3384 break; 3385 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3386 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3387 case X86::BI__builtin_ia32_fixupimmps512_mask: 3388 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3389 case X86::BI__builtin_ia32_fixupimmsd_mask: 3390 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3391 case X86::BI__builtin_ia32_fixupimmss_mask: 3392 case X86::BI__builtin_ia32_fixupimmss_maskz: 3393 case X86::BI__builtin_ia32_rangepd512_mask: 3394 case X86::BI__builtin_ia32_rangeps512_mask: 3395 case X86::BI__builtin_ia32_rangesd128_round_mask: 3396 case X86::BI__builtin_ia32_rangess128_round_mask: 3397 case X86::BI__builtin_ia32_reducesd_mask: 3398 case X86::BI__builtin_ia32_reducess_mask: 3399 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3400 case X86::BI__builtin_ia32_rndscaless_round_mask: 3401 ArgNum = 5; 3402 break; 3403 case X86::BI__builtin_ia32_vcvtsd2si64: 3404 case X86::BI__builtin_ia32_vcvtsd2si32: 3405 case X86::BI__builtin_ia32_vcvtsd2usi32: 3406 case X86::BI__builtin_ia32_vcvtsd2usi64: 3407 case X86::BI__builtin_ia32_vcvtss2si32: 3408 case X86::BI__builtin_ia32_vcvtss2si64: 3409 case X86::BI__builtin_ia32_vcvtss2usi32: 3410 case X86::BI__builtin_ia32_vcvtss2usi64: 3411 case X86::BI__builtin_ia32_sqrtpd512: 3412 case X86::BI__builtin_ia32_sqrtps512: 3413 ArgNum = 1; 3414 HasRC = true; 3415 break; 3416 case X86::BI__builtin_ia32_addpd512: 3417 case X86::BI__builtin_ia32_addps512: 3418 case X86::BI__builtin_ia32_divpd512: 3419 case X86::BI__builtin_ia32_divps512: 3420 case X86::BI__builtin_ia32_mulpd512: 3421 case X86::BI__builtin_ia32_mulps512: 3422 case X86::BI__builtin_ia32_subpd512: 3423 case X86::BI__builtin_ia32_subps512: 3424 case X86::BI__builtin_ia32_cvtsi2sd64: 3425 case X86::BI__builtin_ia32_cvtsi2ss32: 3426 case X86::BI__builtin_ia32_cvtsi2ss64: 3427 case X86::BI__builtin_ia32_cvtusi2sd64: 3428 case X86::BI__builtin_ia32_cvtusi2ss32: 3429 case X86::BI__builtin_ia32_cvtusi2ss64: 3430 ArgNum = 2; 3431 HasRC = true; 3432 break; 3433 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3434 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3435 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3436 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3437 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3438 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3439 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3440 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3441 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3442 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3443 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3444 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3445 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3446 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3447 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3448 ArgNum = 3; 3449 HasRC = true; 3450 break; 3451 case X86::BI__builtin_ia32_addss_round_mask: 3452 case X86::BI__builtin_ia32_addsd_round_mask: 3453 case X86::BI__builtin_ia32_divss_round_mask: 3454 case X86::BI__builtin_ia32_divsd_round_mask: 3455 case X86::BI__builtin_ia32_mulss_round_mask: 3456 case X86::BI__builtin_ia32_mulsd_round_mask: 3457 case X86::BI__builtin_ia32_subss_round_mask: 3458 case X86::BI__builtin_ia32_subsd_round_mask: 3459 case X86::BI__builtin_ia32_scalefpd512_mask: 3460 case X86::BI__builtin_ia32_scalefps512_mask: 3461 case X86::BI__builtin_ia32_scalefsd_round_mask: 3462 case X86::BI__builtin_ia32_scalefss_round_mask: 3463 case X86::BI__builtin_ia32_getmantpd512_mask: 3464 case X86::BI__builtin_ia32_getmantps512_mask: 3465 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3466 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3467 case X86::BI__builtin_ia32_sqrtss_round_mask: 3468 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3469 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3470 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3471 case X86::BI__builtin_ia32_vfmaddss3_mask: 3472 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3473 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3474 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3475 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3476 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3477 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3478 case X86::BI__builtin_ia32_vfmaddps512_mask: 3479 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3480 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3481 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3482 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3483 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3484 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3485 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3486 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3487 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3488 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3489 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3490 ArgNum = 4; 3491 HasRC = true; 3492 break; 3493 case X86::BI__builtin_ia32_getmantsd_round_mask: 3494 case X86::BI__builtin_ia32_getmantss_round_mask: 3495 ArgNum = 5; 3496 HasRC = true; 3497 break; 3498 } 3499 3500 llvm::APSInt Result; 3501 3502 // We can't check the value of a dependent argument. 3503 Expr *Arg = TheCall->getArg(ArgNum); 3504 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3505 return false; 3506 3507 // Check constant-ness first. 3508 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3509 return true; 3510 3511 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3512 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3513 // combined with ROUND_NO_EXC. 3514 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3515 Result == 8/*ROUND_NO_EXC*/ || 3516 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3517 return false; 3518 3519 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3520 << Arg->getSourceRange(); 3521 } 3522 3523 // Check if the gather/scatter scale is legal. 3524 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3525 CallExpr *TheCall) { 3526 unsigned ArgNum = 0; 3527 switch (BuiltinID) { 3528 default: 3529 return false; 3530 case X86::BI__builtin_ia32_gatherpfdpd: 3531 case X86::BI__builtin_ia32_gatherpfdps: 3532 case X86::BI__builtin_ia32_gatherpfqpd: 3533 case X86::BI__builtin_ia32_gatherpfqps: 3534 case X86::BI__builtin_ia32_scatterpfdpd: 3535 case X86::BI__builtin_ia32_scatterpfdps: 3536 case X86::BI__builtin_ia32_scatterpfqpd: 3537 case X86::BI__builtin_ia32_scatterpfqps: 3538 ArgNum = 3; 3539 break; 3540 case X86::BI__builtin_ia32_gatherd_pd: 3541 case X86::BI__builtin_ia32_gatherd_pd256: 3542 case X86::BI__builtin_ia32_gatherq_pd: 3543 case X86::BI__builtin_ia32_gatherq_pd256: 3544 case X86::BI__builtin_ia32_gatherd_ps: 3545 case X86::BI__builtin_ia32_gatherd_ps256: 3546 case X86::BI__builtin_ia32_gatherq_ps: 3547 case X86::BI__builtin_ia32_gatherq_ps256: 3548 case X86::BI__builtin_ia32_gatherd_q: 3549 case X86::BI__builtin_ia32_gatherd_q256: 3550 case X86::BI__builtin_ia32_gatherq_q: 3551 case X86::BI__builtin_ia32_gatherq_q256: 3552 case X86::BI__builtin_ia32_gatherd_d: 3553 case X86::BI__builtin_ia32_gatherd_d256: 3554 case X86::BI__builtin_ia32_gatherq_d: 3555 case X86::BI__builtin_ia32_gatherq_d256: 3556 case X86::BI__builtin_ia32_gather3div2df: 3557 case X86::BI__builtin_ia32_gather3div2di: 3558 case X86::BI__builtin_ia32_gather3div4df: 3559 case X86::BI__builtin_ia32_gather3div4di: 3560 case X86::BI__builtin_ia32_gather3div4sf: 3561 case X86::BI__builtin_ia32_gather3div4si: 3562 case X86::BI__builtin_ia32_gather3div8sf: 3563 case X86::BI__builtin_ia32_gather3div8si: 3564 case X86::BI__builtin_ia32_gather3siv2df: 3565 case X86::BI__builtin_ia32_gather3siv2di: 3566 case X86::BI__builtin_ia32_gather3siv4df: 3567 case X86::BI__builtin_ia32_gather3siv4di: 3568 case X86::BI__builtin_ia32_gather3siv4sf: 3569 case X86::BI__builtin_ia32_gather3siv4si: 3570 case X86::BI__builtin_ia32_gather3siv8sf: 3571 case X86::BI__builtin_ia32_gather3siv8si: 3572 case X86::BI__builtin_ia32_gathersiv8df: 3573 case X86::BI__builtin_ia32_gathersiv16sf: 3574 case X86::BI__builtin_ia32_gatherdiv8df: 3575 case X86::BI__builtin_ia32_gatherdiv16sf: 3576 case X86::BI__builtin_ia32_gathersiv8di: 3577 case X86::BI__builtin_ia32_gathersiv16si: 3578 case X86::BI__builtin_ia32_gatherdiv8di: 3579 case X86::BI__builtin_ia32_gatherdiv16si: 3580 case X86::BI__builtin_ia32_scatterdiv2df: 3581 case X86::BI__builtin_ia32_scatterdiv2di: 3582 case X86::BI__builtin_ia32_scatterdiv4df: 3583 case X86::BI__builtin_ia32_scatterdiv4di: 3584 case X86::BI__builtin_ia32_scatterdiv4sf: 3585 case X86::BI__builtin_ia32_scatterdiv4si: 3586 case X86::BI__builtin_ia32_scatterdiv8sf: 3587 case X86::BI__builtin_ia32_scatterdiv8si: 3588 case X86::BI__builtin_ia32_scattersiv2df: 3589 case X86::BI__builtin_ia32_scattersiv2di: 3590 case X86::BI__builtin_ia32_scattersiv4df: 3591 case X86::BI__builtin_ia32_scattersiv4di: 3592 case X86::BI__builtin_ia32_scattersiv4sf: 3593 case X86::BI__builtin_ia32_scattersiv4si: 3594 case X86::BI__builtin_ia32_scattersiv8sf: 3595 case X86::BI__builtin_ia32_scattersiv8si: 3596 case X86::BI__builtin_ia32_scattersiv8df: 3597 case X86::BI__builtin_ia32_scattersiv16sf: 3598 case X86::BI__builtin_ia32_scatterdiv8df: 3599 case X86::BI__builtin_ia32_scatterdiv16sf: 3600 case X86::BI__builtin_ia32_scattersiv8di: 3601 case X86::BI__builtin_ia32_scattersiv16si: 3602 case X86::BI__builtin_ia32_scatterdiv8di: 3603 case X86::BI__builtin_ia32_scatterdiv16si: 3604 ArgNum = 4; 3605 break; 3606 } 3607 3608 llvm::APSInt Result; 3609 3610 // We can't check the value of a dependent argument. 3611 Expr *Arg = TheCall->getArg(ArgNum); 3612 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3613 return false; 3614 3615 // Check constant-ness first. 3616 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3617 return true; 3618 3619 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3620 return false; 3621 3622 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3623 << Arg->getSourceRange(); 3624 } 3625 3626 static bool isX86_32Builtin(unsigned BuiltinID) { 3627 // These builtins only work on x86-32 targets. 3628 switch (BuiltinID) { 3629 case X86::BI__builtin_ia32_readeflags_u32: 3630 case X86::BI__builtin_ia32_writeeflags_u32: 3631 return true; 3632 } 3633 3634 return false; 3635 } 3636 3637 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3638 if (BuiltinID == X86::BI__builtin_cpu_supports) 3639 return SemaBuiltinCpuSupports(*this, TheCall); 3640 3641 if (BuiltinID == X86::BI__builtin_cpu_is) 3642 return SemaBuiltinCpuIs(*this, TheCall); 3643 3644 // Check for 32-bit only builtins on a 64-bit target. 3645 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3646 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3647 return Diag(TheCall->getCallee()->getBeginLoc(), 3648 diag::err_32_bit_builtin_64_bit_tgt); 3649 3650 // If the intrinsic has rounding or SAE make sure its valid. 3651 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3652 return true; 3653 3654 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3655 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3656 return true; 3657 3658 // For intrinsics which take an immediate value as part of the instruction, 3659 // range check them here. 3660 int i = 0, l = 0, u = 0; 3661 switch (BuiltinID) { 3662 default: 3663 return false; 3664 case X86::BI__builtin_ia32_vec_ext_v2si: 3665 case X86::BI__builtin_ia32_vec_ext_v2di: 3666 case X86::BI__builtin_ia32_vextractf128_pd256: 3667 case X86::BI__builtin_ia32_vextractf128_ps256: 3668 case X86::BI__builtin_ia32_vextractf128_si256: 3669 case X86::BI__builtin_ia32_extract128i256: 3670 case X86::BI__builtin_ia32_extractf64x4_mask: 3671 case X86::BI__builtin_ia32_extracti64x4_mask: 3672 case X86::BI__builtin_ia32_extractf32x8_mask: 3673 case X86::BI__builtin_ia32_extracti32x8_mask: 3674 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3675 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3676 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3677 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3678 i = 1; l = 0; u = 1; 3679 break; 3680 case X86::BI__builtin_ia32_vec_set_v2di: 3681 case X86::BI__builtin_ia32_vinsertf128_pd256: 3682 case X86::BI__builtin_ia32_vinsertf128_ps256: 3683 case X86::BI__builtin_ia32_vinsertf128_si256: 3684 case X86::BI__builtin_ia32_insert128i256: 3685 case X86::BI__builtin_ia32_insertf32x8: 3686 case X86::BI__builtin_ia32_inserti32x8: 3687 case X86::BI__builtin_ia32_insertf64x4: 3688 case X86::BI__builtin_ia32_inserti64x4: 3689 case X86::BI__builtin_ia32_insertf64x2_256: 3690 case X86::BI__builtin_ia32_inserti64x2_256: 3691 case X86::BI__builtin_ia32_insertf32x4_256: 3692 case X86::BI__builtin_ia32_inserti32x4_256: 3693 i = 2; l = 0; u = 1; 3694 break; 3695 case X86::BI__builtin_ia32_vpermilpd: 3696 case X86::BI__builtin_ia32_vec_ext_v4hi: 3697 case X86::BI__builtin_ia32_vec_ext_v4si: 3698 case X86::BI__builtin_ia32_vec_ext_v4sf: 3699 case X86::BI__builtin_ia32_vec_ext_v4di: 3700 case X86::BI__builtin_ia32_extractf32x4_mask: 3701 case X86::BI__builtin_ia32_extracti32x4_mask: 3702 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3703 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3704 i = 1; l = 0; u = 3; 3705 break; 3706 case X86::BI_mm_prefetch: 3707 case X86::BI__builtin_ia32_vec_ext_v8hi: 3708 case X86::BI__builtin_ia32_vec_ext_v8si: 3709 i = 1; l = 0; u = 7; 3710 break; 3711 case X86::BI__builtin_ia32_sha1rnds4: 3712 case X86::BI__builtin_ia32_blendpd: 3713 case X86::BI__builtin_ia32_shufpd: 3714 case X86::BI__builtin_ia32_vec_set_v4hi: 3715 case X86::BI__builtin_ia32_vec_set_v4si: 3716 case X86::BI__builtin_ia32_vec_set_v4di: 3717 case X86::BI__builtin_ia32_shuf_f32x4_256: 3718 case X86::BI__builtin_ia32_shuf_f64x2_256: 3719 case X86::BI__builtin_ia32_shuf_i32x4_256: 3720 case X86::BI__builtin_ia32_shuf_i64x2_256: 3721 case X86::BI__builtin_ia32_insertf64x2_512: 3722 case X86::BI__builtin_ia32_inserti64x2_512: 3723 case X86::BI__builtin_ia32_insertf32x4: 3724 case X86::BI__builtin_ia32_inserti32x4: 3725 i = 2; l = 0; u = 3; 3726 break; 3727 case X86::BI__builtin_ia32_vpermil2pd: 3728 case X86::BI__builtin_ia32_vpermil2pd256: 3729 case X86::BI__builtin_ia32_vpermil2ps: 3730 case X86::BI__builtin_ia32_vpermil2ps256: 3731 i = 3; l = 0; u = 3; 3732 break; 3733 case X86::BI__builtin_ia32_cmpb128_mask: 3734 case X86::BI__builtin_ia32_cmpw128_mask: 3735 case X86::BI__builtin_ia32_cmpd128_mask: 3736 case X86::BI__builtin_ia32_cmpq128_mask: 3737 case X86::BI__builtin_ia32_cmpb256_mask: 3738 case X86::BI__builtin_ia32_cmpw256_mask: 3739 case X86::BI__builtin_ia32_cmpd256_mask: 3740 case X86::BI__builtin_ia32_cmpq256_mask: 3741 case X86::BI__builtin_ia32_cmpb512_mask: 3742 case X86::BI__builtin_ia32_cmpw512_mask: 3743 case X86::BI__builtin_ia32_cmpd512_mask: 3744 case X86::BI__builtin_ia32_cmpq512_mask: 3745 case X86::BI__builtin_ia32_ucmpb128_mask: 3746 case X86::BI__builtin_ia32_ucmpw128_mask: 3747 case X86::BI__builtin_ia32_ucmpd128_mask: 3748 case X86::BI__builtin_ia32_ucmpq128_mask: 3749 case X86::BI__builtin_ia32_ucmpb256_mask: 3750 case X86::BI__builtin_ia32_ucmpw256_mask: 3751 case X86::BI__builtin_ia32_ucmpd256_mask: 3752 case X86::BI__builtin_ia32_ucmpq256_mask: 3753 case X86::BI__builtin_ia32_ucmpb512_mask: 3754 case X86::BI__builtin_ia32_ucmpw512_mask: 3755 case X86::BI__builtin_ia32_ucmpd512_mask: 3756 case X86::BI__builtin_ia32_ucmpq512_mask: 3757 case X86::BI__builtin_ia32_vpcomub: 3758 case X86::BI__builtin_ia32_vpcomuw: 3759 case X86::BI__builtin_ia32_vpcomud: 3760 case X86::BI__builtin_ia32_vpcomuq: 3761 case X86::BI__builtin_ia32_vpcomb: 3762 case X86::BI__builtin_ia32_vpcomw: 3763 case X86::BI__builtin_ia32_vpcomd: 3764 case X86::BI__builtin_ia32_vpcomq: 3765 case X86::BI__builtin_ia32_vec_set_v8hi: 3766 case X86::BI__builtin_ia32_vec_set_v8si: 3767 i = 2; l = 0; u = 7; 3768 break; 3769 case X86::BI__builtin_ia32_vpermilpd256: 3770 case X86::BI__builtin_ia32_roundps: 3771 case X86::BI__builtin_ia32_roundpd: 3772 case X86::BI__builtin_ia32_roundps256: 3773 case X86::BI__builtin_ia32_roundpd256: 3774 case X86::BI__builtin_ia32_getmantpd128_mask: 3775 case X86::BI__builtin_ia32_getmantpd256_mask: 3776 case X86::BI__builtin_ia32_getmantps128_mask: 3777 case X86::BI__builtin_ia32_getmantps256_mask: 3778 case X86::BI__builtin_ia32_getmantpd512_mask: 3779 case X86::BI__builtin_ia32_getmantps512_mask: 3780 case X86::BI__builtin_ia32_vec_ext_v16qi: 3781 case X86::BI__builtin_ia32_vec_ext_v16hi: 3782 i = 1; l = 0; u = 15; 3783 break; 3784 case X86::BI__builtin_ia32_pblendd128: 3785 case X86::BI__builtin_ia32_blendps: 3786 case X86::BI__builtin_ia32_blendpd256: 3787 case X86::BI__builtin_ia32_shufpd256: 3788 case X86::BI__builtin_ia32_roundss: 3789 case X86::BI__builtin_ia32_roundsd: 3790 case X86::BI__builtin_ia32_rangepd128_mask: 3791 case X86::BI__builtin_ia32_rangepd256_mask: 3792 case X86::BI__builtin_ia32_rangepd512_mask: 3793 case X86::BI__builtin_ia32_rangeps128_mask: 3794 case X86::BI__builtin_ia32_rangeps256_mask: 3795 case X86::BI__builtin_ia32_rangeps512_mask: 3796 case X86::BI__builtin_ia32_getmantsd_round_mask: 3797 case X86::BI__builtin_ia32_getmantss_round_mask: 3798 case X86::BI__builtin_ia32_vec_set_v16qi: 3799 case X86::BI__builtin_ia32_vec_set_v16hi: 3800 i = 2; l = 0; u = 15; 3801 break; 3802 case X86::BI__builtin_ia32_vec_ext_v32qi: 3803 i = 1; l = 0; u = 31; 3804 break; 3805 case X86::BI__builtin_ia32_cmpps: 3806 case X86::BI__builtin_ia32_cmpss: 3807 case X86::BI__builtin_ia32_cmppd: 3808 case X86::BI__builtin_ia32_cmpsd: 3809 case X86::BI__builtin_ia32_cmpps256: 3810 case X86::BI__builtin_ia32_cmppd256: 3811 case X86::BI__builtin_ia32_cmpps128_mask: 3812 case X86::BI__builtin_ia32_cmppd128_mask: 3813 case X86::BI__builtin_ia32_cmpps256_mask: 3814 case X86::BI__builtin_ia32_cmppd256_mask: 3815 case X86::BI__builtin_ia32_cmpps512_mask: 3816 case X86::BI__builtin_ia32_cmppd512_mask: 3817 case X86::BI__builtin_ia32_cmpsd_mask: 3818 case X86::BI__builtin_ia32_cmpss_mask: 3819 case X86::BI__builtin_ia32_vec_set_v32qi: 3820 i = 2; l = 0; u = 31; 3821 break; 3822 case X86::BI__builtin_ia32_permdf256: 3823 case X86::BI__builtin_ia32_permdi256: 3824 case X86::BI__builtin_ia32_permdf512: 3825 case X86::BI__builtin_ia32_permdi512: 3826 case X86::BI__builtin_ia32_vpermilps: 3827 case X86::BI__builtin_ia32_vpermilps256: 3828 case X86::BI__builtin_ia32_vpermilpd512: 3829 case X86::BI__builtin_ia32_vpermilps512: 3830 case X86::BI__builtin_ia32_pshufd: 3831 case X86::BI__builtin_ia32_pshufd256: 3832 case X86::BI__builtin_ia32_pshufd512: 3833 case X86::BI__builtin_ia32_pshufhw: 3834 case X86::BI__builtin_ia32_pshufhw256: 3835 case X86::BI__builtin_ia32_pshufhw512: 3836 case X86::BI__builtin_ia32_pshuflw: 3837 case X86::BI__builtin_ia32_pshuflw256: 3838 case X86::BI__builtin_ia32_pshuflw512: 3839 case X86::BI__builtin_ia32_vcvtps2ph: 3840 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3841 case X86::BI__builtin_ia32_vcvtps2ph256: 3842 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3843 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3844 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3845 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3846 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3847 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3848 case X86::BI__builtin_ia32_rndscaleps_mask: 3849 case X86::BI__builtin_ia32_rndscalepd_mask: 3850 case X86::BI__builtin_ia32_reducepd128_mask: 3851 case X86::BI__builtin_ia32_reducepd256_mask: 3852 case X86::BI__builtin_ia32_reducepd512_mask: 3853 case X86::BI__builtin_ia32_reduceps128_mask: 3854 case X86::BI__builtin_ia32_reduceps256_mask: 3855 case X86::BI__builtin_ia32_reduceps512_mask: 3856 case X86::BI__builtin_ia32_prold512: 3857 case X86::BI__builtin_ia32_prolq512: 3858 case X86::BI__builtin_ia32_prold128: 3859 case X86::BI__builtin_ia32_prold256: 3860 case X86::BI__builtin_ia32_prolq128: 3861 case X86::BI__builtin_ia32_prolq256: 3862 case X86::BI__builtin_ia32_prord512: 3863 case X86::BI__builtin_ia32_prorq512: 3864 case X86::BI__builtin_ia32_prord128: 3865 case X86::BI__builtin_ia32_prord256: 3866 case X86::BI__builtin_ia32_prorq128: 3867 case X86::BI__builtin_ia32_prorq256: 3868 case X86::BI__builtin_ia32_fpclasspd128_mask: 3869 case X86::BI__builtin_ia32_fpclasspd256_mask: 3870 case X86::BI__builtin_ia32_fpclassps128_mask: 3871 case X86::BI__builtin_ia32_fpclassps256_mask: 3872 case X86::BI__builtin_ia32_fpclassps512_mask: 3873 case X86::BI__builtin_ia32_fpclasspd512_mask: 3874 case X86::BI__builtin_ia32_fpclasssd_mask: 3875 case X86::BI__builtin_ia32_fpclassss_mask: 3876 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3877 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3878 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3879 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3880 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3881 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3882 case X86::BI__builtin_ia32_kshiftliqi: 3883 case X86::BI__builtin_ia32_kshiftlihi: 3884 case X86::BI__builtin_ia32_kshiftlisi: 3885 case X86::BI__builtin_ia32_kshiftlidi: 3886 case X86::BI__builtin_ia32_kshiftriqi: 3887 case X86::BI__builtin_ia32_kshiftrihi: 3888 case X86::BI__builtin_ia32_kshiftrisi: 3889 case X86::BI__builtin_ia32_kshiftridi: 3890 i = 1; l = 0; u = 255; 3891 break; 3892 case X86::BI__builtin_ia32_vperm2f128_pd256: 3893 case X86::BI__builtin_ia32_vperm2f128_ps256: 3894 case X86::BI__builtin_ia32_vperm2f128_si256: 3895 case X86::BI__builtin_ia32_permti256: 3896 case X86::BI__builtin_ia32_pblendw128: 3897 case X86::BI__builtin_ia32_pblendw256: 3898 case X86::BI__builtin_ia32_blendps256: 3899 case X86::BI__builtin_ia32_pblendd256: 3900 case X86::BI__builtin_ia32_palignr128: 3901 case X86::BI__builtin_ia32_palignr256: 3902 case X86::BI__builtin_ia32_palignr512: 3903 case X86::BI__builtin_ia32_alignq512: 3904 case X86::BI__builtin_ia32_alignd512: 3905 case X86::BI__builtin_ia32_alignd128: 3906 case X86::BI__builtin_ia32_alignd256: 3907 case X86::BI__builtin_ia32_alignq128: 3908 case X86::BI__builtin_ia32_alignq256: 3909 case X86::BI__builtin_ia32_vcomisd: 3910 case X86::BI__builtin_ia32_vcomiss: 3911 case X86::BI__builtin_ia32_shuf_f32x4: 3912 case X86::BI__builtin_ia32_shuf_f64x2: 3913 case X86::BI__builtin_ia32_shuf_i32x4: 3914 case X86::BI__builtin_ia32_shuf_i64x2: 3915 case X86::BI__builtin_ia32_shufpd512: 3916 case X86::BI__builtin_ia32_shufps: 3917 case X86::BI__builtin_ia32_shufps256: 3918 case X86::BI__builtin_ia32_shufps512: 3919 case X86::BI__builtin_ia32_dbpsadbw128: 3920 case X86::BI__builtin_ia32_dbpsadbw256: 3921 case X86::BI__builtin_ia32_dbpsadbw512: 3922 case X86::BI__builtin_ia32_vpshldd128: 3923 case X86::BI__builtin_ia32_vpshldd256: 3924 case X86::BI__builtin_ia32_vpshldd512: 3925 case X86::BI__builtin_ia32_vpshldq128: 3926 case X86::BI__builtin_ia32_vpshldq256: 3927 case X86::BI__builtin_ia32_vpshldq512: 3928 case X86::BI__builtin_ia32_vpshldw128: 3929 case X86::BI__builtin_ia32_vpshldw256: 3930 case X86::BI__builtin_ia32_vpshldw512: 3931 case X86::BI__builtin_ia32_vpshrdd128: 3932 case X86::BI__builtin_ia32_vpshrdd256: 3933 case X86::BI__builtin_ia32_vpshrdd512: 3934 case X86::BI__builtin_ia32_vpshrdq128: 3935 case X86::BI__builtin_ia32_vpshrdq256: 3936 case X86::BI__builtin_ia32_vpshrdq512: 3937 case X86::BI__builtin_ia32_vpshrdw128: 3938 case X86::BI__builtin_ia32_vpshrdw256: 3939 case X86::BI__builtin_ia32_vpshrdw512: 3940 i = 2; l = 0; u = 255; 3941 break; 3942 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3943 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3944 case X86::BI__builtin_ia32_fixupimmps512_mask: 3945 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3946 case X86::BI__builtin_ia32_fixupimmsd_mask: 3947 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3948 case X86::BI__builtin_ia32_fixupimmss_mask: 3949 case X86::BI__builtin_ia32_fixupimmss_maskz: 3950 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3951 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3952 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3953 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3954 case X86::BI__builtin_ia32_fixupimmps128_mask: 3955 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3956 case X86::BI__builtin_ia32_fixupimmps256_mask: 3957 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3958 case X86::BI__builtin_ia32_pternlogd512_mask: 3959 case X86::BI__builtin_ia32_pternlogd512_maskz: 3960 case X86::BI__builtin_ia32_pternlogq512_mask: 3961 case X86::BI__builtin_ia32_pternlogq512_maskz: 3962 case X86::BI__builtin_ia32_pternlogd128_mask: 3963 case X86::BI__builtin_ia32_pternlogd128_maskz: 3964 case X86::BI__builtin_ia32_pternlogd256_mask: 3965 case X86::BI__builtin_ia32_pternlogd256_maskz: 3966 case X86::BI__builtin_ia32_pternlogq128_mask: 3967 case X86::BI__builtin_ia32_pternlogq128_maskz: 3968 case X86::BI__builtin_ia32_pternlogq256_mask: 3969 case X86::BI__builtin_ia32_pternlogq256_maskz: 3970 i = 3; l = 0; u = 255; 3971 break; 3972 case X86::BI__builtin_ia32_gatherpfdpd: 3973 case X86::BI__builtin_ia32_gatherpfdps: 3974 case X86::BI__builtin_ia32_gatherpfqpd: 3975 case X86::BI__builtin_ia32_gatherpfqps: 3976 case X86::BI__builtin_ia32_scatterpfdpd: 3977 case X86::BI__builtin_ia32_scatterpfdps: 3978 case X86::BI__builtin_ia32_scatterpfqpd: 3979 case X86::BI__builtin_ia32_scatterpfqps: 3980 i = 4; l = 2; u = 3; 3981 break; 3982 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3983 case X86::BI__builtin_ia32_rndscaless_round_mask: 3984 i = 4; l = 0; u = 255; 3985 break; 3986 } 3987 3988 // Note that we don't force a hard error on the range check here, allowing 3989 // template-generated or macro-generated dead code to potentially have out-of- 3990 // range values. These need to code generate, but don't need to necessarily 3991 // make any sense. We use a warning that defaults to an error. 3992 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3993 } 3994 3995 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3996 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3997 /// Returns true when the format fits the function and the FormatStringInfo has 3998 /// been populated. 3999 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4000 FormatStringInfo *FSI) { 4001 FSI->HasVAListArg = Format->getFirstArg() == 0; 4002 FSI->FormatIdx = Format->getFormatIdx() - 1; 4003 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4004 4005 // The way the format attribute works in GCC, the implicit this argument 4006 // of member functions is counted. However, it doesn't appear in our own 4007 // lists, so decrement format_idx in that case. 4008 if (IsCXXMember) { 4009 if(FSI->FormatIdx == 0) 4010 return false; 4011 --FSI->FormatIdx; 4012 if (FSI->FirstDataArg != 0) 4013 --FSI->FirstDataArg; 4014 } 4015 return true; 4016 } 4017 4018 /// Checks if a the given expression evaluates to null. 4019 /// 4020 /// Returns true if the value evaluates to null. 4021 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4022 // If the expression has non-null type, it doesn't evaluate to null. 4023 if (auto nullability 4024 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4025 if (*nullability == NullabilityKind::NonNull) 4026 return false; 4027 } 4028 4029 // As a special case, transparent unions initialized with zero are 4030 // considered null for the purposes of the nonnull attribute. 4031 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4032 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4033 if (const CompoundLiteralExpr *CLE = 4034 dyn_cast<CompoundLiteralExpr>(Expr)) 4035 if (const InitListExpr *ILE = 4036 dyn_cast<InitListExpr>(CLE->getInitializer())) 4037 Expr = ILE->getInit(0); 4038 } 4039 4040 bool Result; 4041 return (!Expr->isValueDependent() && 4042 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4043 !Result); 4044 } 4045 4046 static void CheckNonNullArgument(Sema &S, 4047 const Expr *ArgExpr, 4048 SourceLocation CallSiteLoc) { 4049 if (CheckNonNullExpr(S, ArgExpr)) 4050 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4051 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange()); 4052 } 4053 4054 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4055 FormatStringInfo FSI; 4056 if ((GetFormatStringType(Format) == FST_NSString) && 4057 getFormatStringInfo(Format, false, &FSI)) { 4058 Idx = FSI.FormatIdx; 4059 return true; 4060 } 4061 return false; 4062 } 4063 4064 /// Diagnose use of %s directive in an NSString which is being passed 4065 /// as formatting string to formatting method. 4066 static void 4067 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4068 const NamedDecl *FDecl, 4069 Expr **Args, 4070 unsigned NumArgs) { 4071 unsigned Idx = 0; 4072 bool Format = false; 4073 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4074 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4075 Idx = 2; 4076 Format = true; 4077 } 4078 else 4079 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4080 if (S.GetFormatNSStringIdx(I, Idx)) { 4081 Format = true; 4082 break; 4083 } 4084 } 4085 if (!Format || NumArgs <= Idx) 4086 return; 4087 const Expr *FormatExpr = Args[Idx]; 4088 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4089 FormatExpr = CSCE->getSubExpr(); 4090 const StringLiteral *FormatString; 4091 if (const ObjCStringLiteral *OSL = 4092 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4093 FormatString = OSL->getString(); 4094 else 4095 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4096 if (!FormatString) 4097 return; 4098 if (S.FormatStringHasSArg(FormatString)) { 4099 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4100 << "%s" << 1 << 1; 4101 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4102 << FDecl->getDeclName(); 4103 } 4104 } 4105 4106 /// Determine whether the given type has a non-null nullability annotation. 4107 static bool isNonNullType(ASTContext &ctx, QualType type) { 4108 if (auto nullability = type->getNullability(ctx)) 4109 return *nullability == NullabilityKind::NonNull; 4110 4111 return false; 4112 } 4113 4114 static void CheckNonNullArguments(Sema &S, 4115 const NamedDecl *FDecl, 4116 const FunctionProtoType *Proto, 4117 ArrayRef<const Expr *> Args, 4118 SourceLocation CallSiteLoc) { 4119 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4120 4121 // Check the attributes attached to the method/function itself. 4122 llvm::SmallBitVector NonNullArgs; 4123 if (FDecl) { 4124 // Handle the nonnull attribute on the function/method declaration itself. 4125 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4126 if (!NonNull->args_size()) { 4127 // Easy case: all pointer arguments are nonnull. 4128 for (const auto *Arg : Args) 4129 if (S.isValidPointerAttrType(Arg->getType())) 4130 CheckNonNullArgument(S, Arg, CallSiteLoc); 4131 return; 4132 } 4133 4134 for (const ParamIdx &Idx : NonNull->args()) { 4135 unsigned IdxAST = Idx.getASTIndex(); 4136 if (IdxAST >= Args.size()) 4137 continue; 4138 if (NonNullArgs.empty()) 4139 NonNullArgs.resize(Args.size()); 4140 NonNullArgs.set(IdxAST); 4141 } 4142 } 4143 } 4144 4145 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4146 // Handle the nonnull attribute on the parameters of the 4147 // function/method. 4148 ArrayRef<ParmVarDecl*> parms; 4149 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4150 parms = FD->parameters(); 4151 else 4152 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4153 4154 unsigned ParamIndex = 0; 4155 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4156 I != E; ++I, ++ParamIndex) { 4157 const ParmVarDecl *PVD = *I; 4158 if (PVD->hasAttr<NonNullAttr>() || 4159 isNonNullType(S.Context, PVD->getType())) { 4160 if (NonNullArgs.empty()) 4161 NonNullArgs.resize(Args.size()); 4162 4163 NonNullArgs.set(ParamIndex); 4164 } 4165 } 4166 } else { 4167 // If we have a non-function, non-method declaration but no 4168 // function prototype, try to dig out the function prototype. 4169 if (!Proto) { 4170 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4171 QualType type = VD->getType().getNonReferenceType(); 4172 if (auto pointerType = type->getAs<PointerType>()) 4173 type = pointerType->getPointeeType(); 4174 else if (auto blockType = type->getAs<BlockPointerType>()) 4175 type = blockType->getPointeeType(); 4176 // FIXME: data member pointers? 4177 4178 // Dig out the function prototype, if there is one. 4179 Proto = type->getAs<FunctionProtoType>(); 4180 } 4181 } 4182 4183 // Fill in non-null argument information from the nullability 4184 // information on the parameter types (if we have them). 4185 if (Proto) { 4186 unsigned Index = 0; 4187 for (auto paramType : Proto->getParamTypes()) { 4188 if (isNonNullType(S.Context, paramType)) { 4189 if (NonNullArgs.empty()) 4190 NonNullArgs.resize(Args.size()); 4191 4192 NonNullArgs.set(Index); 4193 } 4194 4195 ++Index; 4196 } 4197 } 4198 } 4199 4200 // Check for non-null arguments. 4201 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4202 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4203 if (NonNullArgs[ArgIndex]) 4204 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4205 } 4206 } 4207 4208 /// Handles the checks for format strings, non-POD arguments to vararg 4209 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4210 /// attributes. 4211 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4212 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4213 bool IsMemberFunction, SourceLocation Loc, 4214 SourceRange Range, VariadicCallType CallType) { 4215 // FIXME: We should check as much as we can in the template definition. 4216 if (CurContext->isDependentContext()) 4217 return; 4218 4219 // Printf and scanf checking. 4220 llvm::SmallBitVector CheckedVarArgs; 4221 if (FDecl) { 4222 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4223 // Only create vector if there are format attributes. 4224 CheckedVarArgs.resize(Args.size()); 4225 4226 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4227 CheckedVarArgs); 4228 } 4229 } 4230 4231 // Refuse POD arguments that weren't caught by the format string 4232 // checks above. 4233 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4234 if (CallType != VariadicDoesNotApply && 4235 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4236 unsigned NumParams = Proto ? Proto->getNumParams() 4237 : FDecl && isa<FunctionDecl>(FDecl) 4238 ? cast<FunctionDecl>(FDecl)->getNumParams() 4239 : FDecl && isa<ObjCMethodDecl>(FDecl) 4240 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4241 : 0; 4242 4243 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4244 // Args[ArgIdx] can be null in malformed code. 4245 if (const Expr *Arg = Args[ArgIdx]) { 4246 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4247 checkVariadicArgument(Arg, CallType); 4248 } 4249 } 4250 } 4251 4252 if (FDecl || Proto) { 4253 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4254 4255 // Type safety checking. 4256 if (FDecl) { 4257 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4258 CheckArgumentWithTypeTag(I, Args, Loc); 4259 } 4260 } 4261 4262 if (FD) 4263 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4264 } 4265 4266 /// CheckConstructorCall - Check a constructor call for correctness and safety 4267 /// properties not enforced by the C type system. 4268 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4269 ArrayRef<const Expr *> Args, 4270 const FunctionProtoType *Proto, 4271 SourceLocation Loc) { 4272 VariadicCallType CallType = 4273 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4274 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4275 Loc, SourceRange(), CallType); 4276 } 4277 4278 /// CheckFunctionCall - Check a direct function call for various correctness 4279 /// and safety properties not strictly enforced by the C type system. 4280 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4281 const FunctionProtoType *Proto) { 4282 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4283 isa<CXXMethodDecl>(FDecl); 4284 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4285 IsMemberOperatorCall; 4286 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4287 TheCall->getCallee()); 4288 Expr** Args = TheCall->getArgs(); 4289 unsigned NumArgs = TheCall->getNumArgs(); 4290 4291 Expr *ImplicitThis = nullptr; 4292 if (IsMemberOperatorCall) { 4293 // If this is a call to a member operator, hide the first argument 4294 // from checkCall. 4295 // FIXME: Our choice of AST representation here is less than ideal. 4296 ImplicitThis = Args[0]; 4297 ++Args; 4298 --NumArgs; 4299 } else if (IsMemberFunction) 4300 ImplicitThis = 4301 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4302 4303 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4304 IsMemberFunction, TheCall->getRParenLoc(), 4305 TheCall->getCallee()->getSourceRange(), CallType); 4306 4307 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4308 // None of the checks below are needed for functions that don't have 4309 // simple names (e.g., C++ conversion functions). 4310 if (!FnInfo) 4311 return false; 4312 4313 CheckAbsoluteValueFunction(TheCall, FDecl); 4314 CheckMaxUnsignedZero(TheCall, FDecl); 4315 4316 if (getLangOpts().ObjC) 4317 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4318 4319 unsigned CMId = FDecl->getMemoryFunctionKind(); 4320 if (CMId == 0) 4321 return false; 4322 4323 // Handle memory setting and copying functions. 4324 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4325 CheckStrlcpycatArguments(TheCall, FnInfo); 4326 else if (CMId == Builtin::BIstrncat) 4327 CheckStrncatArguments(TheCall, FnInfo); 4328 else 4329 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4330 4331 return false; 4332 } 4333 4334 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4335 ArrayRef<const Expr *> Args) { 4336 VariadicCallType CallType = 4337 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4338 4339 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4340 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4341 CallType); 4342 4343 return false; 4344 } 4345 4346 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4347 const FunctionProtoType *Proto) { 4348 QualType Ty; 4349 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4350 Ty = V->getType().getNonReferenceType(); 4351 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4352 Ty = F->getType().getNonReferenceType(); 4353 else 4354 return false; 4355 4356 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4357 !Ty->isFunctionProtoType()) 4358 return false; 4359 4360 VariadicCallType CallType; 4361 if (!Proto || !Proto->isVariadic()) { 4362 CallType = VariadicDoesNotApply; 4363 } else if (Ty->isBlockPointerType()) { 4364 CallType = VariadicBlock; 4365 } else { // Ty->isFunctionPointerType() 4366 CallType = VariadicFunction; 4367 } 4368 4369 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4370 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4371 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4372 TheCall->getCallee()->getSourceRange(), CallType); 4373 4374 return false; 4375 } 4376 4377 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4378 /// such as function pointers returned from functions. 4379 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4380 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4381 TheCall->getCallee()); 4382 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4383 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4384 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4385 TheCall->getCallee()->getSourceRange(), CallType); 4386 4387 return false; 4388 } 4389 4390 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4391 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4392 return false; 4393 4394 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4395 switch (Op) { 4396 case AtomicExpr::AO__c11_atomic_init: 4397 case AtomicExpr::AO__opencl_atomic_init: 4398 llvm_unreachable("There is no ordering argument for an init"); 4399 4400 case AtomicExpr::AO__c11_atomic_load: 4401 case AtomicExpr::AO__opencl_atomic_load: 4402 case AtomicExpr::AO__atomic_load_n: 4403 case AtomicExpr::AO__atomic_load: 4404 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4405 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4406 4407 case AtomicExpr::AO__c11_atomic_store: 4408 case AtomicExpr::AO__opencl_atomic_store: 4409 case AtomicExpr::AO__atomic_store: 4410 case AtomicExpr::AO__atomic_store_n: 4411 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4412 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4413 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4414 4415 default: 4416 return true; 4417 } 4418 } 4419 4420 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4421 AtomicExpr::AtomicOp Op) { 4422 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4423 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4424 4425 // All the non-OpenCL operations take one of the following forms. 4426 // The OpenCL operations take the __c11 forms with one extra argument for 4427 // synchronization scope. 4428 enum { 4429 // C __c11_atomic_init(A *, C) 4430 Init, 4431 4432 // C __c11_atomic_load(A *, int) 4433 Load, 4434 4435 // void __atomic_load(A *, CP, int) 4436 LoadCopy, 4437 4438 // void __atomic_store(A *, CP, int) 4439 Copy, 4440 4441 // C __c11_atomic_add(A *, M, int) 4442 Arithmetic, 4443 4444 // C __atomic_exchange_n(A *, CP, int) 4445 Xchg, 4446 4447 // void __atomic_exchange(A *, C *, CP, int) 4448 GNUXchg, 4449 4450 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4451 C11CmpXchg, 4452 4453 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4454 GNUCmpXchg 4455 } Form = Init; 4456 4457 const unsigned NumForm = GNUCmpXchg + 1; 4458 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4459 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4460 // where: 4461 // C is an appropriate type, 4462 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4463 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4464 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4465 // the int parameters are for orderings. 4466 4467 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4468 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4469 "need to update code for modified forms"); 4470 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4471 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4472 AtomicExpr::AO__atomic_load, 4473 "need to update code for modified C11 atomics"); 4474 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4475 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4476 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4477 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4478 IsOpenCL; 4479 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4480 Op == AtomicExpr::AO__atomic_store_n || 4481 Op == AtomicExpr::AO__atomic_exchange_n || 4482 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4483 bool IsAddSub = false; 4484 bool IsMinMax = false; 4485 4486 switch (Op) { 4487 case AtomicExpr::AO__c11_atomic_init: 4488 case AtomicExpr::AO__opencl_atomic_init: 4489 Form = Init; 4490 break; 4491 4492 case AtomicExpr::AO__c11_atomic_load: 4493 case AtomicExpr::AO__opencl_atomic_load: 4494 case AtomicExpr::AO__atomic_load_n: 4495 Form = Load; 4496 break; 4497 4498 case AtomicExpr::AO__atomic_load: 4499 Form = LoadCopy; 4500 break; 4501 4502 case AtomicExpr::AO__c11_atomic_store: 4503 case AtomicExpr::AO__opencl_atomic_store: 4504 case AtomicExpr::AO__atomic_store: 4505 case AtomicExpr::AO__atomic_store_n: 4506 Form = Copy; 4507 break; 4508 4509 case AtomicExpr::AO__c11_atomic_fetch_add: 4510 case AtomicExpr::AO__c11_atomic_fetch_sub: 4511 case AtomicExpr::AO__opencl_atomic_fetch_add: 4512 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4513 case AtomicExpr::AO__opencl_atomic_fetch_min: 4514 case AtomicExpr::AO__opencl_atomic_fetch_max: 4515 case AtomicExpr::AO__atomic_fetch_add: 4516 case AtomicExpr::AO__atomic_fetch_sub: 4517 case AtomicExpr::AO__atomic_add_fetch: 4518 case AtomicExpr::AO__atomic_sub_fetch: 4519 IsAddSub = true; 4520 LLVM_FALLTHROUGH; 4521 case AtomicExpr::AO__c11_atomic_fetch_and: 4522 case AtomicExpr::AO__c11_atomic_fetch_or: 4523 case AtomicExpr::AO__c11_atomic_fetch_xor: 4524 case AtomicExpr::AO__opencl_atomic_fetch_and: 4525 case AtomicExpr::AO__opencl_atomic_fetch_or: 4526 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4527 case AtomicExpr::AO__atomic_fetch_and: 4528 case AtomicExpr::AO__atomic_fetch_or: 4529 case AtomicExpr::AO__atomic_fetch_xor: 4530 case AtomicExpr::AO__atomic_fetch_nand: 4531 case AtomicExpr::AO__atomic_and_fetch: 4532 case AtomicExpr::AO__atomic_or_fetch: 4533 case AtomicExpr::AO__atomic_xor_fetch: 4534 case AtomicExpr::AO__atomic_nand_fetch: 4535 Form = Arithmetic; 4536 break; 4537 4538 case AtomicExpr::AO__atomic_fetch_min: 4539 case AtomicExpr::AO__atomic_fetch_max: 4540 IsMinMax = true; 4541 Form = Arithmetic; 4542 break; 4543 4544 case AtomicExpr::AO__c11_atomic_exchange: 4545 case AtomicExpr::AO__opencl_atomic_exchange: 4546 case AtomicExpr::AO__atomic_exchange_n: 4547 Form = Xchg; 4548 break; 4549 4550 case AtomicExpr::AO__atomic_exchange: 4551 Form = GNUXchg; 4552 break; 4553 4554 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4555 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4556 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4557 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4558 Form = C11CmpXchg; 4559 break; 4560 4561 case AtomicExpr::AO__atomic_compare_exchange: 4562 case AtomicExpr::AO__atomic_compare_exchange_n: 4563 Form = GNUCmpXchg; 4564 break; 4565 } 4566 4567 unsigned AdjustedNumArgs = NumArgs[Form]; 4568 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4569 ++AdjustedNumArgs; 4570 // Check we have the right number of arguments. 4571 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4572 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4573 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4574 << TheCall->getCallee()->getSourceRange(); 4575 return ExprError(); 4576 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4577 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4578 diag::err_typecheck_call_too_many_args) 4579 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4580 << TheCall->getCallee()->getSourceRange(); 4581 return ExprError(); 4582 } 4583 4584 // Inspect the first argument of the atomic operation. 4585 Expr *Ptr = TheCall->getArg(0); 4586 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4587 if (ConvertedPtr.isInvalid()) 4588 return ExprError(); 4589 4590 Ptr = ConvertedPtr.get(); 4591 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4592 if (!pointerType) { 4593 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4594 << Ptr->getType() << Ptr->getSourceRange(); 4595 return ExprError(); 4596 } 4597 4598 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4599 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4600 QualType ValType = AtomTy; // 'C' 4601 if (IsC11) { 4602 if (!AtomTy->isAtomicType()) { 4603 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4604 << Ptr->getType() << Ptr->getSourceRange(); 4605 return ExprError(); 4606 } 4607 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4608 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4609 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4610 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4611 << Ptr->getSourceRange(); 4612 return ExprError(); 4613 } 4614 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4615 } else if (Form != Load && Form != LoadCopy) { 4616 if (ValType.isConstQualified()) { 4617 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4618 << Ptr->getType() << Ptr->getSourceRange(); 4619 return ExprError(); 4620 } 4621 } 4622 4623 // For an arithmetic operation, the implied arithmetic must be well-formed. 4624 if (Form == Arithmetic) { 4625 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4626 if (IsAddSub && !ValType->isIntegerType() 4627 && !ValType->isPointerType()) { 4628 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4629 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4630 return ExprError(); 4631 } 4632 if (IsMinMax) { 4633 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4634 if (!BT || (BT->getKind() != BuiltinType::Int && 4635 BT->getKind() != BuiltinType::UInt)) { 4636 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4637 return ExprError(); 4638 } 4639 } 4640 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4641 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4642 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4643 return ExprError(); 4644 } 4645 if (IsC11 && ValType->isPointerType() && 4646 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4647 diag::err_incomplete_type)) { 4648 return ExprError(); 4649 } 4650 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4651 // For __atomic_*_n operations, the value type must be a scalar integral or 4652 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4653 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4654 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4655 return ExprError(); 4656 } 4657 4658 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4659 !AtomTy->isScalarType()) { 4660 // For GNU atomics, require a trivially-copyable type. This is not part of 4661 // the GNU atomics specification, but we enforce it for sanity. 4662 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4663 << Ptr->getType() << Ptr->getSourceRange(); 4664 return ExprError(); 4665 } 4666 4667 switch (ValType.getObjCLifetime()) { 4668 case Qualifiers::OCL_None: 4669 case Qualifiers::OCL_ExplicitNone: 4670 // okay 4671 break; 4672 4673 case Qualifiers::OCL_Weak: 4674 case Qualifiers::OCL_Strong: 4675 case Qualifiers::OCL_Autoreleasing: 4676 // FIXME: Can this happen? By this point, ValType should be known 4677 // to be trivially copyable. 4678 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4679 << ValType << Ptr->getSourceRange(); 4680 return ExprError(); 4681 } 4682 4683 // All atomic operations have an overload which takes a pointer to a volatile 4684 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4685 // into the result or the other operands. Similarly atomic_load takes a 4686 // pointer to a const 'A'. 4687 ValType.removeLocalVolatile(); 4688 ValType.removeLocalConst(); 4689 QualType ResultType = ValType; 4690 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4691 Form == Init) 4692 ResultType = Context.VoidTy; 4693 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4694 ResultType = Context.BoolTy; 4695 4696 // The type of a parameter passed 'by value'. In the GNU atomics, such 4697 // arguments are actually passed as pointers. 4698 QualType ByValType = ValType; // 'CP' 4699 bool IsPassedByAddress = false; 4700 if (!IsC11 && !IsN) { 4701 ByValType = Ptr->getType(); 4702 IsPassedByAddress = true; 4703 } 4704 4705 // The first argument's non-CV pointer type is used to deduce the type of 4706 // subsequent arguments, except for: 4707 // - weak flag (always converted to bool) 4708 // - memory order (always converted to int) 4709 // - scope (always converted to int) 4710 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4711 QualType Ty; 4712 if (i < NumVals[Form] + 1) { 4713 switch (i) { 4714 case 0: 4715 // The first argument is always a pointer. It has a fixed type. 4716 // It is always dereferenced, a nullptr is undefined. 4717 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4718 // Nothing else to do: we already know all we want about this pointer. 4719 continue; 4720 case 1: 4721 // The second argument is the non-atomic operand. For arithmetic, this 4722 // is always passed by value, and for a compare_exchange it is always 4723 // passed by address. For the rest, GNU uses by-address and C11 uses 4724 // by-value. 4725 assert(Form != Load); 4726 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4727 Ty = ValType; 4728 else if (Form == Copy || Form == Xchg) { 4729 if (IsPassedByAddress) 4730 // The value pointer is always dereferenced, a nullptr is undefined. 4731 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4732 Ty = ByValType; 4733 } else if (Form == Arithmetic) 4734 Ty = Context.getPointerDiffType(); 4735 else { 4736 Expr *ValArg = TheCall->getArg(i); 4737 // The value pointer is always dereferenced, a nullptr is undefined. 4738 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4739 LangAS AS = LangAS::Default; 4740 // Keep address space of non-atomic pointer type. 4741 if (const PointerType *PtrTy = 4742 ValArg->getType()->getAs<PointerType>()) { 4743 AS = PtrTy->getPointeeType().getAddressSpace(); 4744 } 4745 Ty = Context.getPointerType( 4746 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4747 } 4748 break; 4749 case 2: 4750 // The third argument to compare_exchange / GNU exchange is the desired 4751 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4752 if (IsPassedByAddress) 4753 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4754 Ty = ByValType; 4755 break; 4756 case 3: 4757 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4758 Ty = Context.BoolTy; 4759 break; 4760 } 4761 } else { 4762 // The order(s) and scope are always converted to int. 4763 Ty = Context.IntTy; 4764 } 4765 4766 InitializedEntity Entity = 4767 InitializedEntity::InitializeParameter(Context, Ty, false); 4768 ExprResult Arg = TheCall->getArg(i); 4769 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4770 if (Arg.isInvalid()) 4771 return true; 4772 TheCall->setArg(i, Arg.get()); 4773 } 4774 4775 // Permute the arguments into a 'consistent' order. 4776 SmallVector<Expr*, 5> SubExprs; 4777 SubExprs.push_back(Ptr); 4778 switch (Form) { 4779 case Init: 4780 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4781 SubExprs.push_back(TheCall->getArg(1)); // Val1 4782 break; 4783 case Load: 4784 SubExprs.push_back(TheCall->getArg(1)); // Order 4785 break; 4786 case LoadCopy: 4787 case Copy: 4788 case Arithmetic: 4789 case Xchg: 4790 SubExprs.push_back(TheCall->getArg(2)); // Order 4791 SubExprs.push_back(TheCall->getArg(1)); // Val1 4792 break; 4793 case GNUXchg: 4794 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4795 SubExprs.push_back(TheCall->getArg(3)); // Order 4796 SubExprs.push_back(TheCall->getArg(1)); // Val1 4797 SubExprs.push_back(TheCall->getArg(2)); // Val2 4798 break; 4799 case C11CmpXchg: 4800 SubExprs.push_back(TheCall->getArg(3)); // Order 4801 SubExprs.push_back(TheCall->getArg(1)); // Val1 4802 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4803 SubExprs.push_back(TheCall->getArg(2)); // Val2 4804 break; 4805 case GNUCmpXchg: 4806 SubExprs.push_back(TheCall->getArg(4)); // Order 4807 SubExprs.push_back(TheCall->getArg(1)); // Val1 4808 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4809 SubExprs.push_back(TheCall->getArg(2)); // Val2 4810 SubExprs.push_back(TheCall->getArg(3)); // Weak 4811 break; 4812 } 4813 4814 if (SubExprs.size() >= 2 && Form != Init) { 4815 llvm::APSInt Result(32); 4816 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4817 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4818 Diag(SubExprs[1]->getBeginLoc(), 4819 diag::warn_atomic_op_has_invalid_memory_order) 4820 << SubExprs[1]->getSourceRange(); 4821 } 4822 4823 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4824 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4825 llvm::APSInt Result(32); 4826 if (Scope->isIntegerConstantExpr(Result, Context) && 4827 !ScopeModel->isValid(Result.getZExtValue())) { 4828 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4829 << Scope->getSourceRange(); 4830 } 4831 SubExprs.push_back(Scope); 4832 } 4833 4834 AtomicExpr *AE = 4835 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4836 ResultType, Op, TheCall->getRParenLoc()); 4837 4838 if ((Op == AtomicExpr::AO__c11_atomic_load || 4839 Op == AtomicExpr::AO__c11_atomic_store || 4840 Op == AtomicExpr::AO__opencl_atomic_load || 4841 Op == AtomicExpr::AO__opencl_atomic_store ) && 4842 Context.AtomicUsesUnsupportedLibcall(AE)) 4843 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4844 << ((Op == AtomicExpr::AO__c11_atomic_load || 4845 Op == AtomicExpr::AO__opencl_atomic_load) 4846 ? 0 4847 : 1); 4848 4849 return AE; 4850 } 4851 4852 /// checkBuiltinArgument - Given a call to a builtin function, perform 4853 /// normal type-checking on the given argument, updating the call in 4854 /// place. This is useful when a builtin function requires custom 4855 /// type-checking for some of its arguments but not necessarily all of 4856 /// them. 4857 /// 4858 /// Returns true on error. 4859 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4860 FunctionDecl *Fn = E->getDirectCallee(); 4861 assert(Fn && "builtin call without direct callee!"); 4862 4863 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4864 InitializedEntity Entity = 4865 InitializedEntity::InitializeParameter(S.Context, Param); 4866 4867 ExprResult Arg = E->getArg(0); 4868 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4869 if (Arg.isInvalid()) 4870 return true; 4871 4872 E->setArg(ArgIndex, Arg.get()); 4873 return false; 4874 } 4875 4876 /// We have a call to a function like __sync_fetch_and_add, which is an 4877 /// overloaded function based on the pointer type of its first argument. 4878 /// The main ActOnCallExpr routines have already promoted the types of 4879 /// arguments because all of these calls are prototyped as void(...). 4880 /// 4881 /// This function goes through and does final semantic checking for these 4882 /// builtins, as well as generating any warnings. 4883 ExprResult 4884 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4885 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4886 Expr *Callee = TheCall->getCallee(); 4887 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4888 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4889 4890 // Ensure that we have at least one argument to do type inference from. 4891 if (TheCall->getNumArgs() < 1) { 4892 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4893 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4894 return ExprError(); 4895 } 4896 4897 // Inspect the first argument of the atomic builtin. This should always be 4898 // a pointer type, whose element is an integral scalar or pointer type. 4899 // Because it is a pointer type, we don't have to worry about any implicit 4900 // casts here. 4901 // FIXME: We don't allow floating point scalars as input. 4902 Expr *FirstArg = TheCall->getArg(0); 4903 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4904 if (FirstArgResult.isInvalid()) 4905 return ExprError(); 4906 FirstArg = FirstArgResult.get(); 4907 TheCall->setArg(0, FirstArg); 4908 4909 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4910 if (!pointerType) { 4911 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4912 << FirstArg->getType() << FirstArg->getSourceRange(); 4913 return ExprError(); 4914 } 4915 4916 QualType ValType = pointerType->getPointeeType(); 4917 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4918 !ValType->isBlockPointerType()) { 4919 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4920 << FirstArg->getType() << FirstArg->getSourceRange(); 4921 return ExprError(); 4922 } 4923 4924 if (ValType.isConstQualified()) { 4925 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4926 << FirstArg->getType() << FirstArg->getSourceRange(); 4927 return ExprError(); 4928 } 4929 4930 switch (ValType.getObjCLifetime()) { 4931 case Qualifiers::OCL_None: 4932 case Qualifiers::OCL_ExplicitNone: 4933 // okay 4934 break; 4935 4936 case Qualifiers::OCL_Weak: 4937 case Qualifiers::OCL_Strong: 4938 case Qualifiers::OCL_Autoreleasing: 4939 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4940 << ValType << FirstArg->getSourceRange(); 4941 return ExprError(); 4942 } 4943 4944 // Strip any qualifiers off ValType. 4945 ValType = ValType.getUnqualifiedType(); 4946 4947 // The majority of builtins return a value, but a few have special return 4948 // types, so allow them to override appropriately below. 4949 QualType ResultType = ValType; 4950 4951 // We need to figure out which concrete builtin this maps onto. For example, 4952 // __sync_fetch_and_add with a 2 byte object turns into 4953 // __sync_fetch_and_add_2. 4954 #define BUILTIN_ROW(x) \ 4955 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4956 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4957 4958 static const unsigned BuiltinIndices[][5] = { 4959 BUILTIN_ROW(__sync_fetch_and_add), 4960 BUILTIN_ROW(__sync_fetch_and_sub), 4961 BUILTIN_ROW(__sync_fetch_and_or), 4962 BUILTIN_ROW(__sync_fetch_and_and), 4963 BUILTIN_ROW(__sync_fetch_and_xor), 4964 BUILTIN_ROW(__sync_fetch_and_nand), 4965 4966 BUILTIN_ROW(__sync_add_and_fetch), 4967 BUILTIN_ROW(__sync_sub_and_fetch), 4968 BUILTIN_ROW(__sync_and_and_fetch), 4969 BUILTIN_ROW(__sync_or_and_fetch), 4970 BUILTIN_ROW(__sync_xor_and_fetch), 4971 BUILTIN_ROW(__sync_nand_and_fetch), 4972 4973 BUILTIN_ROW(__sync_val_compare_and_swap), 4974 BUILTIN_ROW(__sync_bool_compare_and_swap), 4975 BUILTIN_ROW(__sync_lock_test_and_set), 4976 BUILTIN_ROW(__sync_lock_release), 4977 BUILTIN_ROW(__sync_swap) 4978 }; 4979 #undef BUILTIN_ROW 4980 4981 // Determine the index of the size. 4982 unsigned SizeIndex; 4983 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4984 case 1: SizeIndex = 0; break; 4985 case 2: SizeIndex = 1; break; 4986 case 4: SizeIndex = 2; break; 4987 case 8: SizeIndex = 3; break; 4988 case 16: SizeIndex = 4; break; 4989 default: 4990 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4991 << FirstArg->getType() << FirstArg->getSourceRange(); 4992 return ExprError(); 4993 } 4994 4995 // Each of these builtins has one pointer argument, followed by some number of 4996 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4997 // that we ignore. Find out which row of BuiltinIndices to read from as well 4998 // as the number of fixed args. 4999 unsigned BuiltinID = FDecl->getBuiltinID(); 5000 unsigned BuiltinIndex, NumFixed = 1; 5001 bool WarnAboutSemanticsChange = false; 5002 switch (BuiltinID) { 5003 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5004 case Builtin::BI__sync_fetch_and_add: 5005 case Builtin::BI__sync_fetch_and_add_1: 5006 case Builtin::BI__sync_fetch_and_add_2: 5007 case Builtin::BI__sync_fetch_and_add_4: 5008 case Builtin::BI__sync_fetch_and_add_8: 5009 case Builtin::BI__sync_fetch_and_add_16: 5010 BuiltinIndex = 0; 5011 break; 5012 5013 case Builtin::BI__sync_fetch_and_sub: 5014 case Builtin::BI__sync_fetch_and_sub_1: 5015 case Builtin::BI__sync_fetch_and_sub_2: 5016 case Builtin::BI__sync_fetch_and_sub_4: 5017 case Builtin::BI__sync_fetch_and_sub_8: 5018 case Builtin::BI__sync_fetch_and_sub_16: 5019 BuiltinIndex = 1; 5020 break; 5021 5022 case Builtin::BI__sync_fetch_and_or: 5023 case Builtin::BI__sync_fetch_and_or_1: 5024 case Builtin::BI__sync_fetch_and_or_2: 5025 case Builtin::BI__sync_fetch_and_or_4: 5026 case Builtin::BI__sync_fetch_and_or_8: 5027 case Builtin::BI__sync_fetch_and_or_16: 5028 BuiltinIndex = 2; 5029 break; 5030 5031 case Builtin::BI__sync_fetch_and_and: 5032 case Builtin::BI__sync_fetch_and_and_1: 5033 case Builtin::BI__sync_fetch_and_and_2: 5034 case Builtin::BI__sync_fetch_and_and_4: 5035 case Builtin::BI__sync_fetch_and_and_8: 5036 case Builtin::BI__sync_fetch_and_and_16: 5037 BuiltinIndex = 3; 5038 break; 5039 5040 case Builtin::BI__sync_fetch_and_xor: 5041 case Builtin::BI__sync_fetch_and_xor_1: 5042 case Builtin::BI__sync_fetch_and_xor_2: 5043 case Builtin::BI__sync_fetch_and_xor_4: 5044 case Builtin::BI__sync_fetch_and_xor_8: 5045 case Builtin::BI__sync_fetch_and_xor_16: 5046 BuiltinIndex = 4; 5047 break; 5048 5049 case Builtin::BI__sync_fetch_and_nand: 5050 case Builtin::BI__sync_fetch_and_nand_1: 5051 case Builtin::BI__sync_fetch_and_nand_2: 5052 case Builtin::BI__sync_fetch_and_nand_4: 5053 case Builtin::BI__sync_fetch_and_nand_8: 5054 case Builtin::BI__sync_fetch_and_nand_16: 5055 BuiltinIndex = 5; 5056 WarnAboutSemanticsChange = true; 5057 break; 5058 5059 case Builtin::BI__sync_add_and_fetch: 5060 case Builtin::BI__sync_add_and_fetch_1: 5061 case Builtin::BI__sync_add_and_fetch_2: 5062 case Builtin::BI__sync_add_and_fetch_4: 5063 case Builtin::BI__sync_add_and_fetch_8: 5064 case Builtin::BI__sync_add_and_fetch_16: 5065 BuiltinIndex = 6; 5066 break; 5067 5068 case Builtin::BI__sync_sub_and_fetch: 5069 case Builtin::BI__sync_sub_and_fetch_1: 5070 case Builtin::BI__sync_sub_and_fetch_2: 5071 case Builtin::BI__sync_sub_and_fetch_4: 5072 case Builtin::BI__sync_sub_and_fetch_8: 5073 case Builtin::BI__sync_sub_and_fetch_16: 5074 BuiltinIndex = 7; 5075 break; 5076 5077 case Builtin::BI__sync_and_and_fetch: 5078 case Builtin::BI__sync_and_and_fetch_1: 5079 case Builtin::BI__sync_and_and_fetch_2: 5080 case Builtin::BI__sync_and_and_fetch_4: 5081 case Builtin::BI__sync_and_and_fetch_8: 5082 case Builtin::BI__sync_and_and_fetch_16: 5083 BuiltinIndex = 8; 5084 break; 5085 5086 case Builtin::BI__sync_or_and_fetch: 5087 case Builtin::BI__sync_or_and_fetch_1: 5088 case Builtin::BI__sync_or_and_fetch_2: 5089 case Builtin::BI__sync_or_and_fetch_4: 5090 case Builtin::BI__sync_or_and_fetch_8: 5091 case Builtin::BI__sync_or_and_fetch_16: 5092 BuiltinIndex = 9; 5093 break; 5094 5095 case Builtin::BI__sync_xor_and_fetch: 5096 case Builtin::BI__sync_xor_and_fetch_1: 5097 case Builtin::BI__sync_xor_and_fetch_2: 5098 case Builtin::BI__sync_xor_and_fetch_4: 5099 case Builtin::BI__sync_xor_and_fetch_8: 5100 case Builtin::BI__sync_xor_and_fetch_16: 5101 BuiltinIndex = 10; 5102 break; 5103 5104 case Builtin::BI__sync_nand_and_fetch: 5105 case Builtin::BI__sync_nand_and_fetch_1: 5106 case Builtin::BI__sync_nand_and_fetch_2: 5107 case Builtin::BI__sync_nand_and_fetch_4: 5108 case Builtin::BI__sync_nand_and_fetch_8: 5109 case Builtin::BI__sync_nand_and_fetch_16: 5110 BuiltinIndex = 11; 5111 WarnAboutSemanticsChange = true; 5112 break; 5113 5114 case Builtin::BI__sync_val_compare_and_swap: 5115 case Builtin::BI__sync_val_compare_and_swap_1: 5116 case Builtin::BI__sync_val_compare_and_swap_2: 5117 case Builtin::BI__sync_val_compare_and_swap_4: 5118 case Builtin::BI__sync_val_compare_and_swap_8: 5119 case Builtin::BI__sync_val_compare_and_swap_16: 5120 BuiltinIndex = 12; 5121 NumFixed = 2; 5122 break; 5123 5124 case Builtin::BI__sync_bool_compare_and_swap: 5125 case Builtin::BI__sync_bool_compare_and_swap_1: 5126 case Builtin::BI__sync_bool_compare_and_swap_2: 5127 case Builtin::BI__sync_bool_compare_and_swap_4: 5128 case Builtin::BI__sync_bool_compare_and_swap_8: 5129 case Builtin::BI__sync_bool_compare_and_swap_16: 5130 BuiltinIndex = 13; 5131 NumFixed = 2; 5132 ResultType = Context.BoolTy; 5133 break; 5134 5135 case Builtin::BI__sync_lock_test_and_set: 5136 case Builtin::BI__sync_lock_test_and_set_1: 5137 case Builtin::BI__sync_lock_test_and_set_2: 5138 case Builtin::BI__sync_lock_test_and_set_4: 5139 case Builtin::BI__sync_lock_test_and_set_8: 5140 case Builtin::BI__sync_lock_test_and_set_16: 5141 BuiltinIndex = 14; 5142 break; 5143 5144 case Builtin::BI__sync_lock_release: 5145 case Builtin::BI__sync_lock_release_1: 5146 case Builtin::BI__sync_lock_release_2: 5147 case Builtin::BI__sync_lock_release_4: 5148 case Builtin::BI__sync_lock_release_8: 5149 case Builtin::BI__sync_lock_release_16: 5150 BuiltinIndex = 15; 5151 NumFixed = 0; 5152 ResultType = Context.VoidTy; 5153 break; 5154 5155 case Builtin::BI__sync_swap: 5156 case Builtin::BI__sync_swap_1: 5157 case Builtin::BI__sync_swap_2: 5158 case Builtin::BI__sync_swap_4: 5159 case Builtin::BI__sync_swap_8: 5160 case Builtin::BI__sync_swap_16: 5161 BuiltinIndex = 16; 5162 break; 5163 } 5164 5165 // Now that we know how many fixed arguments we expect, first check that we 5166 // have at least that many. 5167 if (TheCall->getNumArgs() < 1+NumFixed) { 5168 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5169 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5170 << Callee->getSourceRange(); 5171 return ExprError(); 5172 } 5173 5174 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5175 << Callee->getSourceRange(); 5176 5177 if (WarnAboutSemanticsChange) { 5178 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5179 << Callee->getSourceRange(); 5180 } 5181 5182 // Get the decl for the concrete builtin from this, we can tell what the 5183 // concrete integer type we should convert to is. 5184 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5185 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5186 FunctionDecl *NewBuiltinDecl; 5187 if (NewBuiltinID == BuiltinID) 5188 NewBuiltinDecl = FDecl; 5189 else { 5190 // Perform builtin lookup to avoid redeclaring it. 5191 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5192 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5193 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5194 assert(Res.getFoundDecl()); 5195 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5196 if (!NewBuiltinDecl) 5197 return ExprError(); 5198 } 5199 5200 // The first argument --- the pointer --- has a fixed type; we 5201 // deduce the types of the rest of the arguments accordingly. Walk 5202 // the remaining arguments, converting them to the deduced value type. 5203 for (unsigned i = 0; i != NumFixed; ++i) { 5204 ExprResult Arg = TheCall->getArg(i+1); 5205 5206 // GCC does an implicit conversion to the pointer or integer ValType. This 5207 // can fail in some cases (1i -> int**), check for this error case now. 5208 // Initialize the argument. 5209 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5210 ValType, /*consume*/ false); 5211 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5212 if (Arg.isInvalid()) 5213 return ExprError(); 5214 5215 // Okay, we have something that *can* be converted to the right type. Check 5216 // to see if there is a potentially weird extension going on here. This can 5217 // happen when you do an atomic operation on something like an char* and 5218 // pass in 42. The 42 gets converted to char. This is even more strange 5219 // for things like 45.123 -> char, etc. 5220 // FIXME: Do this check. 5221 TheCall->setArg(i+1, Arg.get()); 5222 } 5223 5224 // Create a new DeclRefExpr to refer to the new decl. 5225 DeclRefExpr* NewDRE = DeclRefExpr::Create( 5226 Context, 5227 DRE->getQualifierLoc(), 5228 SourceLocation(), 5229 NewBuiltinDecl, 5230 /*enclosing*/ false, 5231 DRE->getLocation(), 5232 Context.BuiltinFnTy, 5233 DRE->getValueKind()); 5234 5235 // Set the callee in the CallExpr. 5236 // FIXME: This loses syntactic information. 5237 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5238 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5239 CK_BuiltinFnToFnPtr); 5240 TheCall->setCallee(PromotedCall.get()); 5241 5242 // Change the result type of the call to match the original value type. This 5243 // is arbitrary, but the codegen for these builtins ins design to handle it 5244 // gracefully. 5245 TheCall->setType(ResultType); 5246 5247 return TheCallResult; 5248 } 5249 5250 /// SemaBuiltinNontemporalOverloaded - We have a call to 5251 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5252 /// overloaded function based on the pointer type of its last argument. 5253 /// 5254 /// This function goes through and does final semantic checking for these 5255 /// builtins. 5256 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5257 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5258 DeclRefExpr *DRE = 5259 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5260 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5261 unsigned BuiltinID = FDecl->getBuiltinID(); 5262 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5263 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5264 "Unexpected nontemporal load/store builtin!"); 5265 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5266 unsigned numArgs = isStore ? 2 : 1; 5267 5268 // Ensure that we have the proper number of arguments. 5269 if (checkArgCount(*this, TheCall, numArgs)) 5270 return ExprError(); 5271 5272 // Inspect the last argument of the nontemporal builtin. This should always 5273 // be a pointer type, from which we imply the type of the memory access. 5274 // Because it is a pointer type, we don't have to worry about any implicit 5275 // casts here. 5276 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5277 ExprResult PointerArgResult = 5278 DefaultFunctionArrayLvalueConversion(PointerArg); 5279 5280 if (PointerArgResult.isInvalid()) 5281 return ExprError(); 5282 PointerArg = PointerArgResult.get(); 5283 TheCall->setArg(numArgs - 1, PointerArg); 5284 5285 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5286 if (!pointerType) { 5287 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5288 << PointerArg->getType() << PointerArg->getSourceRange(); 5289 return ExprError(); 5290 } 5291 5292 QualType ValType = pointerType->getPointeeType(); 5293 5294 // Strip any qualifiers off ValType. 5295 ValType = ValType.getUnqualifiedType(); 5296 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5297 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5298 !ValType->isVectorType()) { 5299 Diag(DRE->getBeginLoc(), 5300 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5301 << PointerArg->getType() << PointerArg->getSourceRange(); 5302 return ExprError(); 5303 } 5304 5305 if (!isStore) { 5306 TheCall->setType(ValType); 5307 return TheCallResult; 5308 } 5309 5310 ExprResult ValArg = TheCall->getArg(0); 5311 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5312 Context, ValType, /*consume*/ false); 5313 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5314 if (ValArg.isInvalid()) 5315 return ExprError(); 5316 5317 TheCall->setArg(0, ValArg.get()); 5318 TheCall->setType(Context.VoidTy); 5319 return TheCallResult; 5320 } 5321 5322 /// CheckObjCString - Checks that the argument to the builtin 5323 /// CFString constructor is correct 5324 /// Note: It might also make sense to do the UTF-16 conversion here (would 5325 /// simplify the backend). 5326 bool Sema::CheckObjCString(Expr *Arg) { 5327 Arg = Arg->IgnoreParenCasts(); 5328 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5329 5330 if (!Literal || !Literal->isAscii()) { 5331 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5332 << Arg->getSourceRange(); 5333 return true; 5334 } 5335 5336 if (Literal->containsNonAsciiOrNull()) { 5337 StringRef String = Literal->getString(); 5338 unsigned NumBytes = String.size(); 5339 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5340 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5341 llvm::UTF16 *ToPtr = &ToBuf[0]; 5342 5343 llvm::ConversionResult Result = 5344 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5345 ToPtr + NumBytes, llvm::strictConversion); 5346 // Check for conversion failure. 5347 if (Result != llvm::conversionOK) 5348 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5349 << Arg->getSourceRange(); 5350 } 5351 return false; 5352 } 5353 5354 /// CheckObjCString - Checks that the format string argument to the os_log() 5355 /// and os_trace() functions is correct, and converts it to const char *. 5356 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5357 Arg = Arg->IgnoreParenCasts(); 5358 auto *Literal = dyn_cast<StringLiteral>(Arg); 5359 if (!Literal) { 5360 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5361 Literal = ObjcLiteral->getString(); 5362 } 5363 } 5364 5365 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5366 return ExprError( 5367 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5368 << Arg->getSourceRange()); 5369 } 5370 5371 ExprResult Result(Literal); 5372 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5373 InitializedEntity Entity = 5374 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5375 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5376 return Result; 5377 } 5378 5379 /// Check that the user is calling the appropriate va_start builtin for the 5380 /// target and calling convention. 5381 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5382 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5383 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5384 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5385 bool IsWindows = TT.isOSWindows(); 5386 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5387 if (IsX64 || IsAArch64) { 5388 CallingConv CC = CC_C; 5389 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5390 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5391 if (IsMSVAStart) { 5392 // Don't allow this in System V ABI functions. 5393 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5394 return S.Diag(Fn->getBeginLoc(), 5395 diag::err_ms_va_start_used_in_sysv_function); 5396 } else { 5397 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5398 // On x64 Windows, don't allow this in System V ABI functions. 5399 // (Yes, that means there's no corresponding way to support variadic 5400 // System V ABI functions on Windows.) 5401 if ((IsWindows && CC == CC_X86_64SysV) || 5402 (!IsWindows && CC == CC_Win64)) 5403 return S.Diag(Fn->getBeginLoc(), 5404 diag::err_va_start_used_in_wrong_abi_function) 5405 << !IsWindows; 5406 } 5407 return false; 5408 } 5409 5410 if (IsMSVAStart) 5411 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5412 return false; 5413 } 5414 5415 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5416 ParmVarDecl **LastParam = nullptr) { 5417 // Determine whether the current function, block, or obj-c method is variadic 5418 // and get its parameter list. 5419 bool IsVariadic = false; 5420 ArrayRef<ParmVarDecl *> Params; 5421 DeclContext *Caller = S.CurContext; 5422 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5423 IsVariadic = Block->isVariadic(); 5424 Params = Block->parameters(); 5425 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5426 IsVariadic = FD->isVariadic(); 5427 Params = FD->parameters(); 5428 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5429 IsVariadic = MD->isVariadic(); 5430 // FIXME: This isn't correct for methods (results in bogus warning). 5431 Params = MD->parameters(); 5432 } else if (isa<CapturedDecl>(Caller)) { 5433 // We don't support va_start in a CapturedDecl. 5434 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5435 return true; 5436 } else { 5437 // This must be some other declcontext that parses exprs. 5438 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5439 return true; 5440 } 5441 5442 if (!IsVariadic) { 5443 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5444 return true; 5445 } 5446 5447 if (LastParam) 5448 *LastParam = Params.empty() ? nullptr : Params.back(); 5449 5450 return false; 5451 } 5452 5453 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5454 /// for validity. Emit an error and return true on failure; return false 5455 /// on success. 5456 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5457 Expr *Fn = TheCall->getCallee(); 5458 5459 if (checkVAStartABI(*this, BuiltinID, Fn)) 5460 return true; 5461 5462 if (TheCall->getNumArgs() > 2) { 5463 Diag(TheCall->getArg(2)->getBeginLoc(), 5464 diag::err_typecheck_call_too_many_args) 5465 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5466 << Fn->getSourceRange() 5467 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5468 (*(TheCall->arg_end() - 1))->getEndLoc()); 5469 return true; 5470 } 5471 5472 if (TheCall->getNumArgs() < 2) { 5473 return Diag(TheCall->getEndLoc(), 5474 diag::err_typecheck_call_too_few_args_at_least) 5475 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5476 } 5477 5478 // Type-check the first argument normally. 5479 if (checkBuiltinArgument(*this, TheCall, 0)) 5480 return true; 5481 5482 // Check that the current function is variadic, and get its last parameter. 5483 ParmVarDecl *LastParam; 5484 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5485 return true; 5486 5487 // Verify that the second argument to the builtin is the last argument of the 5488 // current function or method. 5489 bool SecondArgIsLastNamedArgument = false; 5490 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5491 5492 // These are valid if SecondArgIsLastNamedArgument is false after the next 5493 // block. 5494 QualType Type; 5495 SourceLocation ParamLoc; 5496 bool IsCRegister = false; 5497 5498 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5499 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5500 SecondArgIsLastNamedArgument = PV == LastParam; 5501 5502 Type = PV->getType(); 5503 ParamLoc = PV->getLocation(); 5504 IsCRegister = 5505 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5506 } 5507 } 5508 5509 if (!SecondArgIsLastNamedArgument) 5510 Diag(TheCall->getArg(1)->getBeginLoc(), 5511 diag::warn_second_arg_of_va_start_not_last_named_param); 5512 else if (IsCRegister || Type->isReferenceType() || 5513 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5514 // Promotable integers are UB, but enumerations need a bit of 5515 // extra checking to see what their promotable type actually is. 5516 if (!Type->isPromotableIntegerType()) 5517 return false; 5518 if (!Type->isEnumeralType()) 5519 return true; 5520 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5521 return !(ED && 5522 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5523 }()) { 5524 unsigned Reason = 0; 5525 if (Type->isReferenceType()) Reason = 1; 5526 else if (IsCRegister) Reason = 2; 5527 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5528 Diag(ParamLoc, diag::note_parameter_type) << Type; 5529 } 5530 5531 TheCall->setType(Context.VoidTy); 5532 return false; 5533 } 5534 5535 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5536 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5537 // const char *named_addr); 5538 5539 Expr *Func = Call->getCallee(); 5540 5541 if (Call->getNumArgs() < 3) 5542 return Diag(Call->getEndLoc(), 5543 diag::err_typecheck_call_too_few_args_at_least) 5544 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5545 5546 // Type-check the first argument normally. 5547 if (checkBuiltinArgument(*this, Call, 0)) 5548 return true; 5549 5550 // Check that the current function is variadic. 5551 if (checkVAStartIsInVariadicFunction(*this, Func)) 5552 return true; 5553 5554 // __va_start on Windows does not validate the parameter qualifiers 5555 5556 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5557 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5558 5559 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5560 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5561 5562 const QualType &ConstCharPtrTy = 5563 Context.getPointerType(Context.CharTy.withConst()); 5564 if (!Arg1Ty->isPointerType() || 5565 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5566 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5567 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5568 << 0 /* qualifier difference */ 5569 << 3 /* parameter mismatch */ 5570 << 2 << Arg1->getType() << ConstCharPtrTy; 5571 5572 const QualType SizeTy = Context.getSizeType(); 5573 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5574 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5575 << Arg2->getType() << SizeTy << 1 /* different class */ 5576 << 0 /* qualifier difference */ 5577 << 3 /* parameter mismatch */ 5578 << 3 << Arg2->getType() << SizeTy; 5579 5580 return false; 5581 } 5582 5583 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5584 /// friends. This is declared to take (...), so we have to check everything. 5585 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5586 if (TheCall->getNumArgs() < 2) 5587 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5588 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5589 if (TheCall->getNumArgs() > 2) 5590 return Diag(TheCall->getArg(2)->getBeginLoc(), 5591 diag::err_typecheck_call_too_many_args) 5592 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5593 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5594 (*(TheCall->arg_end() - 1))->getEndLoc()); 5595 5596 ExprResult OrigArg0 = TheCall->getArg(0); 5597 ExprResult OrigArg1 = TheCall->getArg(1); 5598 5599 // Do standard promotions between the two arguments, returning their common 5600 // type. 5601 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5602 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5603 return true; 5604 5605 // Make sure any conversions are pushed back into the call; this is 5606 // type safe since unordered compare builtins are declared as "_Bool 5607 // foo(...)". 5608 TheCall->setArg(0, OrigArg0.get()); 5609 TheCall->setArg(1, OrigArg1.get()); 5610 5611 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5612 return false; 5613 5614 // If the common type isn't a real floating type, then the arguments were 5615 // invalid for this operation. 5616 if (Res.isNull() || !Res->isRealFloatingType()) 5617 return Diag(OrigArg0.get()->getBeginLoc(), 5618 diag::err_typecheck_call_invalid_ordered_compare) 5619 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5620 << SourceRange(OrigArg0.get()->getBeginLoc(), 5621 OrigArg1.get()->getEndLoc()); 5622 5623 return false; 5624 } 5625 5626 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5627 /// __builtin_isnan and friends. This is declared to take (...), so we have 5628 /// to check everything. We expect the last argument to be a floating point 5629 /// value. 5630 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5631 if (TheCall->getNumArgs() < NumArgs) 5632 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5633 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5634 if (TheCall->getNumArgs() > NumArgs) 5635 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5636 diag::err_typecheck_call_too_many_args) 5637 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5638 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5639 (*(TheCall->arg_end() - 1))->getEndLoc()); 5640 5641 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5642 5643 if (OrigArg->isTypeDependent()) 5644 return false; 5645 5646 // This operation requires a non-_Complex floating-point number. 5647 if (!OrigArg->getType()->isRealFloatingType()) 5648 return Diag(OrigArg->getBeginLoc(), 5649 diag::err_typecheck_call_invalid_unary_fp) 5650 << OrigArg->getType() << OrigArg->getSourceRange(); 5651 5652 // If this is an implicit conversion from float -> float, double, or 5653 // long double, remove it. 5654 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5655 // Only remove standard FloatCasts, leaving other casts inplace 5656 if (Cast->getCastKind() == CK_FloatingCast) { 5657 Expr *CastArg = Cast->getSubExpr(); 5658 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5659 assert( 5660 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5661 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5662 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5663 "promotion from float to either float, double, or long double is " 5664 "the only expected cast here"); 5665 Cast->setSubExpr(nullptr); 5666 TheCall->setArg(NumArgs-1, CastArg); 5667 } 5668 } 5669 } 5670 5671 return false; 5672 } 5673 5674 // Customized Sema Checking for VSX builtins that have the following signature: 5675 // vector [...] builtinName(vector [...], vector [...], const int); 5676 // Which takes the same type of vectors (any legal vector type) for the first 5677 // two arguments and takes compile time constant for the third argument. 5678 // Example builtins are : 5679 // vector double vec_xxpermdi(vector double, vector double, int); 5680 // vector short vec_xxsldwi(vector short, vector short, int); 5681 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5682 unsigned ExpectedNumArgs = 3; 5683 if (TheCall->getNumArgs() < ExpectedNumArgs) 5684 return Diag(TheCall->getEndLoc(), 5685 diag::err_typecheck_call_too_few_args_at_least) 5686 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5687 << TheCall->getSourceRange(); 5688 5689 if (TheCall->getNumArgs() > ExpectedNumArgs) 5690 return Diag(TheCall->getEndLoc(), 5691 diag::err_typecheck_call_too_many_args_at_most) 5692 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5693 << TheCall->getSourceRange(); 5694 5695 // Check the third argument is a compile time constant 5696 llvm::APSInt Value; 5697 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5698 return Diag(TheCall->getBeginLoc(), 5699 diag::err_vsx_builtin_nonconstant_argument) 5700 << 3 /* argument index */ << TheCall->getDirectCallee() 5701 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5702 TheCall->getArg(2)->getEndLoc()); 5703 5704 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5705 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5706 5707 // Check the type of argument 1 and argument 2 are vectors. 5708 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5709 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5710 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5711 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5712 << TheCall->getDirectCallee() 5713 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5714 TheCall->getArg(1)->getEndLoc()); 5715 } 5716 5717 // Check the first two arguments are the same type. 5718 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5719 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5720 << TheCall->getDirectCallee() 5721 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5722 TheCall->getArg(1)->getEndLoc()); 5723 } 5724 5725 // When default clang type checking is turned off and the customized type 5726 // checking is used, the returning type of the function must be explicitly 5727 // set. Otherwise it is _Bool by default. 5728 TheCall->setType(Arg1Ty); 5729 5730 return false; 5731 } 5732 5733 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5734 // This is declared to take (...), so we have to check everything. 5735 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5736 if (TheCall->getNumArgs() < 2) 5737 return ExprError(Diag(TheCall->getEndLoc(), 5738 diag::err_typecheck_call_too_few_args_at_least) 5739 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5740 << TheCall->getSourceRange()); 5741 5742 // Determine which of the following types of shufflevector we're checking: 5743 // 1) unary, vector mask: (lhs, mask) 5744 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5745 QualType resType = TheCall->getArg(0)->getType(); 5746 unsigned numElements = 0; 5747 5748 if (!TheCall->getArg(0)->isTypeDependent() && 5749 !TheCall->getArg(1)->isTypeDependent()) { 5750 QualType LHSType = TheCall->getArg(0)->getType(); 5751 QualType RHSType = TheCall->getArg(1)->getType(); 5752 5753 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5754 return ExprError( 5755 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5756 << TheCall->getDirectCallee() 5757 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5758 TheCall->getArg(1)->getEndLoc())); 5759 5760 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5761 unsigned numResElements = TheCall->getNumArgs() - 2; 5762 5763 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5764 // with mask. If so, verify that RHS is an integer vector type with the 5765 // same number of elts as lhs. 5766 if (TheCall->getNumArgs() == 2) { 5767 if (!RHSType->hasIntegerRepresentation() || 5768 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5769 return ExprError(Diag(TheCall->getBeginLoc(), 5770 diag::err_vec_builtin_incompatible_vector) 5771 << TheCall->getDirectCallee() 5772 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5773 TheCall->getArg(1)->getEndLoc())); 5774 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5775 return ExprError(Diag(TheCall->getBeginLoc(), 5776 diag::err_vec_builtin_incompatible_vector) 5777 << TheCall->getDirectCallee() 5778 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5779 TheCall->getArg(1)->getEndLoc())); 5780 } else if (numElements != numResElements) { 5781 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5782 resType = Context.getVectorType(eltType, numResElements, 5783 VectorType::GenericVector); 5784 } 5785 } 5786 5787 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5788 if (TheCall->getArg(i)->isTypeDependent() || 5789 TheCall->getArg(i)->isValueDependent()) 5790 continue; 5791 5792 llvm::APSInt Result(32); 5793 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5794 return ExprError(Diag(TheCall->getBeginLoc(), 5795 diag::err_shufflevector_nonconstant_argument) 5796 << TheCall->getArg(i)->getSourceRange()); 5797 5798 // Allow -1 which will be translated to undef in the IR. 5799 if (Result.isSigned() && Result.isAllOnesValue()) 5800 continue; 5801 5802 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5803 return ExprError(Diag(TheCall->getBeginLoc(), 5804 diag::err_shufflevector_argument_too_large) 5805 << TheCall->getArg(i)->getSourceRange()); 5806 } 5807 5808 SmallVector<Expr*, 32> exprs; 5809 5810 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5811 exprs.push_back(TheCall->getArg(i)); 5812 TheCall->setArg(i, nullptr); 5813 } 5814 5815 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5816 TheCall->getCallee()->getBeginLoc(), 5817 TheCall->getRParenLoc()); 5818 } 5819 5820 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5821 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5822 SourceLocation BuiltinLoc, 5823 SourceLocation RParenLoc) { 5824 ExprValueKind VK = VK_RValue; 5825 ExprObjectKind OK = OK_Ordinary; 5826 QualType DstTy = TInfo->getType(); 5827 QualType SrcTy = E->getType(); 5828 5829 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5830 return ExprError(Diag(BuiltinLoc, 5831 diag::err_convertvector_non_vector) 5832 << E->getSourceRange()); 5833 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5834 return ExprError(Diag(BuiltinLoc, 5835 diag::err_convertvector_non_vector_type)); 5836 5837 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5838 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5839 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5840 if (SrcElts != DstElts) 5841 return ExprError(Diag(BuiltinLoc, 5842 diag::err_convertvector_incompatible_vector) 5843 << E->getSourceRange()); 5844 } 5845 5846 return new (Context) 5847 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5848 } 5849 5850 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5851 // This is declared to take (const void*, ...) and can take two 5852 // optional constant int args. 5853 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5854 unsigned NumArgs = TheCall->getNumArgs(); 5855 5856 if (NumArgs > 3) 5857 return Diag(TheCall->getEndLoc(), 5858 diag::err_typecheck_call_too_many_args_at_most) 5859 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5860 5861 // Argument 0 is checked for us and the remaining arguments must be 5862 // constant integers. 5863 for (unsigned i = 1; i != NumArgs; ++i) 5864 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5865 return true; 5866 5867 return false; 5868 } 5869 5870 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5871 // __assume does not evaluate its arguments, and should warn if its argument 5872 // has side effects. 5873 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5874 Expr *Arg = TheCall->getArg(0); 5875 if (Arg->isInstantiationDependent()) return false; 5876 5877 if (Arg->HasSideEffects(Context)) 5878 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5879 << Arg->getSourceRange() 5880 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5881 5882 return false; 5883 } 5884 5885 /// Handle __builtin_alloca_with_align. This is declared 5886 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5887 /// than 8. 5888 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5889 // The alignment must be a constant integer. 5890 Expr *Arg = TheCall->getArg(1); 5891 5892 // We can't check the value of a dependent argument. 5893 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5894 if (const auto *UE = 5895 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5896 if (UE->getKind() == UETT_AlignOf || 5897 UE->getKind() == UETT_PreferredAlignOf) 5898 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5899 << Arg->getSourceRange(); 5900 5901 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5902 5903 if (!Result.isPowerOf2()) 5904 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5905 << Arg->getSourceRange(); 5906 5907 if (Result < Context.getCharWidth()) 5908 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5909 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5910 5911 if (Result > std::numeric_limits<int32_t>::max()) 5912 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5913 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5914 } 5915 5916 return false; 5917 } 5918 5919 /// Handle __builtin_assume_aligned. This is declared 5920 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5921 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5922 unsigned NumArgs = TheCall->getNumArgs(); 5923 5924 if (NumArgs > 3) 5925 return Diag(TheCall->getEndLoc(), 5926 diag::err_typecheck_call_too_many_args_at_most) 5927 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5928 5929 // The alignment must be a constant integer. 5930 Expr *Arg = TheCall->getArg(1); 5931 5932 // We can't check the value of a dependent argument. 5933 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5934 llvm::APSInt Result; 5935 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5936 return true; 5937 5938 if (!Result.isPowerOf2()) 5939 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5940 << Arg->getSourceRange(); 5941 } 5942 5943 if (NumArgs > 2) { 5944 ExprResult Arg(TheCall->getArg(2)); 5945 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5946 Context.getSizeType(), false); 5947 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5948 if (Arg.isInvalid()) return true; 5949 TheCall->setArg(2, Arg.get()); 5950 } 5951 5952 return false; 5953 } 5954 5955 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5956 unsigned BuiltinID = 5957 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5958 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5959 5960 unsigned NumArgs = TheCall->getNumArgs(); 5961 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5962 if (NumArgs < NumRequiredArgs) { 5963 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5964 << 0 /* function call */ << NumRequiredArgs << NumArgs 5965 << TheCall->getSourceRange(); 5966 } 5967 if (NumArgs >= NumRequiredArgs + 0x100) { 5968 return Diag(TheCall->getEndLoc(), 5969 diag::err_typecheck_call_too_many_args_at_most) 5970 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5971 << TheCall->getSourceRange(); 5972 } 5973 unsigned i = 0; 5974 5975 // For formatting call, check buffer arg. 5976 if (!IsSizeCall) { 5977 ExprResult Arg(TheCall->getArg(i)); 5978 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5979 Context, Context.VoidPtrTy, false); 5980 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5981 if (Arg.isInvalid()) 5982 return true; 5983 TheCall->setArg(i, Arg.get()); 5984 i++; 5985 } 5986 5987 // Check string literal arg. 5988 unsigned FormatIdx = i; 5989 { 5990 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5991 if (Arg.isInvalid()) 5992 return true; 5993 TheCall->setArg(i, Arg.get()); 5994 i++; 5995 } 5996 5997 // Make sure variadic args are scalar. 5998 unsigned FirstDataArg = i; 5999 while (i < NumArgs) { 6000 ExprResult Arg = DefaultVariadicArgumentPromotion( 6001 TheCall->getArg(i), VariadicFunction, nullptr); 6002 if (Arg.isInvalid()) 6003 return true; 6004 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6005 if (ArgSize.getQuantity() >= 0x100) { 6006 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6007 << i << (int)ArgSize.getQuantity() << 0xff 6008 << TheCall->getSourceRange(); 6009 } 6010 TheCall->setArg(i, Arg.get()); 6011 i++; 6012 } 6013 6014 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6015 // call to avoid duplicate diagnostics. 6016 if (!IsSizeCall) { 6017 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6018 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6019 bool Success = CheckFormatArguments( 6020 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6021 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6022 CheckedVarArgs); 6023 if (!Success) 6024 return true; 6025 } 6026 6027 if (IsSizeCall) { 6028 TheCall->setType(Context.getSizeType()); 6029 } else { 6030 TheCall->setType(Context.VoidPtrTy); 6031 } 6032 return false; 6033 } 6034 6035 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6036 /// TheCall is a constant expression. 6037 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6038 llvm::APSInt &Result) { 6039 Expr *Arg = TheCall->getArg(ArgNum); 6040 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6041 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6042 6043 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6044 6045 if (!Arg->isIntegerConstantExpr(Result, Context)) 6046 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6047 << FDecl->getDeclName() << Arg->getSourceRange(); 6048 6049 return false; 6050 } 6051 6052 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6053 /// TheCall is a constant expression in the range [Low, High]. 6054 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6055 int Low, int High, bool RangeIsError) { 6056 llvm::APSInt Result; 6057 6058 // We can't check the value of a dependent argument. 6059 Expr *Arg = TheCall->getArg(ArgNum); 6060 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6061 return false; 6062 6063 // Check constant-ness first. 6064 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6065 return true; 6066 6067 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6068 if (RangeIsError) 6069 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6070 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6071 else 6072 // Defer the warning until we know if the code will be emitted so that 6073 // dead code can ignore this. 6074 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6075 PDiag(diag::warn_argument_invalid_range) 6076 << Result.toString(10) << Low << High 6077 << Arg->getSourceRange()); 6078 } 6079 6080 return false; 6081 } 6082 6083 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6084 /// TheCall is a constant expression is a multiple of Num.. 6085 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6086 unsigned Num) { 6087 llvm::APSInt Result; 6088 6089 // We can't check the value of a dependent argument. 6090 Expr *Arg = TheCall->getArg(ArgNum); 6091 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6092 return false; 6093 6094 // Check constant-ness first. 6095 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6096 return true; 6097 6098 if (Result.getSExtValue() % Num != 0) 6099 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6100 << Num << Arg->getSourceRange(); 6101 6102 return false; 6103 } 6104 6105 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6106 /// TheCall is an ARM/AArch64 special register string literal. 6107 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6108 int ArgNum, unsigned ExpectedFieldNum, 6109 bool AllowName) { 6110 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6111 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6112 BuiltinID == ARM::BI__builtin_arm_rsr || 6113 BuiltinID == ARM::BI__builtin_arm_rsrp || 6114 BuiltinID == ARM::BI__builtin_arm_wsr || 6115 BuiltinID == ARM::BI__builtin_arm_wsrp; 6116 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6117 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6118 BuiltinID == AArch64::BI__builtin_arm_rsr || 6119 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6120 BuiltinID == AArch64::BI__builtin_arm_wsr || 6121 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6122 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6123 6124 // We can't check the value of a dependent argument. 6125 Expr *Arg = TheCall->getArg(ArgNum); 6126 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6127 return false; 6128 6129 // Check if the argument is a string literal. 6130 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6131 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6132 << Arg->getSourceRange(); 6133 6134 // Check the type of special register given. 6135 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6136 SmallVector<StringRef, 6> Fields; 6137 Reg.split(Fields, ":"); 6138 6139 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6140 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6141 << Arg->getSourceRange(); 6142 6143 // If the string is the name of a register then we cannot check that it is 6144 // valid here but if the string is of one the forms described in ACLE then we 6145 // can check that the supplied fields are integers and within the valid 6146 // ranges. 6147 if (Fields.size() > 1) { 6148 bool FiveFields = Fields.size() == 5; 6149 6150 bool ValidString = true; 6151 if (IsARMBuiltin) { 6152 ValidString &= Fields[0].startswith_lower("cp") || 6153 Fields[0].startswith_lower("p"); 6154 if (ValidString) 6155 Fields[0] = 6156 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6157 6158 ValidString &= Fields[2].startswith_lower("c"); 6159 if (ValidString) 6160 Fields[2] = Fields[2].drop_front(1); 6161 6162 if (FiveFields) { 6163 ValidString &= Fields[3].startswith_lower("c"); 6164 if (ValidString) 6165 Fields[3] = Fields[3].drop_front(1); 6166 } 6167 } 6168 6169 SmallVector<int, 5> Ranges; 6170 if (FiveFields) 6171 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6172 else 6173 Ranges.append({15, 7, 15}); 6174 6175 for (unsigned i=0; i<Fields.size(); ++i) { 6176 int IntField; 6177 ValidString &= !Fields[i].getAsInteger(10, IntField); 6178 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6179 } 6180 6181 if (!ValidString) 6182 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6183 << Arg->getSourceRange(); 6184 } else if (IsAArch64Builtin && Fields.size() == 1) { 6185 // If the register name is one of those that appear in the condition below 6186 // and the special register builtin being used is one of the write builtins, 6187 // then we require that the argument provided for writing to the register 6188 // is an integer constant expression. This is because it will be lowered to 6189 // an MSR (immediate) instruction, so we need to know the immediate at 6190 // compile time. 6191 if (TheCall->getNumArgs() != 2) 6192 return false; 6193 6194 std::string RegLower = Reg.lower(); 6195 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6196 RegLower != "pan" && RegLower != "uao") 6197 return false; 6198 6199 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6200 } 6201 6202 return false; 6203 } 6204 6205 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6206 /// This checks that the target supports __builtin_longjmp and 6207 /// that val is a constant 1. 6208 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6209 if (!Context.getTargetInfo().hasSjLjLowering()) 6210 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6211 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6212 6213 Expr *Arg = TheCall->getArg(1); 6214 llvm::APSInt Result; 6215 6216 // TODO: This is less than ideal. Overload this to take a value. 6217 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6218 return true; 6219 6220 if (Result != 1) 6221 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6222 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6223 6224 return false; 6225 } 6226 6227 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6228 /// This checks that the target supports __builtin_setjmp. 6229 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6230 if (!Context.getTargetInfo().hasSjLjLowering()) 6231 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6232 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6233 return false; 6234 } 6235 6236 namespace { 6237 6238 class UncoveredArgHandler { 6239 enum { Unknown = -1, AllCovered = -2 }; 6240 6241 signed FirstUncoveredArg = Unknown; 6242 SmallVector<const Expr *, 4> DiagnosticExprs; 6243 6244 public: 6245 UncoveredArgHandler() = default; 6246 6247 bool hasUncoveredArg() const { 6248 return (FirstUncoveredArg >= 0); 6249 } 6250 6251 unsigned getUncoveredArg() const { 6252 assert(hasUncoveredArg() && "no uncovered argument"); 6253 return FirstUncoveredArg; 6254 } 6255 6256 void setAllCovered() { 6257 // A string has been found with all arguments covered, so clear out 6258 // the diagnostics. 6259 DiagnosticExprs.clear(); 6260 FirstUncoveredArg = AllCovered; 6261 } 6262 6263 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6264 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6265 6266 // Don't update if a previous string covers all arguments. 6267 if (FirstUncoveredArg == AllCovered) 6268 return; 6269 6270 // UncoveredArgHandler tracks the highest uncovered argument index 6271 // and with it all the strings that match this index. 6272 if (NewFirstUncoveredArg == FirstUncoveredArg) 6273 DiagnosticExprs.push_back(StrExpr); 6274 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6275 DiagnosticExprs.clear(); 6276 DiagnosticExprs.push_back(StrExpr); 6277 FirstUncoveredArg = NewFirstUncoveredArg; 6278 } 6279 } 6280 6281 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6282 }; 6283 6284 enum StringLiteralCheckType { 6285 SLCT_NotALiteral, 6286 SLCT_UncheckedLiteral, 6287 SLCT_CheckedLiteral 6288 }; 6289 6290 } // namespace 6291 6292 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6293 BinaryOperatorKind BinOpKind, 6294 bool AddendIsRight) { 6295 unsigned BitWidth = Offset.getBitWidth(); 6296 unsigned AddendBitWidth = Addend.getBitWidth(); 6297 // There might be negative interim results. 6298 if (Addend.isUnsigned()) { 6299 Addend = Addend.zext(++AddendBitWidth); 6300 Addend.setIsSigned(true); 6301 } 6302 // Adjust the bit width of the APSInts. 6303 if (AddendBitWidth > BitWidth) { 6304 Offset = Offset.sext(AddendBitWidth); 6305 BitWidth = AddendBitWidth; 6306 } else if (BitWidth > AddendBitWidth) { 6307 Addend = Addend.sext(BitWidth); 6308 } 6309 6310 bool Ov = false; 6311 llvm::APSInt ResOffset = Offset; 6312 if (BinOpKind == BO_Add) 6313 ResOffset = Offset.sadd_ov(Addend, Ov); 6314 else { 6315 assert(AddendIsRight && BinOpKind == BO_Sub && 6316 "operator must be add or sub with addend on the right"); 6317 ResOffset = Offset.ssub_ov(Addend, Ov); 6318 } 6319 6320 // We add an offset to a pointer here so we should support an offset as big as 6321 // possible. 6322 if (Ov) { 6323 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6324 "index (intermediate) result too big"); 6325 Offset = Offset.sext(2 * BitWidth); 6326 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6327 return; 6328 } 6329 6330 Offset = ResOffset; 6331 } 6332 6333 namespace { 6334 6335 // This is a wrapper class around StringLiteral to support offsetted string 6336 // literals as format strings. It takes the offset into account when returning 6337 // the string and its length or the source locations to display notes correctly. 6338 class FormatStringLiteral { 6339 const StringLiteral *FExpr; 6340 int64_t Offset; 6341 6342 public: 6343 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6344 : FExpr(fexpr), Offset(Offset) {} 6345 6346 StringRef getString() const { 6347 return FExpr->getString().drop_front(Offset); 6348 } 6349 6350 unsigned getByteLength() const { 6351 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6352 } 6353 6354 unsigned getLength() const { return FExpr->getLength() - Offset; } 6355 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6356 6357 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6358 6359 QualType getType() const { return FExpr->getType(); } 6360 6361 bool isAscii() const { return FExpr->isAscii(); } 6362 bool isWide() const { return FExpr->isWide(); } 6363 bool isUTF8() const { return FExpr->isUTF8(); } 6364 bool isUTF16() const { return FExpr->isUTF16(); } 6365 bool isUTF32() const { return FExpr->isUTF32(); } 6366 bool isPascal() const { return FExpr->isPascal(); } 6367 6368 SourceLocation getLocationOfByte( 6369 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6370 const TargetInfo &Target, unsigned *StartToken = nullptr, 6371 unsigned *StartTokenByteOffset = nullptr) const { 6372 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6373 StartToken, StartTokenByteOffset); 6374 } 6375 6376 SourceLocation getBeginLoc() const LLVM_READONLY { 6377 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6378 } 6379 6380 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6381 }; 6382 6383 } // namespace 6384 6385 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6386 const Expr *OrigFormatExpr, 6387 ArrayRef<const Expr *> Args, 6388 bool HasVAListArg, unsigned format_idx, 6389 unsigned firstDataArg, 6390 Sema::FormatStringType Type, 6391 bool inFunctionCall, 6392 Sema::VariadicCallType CallType, 6393 llvm::SmallBitVector &CheckedVarArgs, 6394 UncoveredArgHandler &UncoveredArg); 6395 6396 // Determine if an expression is a string literal or constant string. 6397 // If this function returns false on the arguments to a function expecting a 6398 // format string, we will usually need to emit a warning. 6399 // True string literals are then checked by CheckFormatString. 6400 static StringLiteralCheckType 6401 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6402 bool HasVAListArg, unsigned format_idx, 6403 unsigned firstDataArg, Sema::FormatStringType Type, 6404 Sema::VariadicCallType CallType, bool InFunctionCall, 6405 llvm::SmallBitVector &CheckedVarArgs, 6406 UncoveredArgHandler &UncoveredArg, 6407 llvm::APSInt Offset) { 6408 tryAgain: 6409 assert(Offset.isSigned() && "invalid offset"); 6410 6411 if (E->isTypeDependent() || E->isValueDependent()) 6412 return SLCT_NotALiteral; 6413 6414 E = E->IgnoreParenCasts(); 6415 6416 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6417 // Technically -Wformat-nonliteral does not warn about this case. 6418 // The behavior of printf and friends in this case is implementation 6419 // dependent. Ideally if the format string cannot be null then 6420 // it should have a 'nonnull' attribute in the function prototype. 6421 return SLCT_UncheckedLiteral; 6422 6423 switch (E->getStmtClass()) { 6424 case Stmt::BinaryConditionalOperatorClass: 6425 case Stmt::ConditionalOperatorClass: { 6426 // The expression is a literal if both sub-expressions were, and it was 6427 // completely checked only if both sub-expressions were checked. 6428 const AbstractConditionalOperator *C = 6429 cast<AbstractConditionalOperator>(E); 6430 6431 // Determine whether it is necessary to check both sub-expressions, for 6432 // example, because the condition expression is a constant that can be 6433 // evaluated at compile time. 6434 bool CheckLeft = true, CheckRight = true; 6435 6436 bool Cond; 6437 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) { 6438 if (Cond) 6439 CheckRight = false; 6440 else 6441 CheckLeft = false; 6442 } 6443 6444 // We need to maintain the offsets for the right and the left hand side 6445 // separately to check if every possible indexed expression is a valid 6446 // string literal. They might have different offsets for different string 6447 // literals in the end. 6448 StringLiteralCheckType Left; 6449 if (!CheckLeft) 6450 Left = SLCT_UncheckedLiteral; 6451 else { 6452 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6453 HasVAListArg, format_idx, firstDataArg, 6454 Type, CallType, InFunctionCall, 6455 CheckedVarArgs, UncoveredArg, Offset); 6456 if (Left == SLCT_NotALiteral || !CheckRight) { 6457 return Left; 6458 } 6459 } 6460 6461 StringLiteralCheckType Right = 6462 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6463 HasVAListArg, format_idx, firstDataArg, 6464 Type, CallType, InFunctionCall, CheckedVarArgs, 6465 UncoveredArg, Offset); 6466 6467 return (CheckLeft && Left < Right) ? Left : Right; 6468 } 6469 6470 case Stmt::ImplicitCastExprClass: 6471 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6472 goto tryAgain; 6473 6474 case Stmt::OpaqueValueExprClass: 6475 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6476 E = src; 6477 goto tryAgain; 6478 } 6479 return SLCT_NotALiteral; 6480 6481 case Stmt::PredefinedExprClass: 6482 // While __func__, etc., are technically not string literals, they 6483 // cannot contain format specifiers and thus are not a security 6484 // liability. 6485 return SLCT_UncheckedLiteral; 6486 6487 case Stmt::DeclRefExprClass: { 6488 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6489 6490 // As an exception, do not flag errors for variables binding to 6491 // const string literals. 6492 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6493 bool isConstant = false; 6494 QualType T = DR->getType(); 6495 6496 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6497 isConstant = AT->getElementType().isConstant(S.Context); 6498 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6499 isConstant = T.isConstant(S.Context) && 6500 PT->getPointeeType().isConstant(S.Context); 6501 } else if (T->isObjCObjectPointerType()) { 6502 // In ObjC, there is usually no "const ObjectPointer" type, 6503 // so don't check if the pointee type is constant. 6504 isConstant = T.isConstant(S.Context); 6505 } 6506 6507 if (isConstant) { 6508 if (const Expr *Init = VD->getAnyInitializer()) { 6509 // Look through initializers like const char c[] = { "foo" } 6510 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6511 if (InitList->isStringLiteralInit()) 6512 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6513 } 6514 return checkFormatStringExpr(S, Init, Args, 6515 HasVAListArg, format_idx, 6516 firstDataArg, Type, CallType, 6517 /*InFunctionCall*/ false, CheckedVarArgs, 6518 UncoveredArg, Offset); 6519 } 6520 } 6521 6522 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6523 // special check to see if the format string is a function parameter 6524 // of the function calling the printf function. If the function 6525 // has an attribute indicating it is a printf-like function, then we 6526 // should suppress warnings concerning non-literals being used in a call 6527 // to a vprintf function. For example: 6528 // 6529 // void 6530 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6531 // va_list ap; 6532 // va_start(ap, fmt); 6533 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6534 // ... 6535 // } 6536 if (HasVAListArg) { 6537 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6538 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6539 int PVIndex = PV->getFunctionScopeIndex() + 1; 6540 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6541 // adjust for implicit parameter 6542 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6543 if (MD->isInstance()) 6544 ++PVIndex; 6545 // We also check if the formats are compatible. 6546 // We can't pass a 'scanf' string to a 'printf' function. 6547 if (PVIndex == PVFormat->getFormatIdx() && 6548 Type == S.GetFormatStringType(PVFormat)) 6549 return SLCT_UncheckedLiteral; 6550 } 6551 } 6552 } 6553 } 6554 } 6555 6556 return SLCT_NotALiteral; 6557 } 6558 6559 case Stmt::CallExprClass: 6560 case Stmt::CXXMemberCallExprClass: { 6561 const CallExpr *CE = cast<CallExpr>(E); 6562 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6563 bool IsFirst = true; 6564 StringLiteralCheckType CommonResult; 6565 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6566 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6567 StringLiteralCheckType Result = checkFormatStringExpr( 6568 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6569 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6570 if (IsFirst) { 6571 CommonResult = Result; 6572 IsFirst = false; 6573 } 6574 } 6575 if (!IsFirst) 6576 return CommonResult; 6577 6578 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6579 unsigned BuiltinID = FD->getBuiltinID(); 6580 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6581 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6582 const Expr *Arg = CE->getArg(0); 6583 return checkFormatStringExpr(S, Arg, Args, 6584 HasVAListArg, format_idx, 6585 firstDataArg, Type, CallType, 6586 InFunctionCall, CheckedVarArgs, 6587 UncoveredArg, Offset); 6588 } 6589 } 6590 } 6591 6592 return SLCT_NotALiteral; 6593 } 6594 case Stmt::ObjCMessageExprClass: { 6595 const auto *ME = cast<ObjCMessageExpr>(E); 6596 if (const auto *ND = ME->getMethodDecl()) { 6597 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6598 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6599 return checkFormatStringExpr( 6600 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6601 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6602 } 6603 } 6604 6605 return SLCT_NotALiteral; 6606 } 6607 case Stmt::ObjCStringLiteralClass: 6608 case Stmt::StringLiteralClass: { 6609 const StringLiteral *StrE = nullptr; 6610 6611 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6612 StrE = ObjCFExpr->getString(); 6613 else 6614 StrE = cast<StringLiteral>(E); 6615 6616 if (StrE) { 6617 if (Offset.isNegative() || Offset > StrE->getLength()) { 6618 // TODO: It would be better to have an explicit warning for out of 6619 // bounds literals. 6620 return SLCT_NotALiteral; 6621 } 6622 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6623 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6624 firstDataArg, Type, InFunctionCall, CallType, 6625 CheckedVarArgs, UncoveredArg); 6626 return SLCT_CheckedLiteral; 6627 } 6628 6629 return SLCT_NotALiteral; 6630 } 6631 case Stmt::BinaryOperatorClass: { 6632 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6633 6634 // A string literal + an int offset is still a string literal. 6635 if (BinOp->isAdditiveOp()) { 6636 Expr::EvalResult LResult, RResult; 6637 6638 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context); 6639 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context); 6640 6641 if (LIsInt != RIsInt) { 6642 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6643 6644 if (LIsInt) { 6645 if (BinOpKind == BO_Add) { 6646 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6647 E = BinOp->getRHS(); 6648 goto tryAgain; 6649 } 6650 } else { 6651 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6652 E = BinOp->getLHS(); 6653 goto tryAgain; 6654 } 6655 } 6656 } 6657 6658 return SLCT_NotALiteral; 6659 } 6660 case Stmt::UnaryOperatorClass: { 6661 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6662 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6663 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6664 Expr::EvalResult IndexResult; 6665 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) { 6666 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6667 /*RHS is int*/ true); 6668 E = ASE->getBase(); 6669 goto tryAgain; 6670 } 6671 } 6672 6673 return SLCT_NotALiteral; 6674 } 6675 6676 default: 6677 return SLCT_NotALiteral; 6678 } 6679 } 6680 6681 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6682 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6683 .Case("scanf", FST_Scanf) 6684 .Cases("printf", "printf0", FST_Printf) 6685 .Cases("NSString", "CFString", FST_NSString) 6686 .Case("strftime", FST_Strftime) 6687 .Case("strfmon", FST_Strfmon) 6688 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6689 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6690 .Case("os_trace", FST_OSLog) 6691 .Case("os_log", FST_OSLog) 6692 .Default(FST_Unknown); 6693 } 6694 6695 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6696 /// functions) for correct use of format strings. 6697 /// Returns true if a format string has been fully checked. 6698 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6699 ArrayRef<const Expr *> Args, 6700 bool IsCXXMember, 6701 VariadicCallType CallType, 6702 SourceLocation Loc, SourceRange Range, 6703 llvm::SmallBitVector &CheckedVarArgs) { 6704 FormatStringInfo FSI; 6705 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6706 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6707 FSI.FirstDataArg, GetFormatStringType(Format), 6708 CallType, Loc, Range, CheckedVarArgs); 6709 return false; 6710 } 6711 6712 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6713 bool HasVAListArg, unsigned format_idx, 6714 unsigned firstDataArg, FormatStringType Type, 6715 VariadicCallType CallType, 6716 SourceLocation Loc, SourceRange Range, 6717 llvm::SmallBitVector &CheckedVarArgs) { 6718 // CHECK: printf/scanf-like function is called with no format string. 6719 if (format_idx >= Args.size()) { 6720 Diag(Loc, diag::warn_missing_format_string) << Range; 6721 return false; 6722 } 6723 6724 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6725 6726 // CHECK: format string is not a string literal. 6727 // 6728 // Dynamically generated format strings are difficult to 6729 // automatically vet at compile time. Requiring that format strings 6730 // are string literals: (1) permits the checking of format strings by 6731 // the compiler and thereby (2) can practically remove the source of 6732 // many format string exploits. 6733 6734 // Format string can be either ObjC string (e.g. @"%d") or 6735 // C string (e.g. "%d") 6736 // ObjC string uses the same format specifiers as C string, so we can use 6737 // the same format string checking logic for both ObjC and C strings. 6738 UncoveredArgHandler UncoveredArg; 6739 StringLiteralCheckType CT = 6740 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6741 format_idx, firstDataArg, Type, CallType, 6742 /*IsFunctionCall*/ true, CheckedVarArgs, 6743 UncoveredArg, 6744 /*no string offset*/ llvm::APSInt(64, false) = 0); 6745 6746 // Generate a diagnostic where an uncovered argument is detected. 6747 if (UncoveredArg.hasUncoveredArg()) { 6748 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6749 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6750 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6751 } 6752 6753 if (CT != SLCT_NotALiteral) 6754 // Literal format string found, check done! 6755 return CT == SLCT_CheckedLiteral; 6756 6757 // Strftime is particular as it always uses a single 'time' argument, 6758 // so it is safe to pass a non-literal string. 6759 if (Type == FST_Strftime) 6760 return false; 6761 6762 // Do not emit diag when the string param is a macro expansion and the 6763 // format is either NSString or CFString. This is a hack to prevent 6764 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6765 // which are usually used in place of NS and CF string literals. 6766 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6767 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6768 return false; 6769 6770 // If there are no arguments specified, warn with -Wformat-security, otherwise 6771 // warn only with -Wformat-nonliteral. 6772 if (Args.size() == firstDataArg) { 6773 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6774 << OrigFormatExpr->getSourceRange(); 6775 switch (Type) { 6776 default: 6777 break; 6778 case FST_Kprintf: 6779 case FST_FreeBSDKPrintf: 6780 case FST_Printf: 6781 Diag(FormatLoc, diag::note_format_security_fixit) 6782 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6783 break; 6784 case FST_NSString: 6785 Diag(FormatLoc, diag::note_format_security_fixit) 6786 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6787 break; 6788 } 6789 } else { 6790 Diag(FormatLoc, diag::warn_format_nonliteral) 6791 << OrigFormatExpr->getSourceRange(); 6792 } 6793 return false; 6794 } 6795 6796 namespace { 6797 6798 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6799 protected: 6800 Sema &S; 6801 const FormatStringLiteral *FExpr; 6802 const Expr *OrigFormatExpr; 6803 const Sema::FormatStringType FSType; 6804 const unsigned FirstDataArg; 6805 const unsigned NumDataArgs; 6806 const char *Beg; // Start of format string. 6807 const bool HasVAListArg; 6808 ArrayRef<const Expr *> Args; 6809 unsigned FormatIdx; 6810 llvm::SmallBitVector CoveredArgs; 6811 bool usesPositionalArgs = false; 6812 bool atFirstArg = true; 6813 bool inFunctionCall; 6814 Sema::VariadicCallType CallType; 6815 llvm::SmallBitVector &CheckedVarArgs; 6816 UncoveredArgHandler &UncoveredArg; 6817 6818 public: 6819 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6820 const Expr *origFormatExpr, 6821 const Sema::FormatStringType type, unsigned firstDataArg, 6822 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6823 ArrayRef<const Expr *> Args, unsigned formatIdx, 6824 bool inFunctionCall, Sema::VariadicCallType callType, 6825 llvm::SmallBitVector &CheckedVarArgs, 6826 UncoveredArgHandler &UncoveredArg) 6827 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6828 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6829 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6830 inFunctionCall(inFunctionCall), CallType(callType), 6831 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6832 CoveredArgs.resize(numDataArgs); 6833 CoveredArgs.reset(); 6834 } 6835 6836 void DoneProcessing(); 6837 6838 void HandleIncompleteSpecifier(const char *startSpecifier, 6839 unsigned specifierLen) override; 6840 6841 void HandleInvalidLengthModifier( 6842 const analyze_format_string::FormatSpecifier &FS, 6843 const analyze_format_string::ConversionSpecifier &CS, 6844 const char *startSpecifier, unsigned specifierLen, 6845 unsigned DiagID); 6846 6847 void HandleNonStandardLengthModifier( 6848 const analyze_format_string::FormatSpecifier &FS, 6849 const char *startSpecifier, unsigned specifierLen); 6850 6851 void HandleNonStandardConversionSpecifier( 6852 const analyze_format_string::ConversionSpecifier &CS, 6853 const char *startSpecifier, unsigned specifierLen); 6854 6855 void HandlePosition(const char *startPos, unsigned posLen) override; 6856 6857 void HandleInvalidPosition(const char *startSpecifier, 6858 unsigned specifierLen, 6859 analyze_format_string::PositionContext p) override; 6860 6861 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6862 6863 void HandleNullChar(const char *nullCharacter) override; 6864 6865 template <typename Range> 6866 static void 6867 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6868 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6869 bool IsStringLocation, Range StringRange, 6870 ArrayRef<FixItHint> Fixit = None); 6871 6872 protected: 6873 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6874 const char *startSpec, 6875 unsigned specifierLen, 6876 const char *csStart, unsigned csLen); 6877 6878 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6879 const char *startSpec, 6880 unsigned specifierLen); 6881 6882 SourceRange getFormatStringRange(); 6883 CharSourceRange getSpecifierRange(const char *startSpecifier, 6884 unsigned specifierLen); 6885 SourceLocation getLocationOfByte(const char *x); 6886 6887 const Expr *getDataArg(unsigned i) const; 6888 6889 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6890 const analyze_format_string::ConversionSpecifier &CS, 6891 const char *startSpecifier, unsigned specifierLen, 6892 unsigned argIndex); 6893 6894 template <typename Range> 6895 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6896 bool IsStringLocation, Range StringRange, 6897 ArrayRef<FixItHint> Fixit = None); 6898 }; 6899 6900 } // namespace 6901 6902 SourceRange CheckFormatHandler::getFormatStringRange() { 6903 return OrigFormatExpr->getSourceRange(); 6904 } 6905 6906 CharSourceRange CheckFormatHandler:: 6907 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6908 SourceLocation Start = getLocationOfByte(startSpecifier); 6909 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6910 6911 // Advance the end SourceLocation by one due to half-open ranges. 6912 End = End.getLocWithOffset(1); 6913 6914 return CharSourceRange::getCharRange(Start, End); 6915 } 6916 6917 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6918 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6919 S.getLangOpts(), S.Context.getTargetInfo()); 6920 } 6921 6922 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6923 unsigned specifierLen){ 6924 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6925 getLocationOfByte(startSpecifier), 6926 /*IsStringLocation*/true, 6927 getSpecifierRange(startSpecifier, specifierLen)); 6928 } 6929 6930 void CheckFormatHandler::HandleInvalidLengthModifier( 6931 const analyze_format_string::FormatSpecifier &FS, 6932 const analyze_format_string::ConversionSpecifier &CS, 6933 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6934 using namespace analyze_format_string; 6935 6936 const LengthModifier &LM = FS.getLengthModifier(); 6937 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6938 6939 // See if we know how to fix this length modifier. 6940 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6941 if (FixedLM) { 6942 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6943 getLocationOfByte(LM.getStart()), 6944 /*IsStringLocation*/true, 6945 getSpecifierRange(startSpecifier, specifierLen)); 6946 6947 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6948 << FixedLM->toString() 6949 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6950 6951 } else { 6952 FixItHint Hint; 6953 if (DiagID == diag::warn_format_nonsensical_length) 6954 Hint = FixItHint::CreateRemoval(LMRange); 6955 6956 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6957 getLocationOfByte(LM.getStart()), 6958 /*IsStringLocation*/true, 6959 getSpecifierRange(startSpecifier, specifierLen), 6960 Hint); 6961 } 6962 } 6963 6964 void CheckFormatHandler::HandleNonStandardLengthModifier( 6965 const analyze_format_string::FormatSpecifier &FS, 6966 const char *startSpecifier, unsigned specifierLen) { 6967 using namespace analyze_format_string; 6968 6969 const LengthModifier &LM = FS.getLengthModifier(); 6970 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6971 6972 // See if we know how to fix this length modifier. 6973 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6974 if (FixedLM) { 6975 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6976 << LM.toString() << 0, 6977 getLocationOfByte(LM.getStart()), 6978 /*IsStringLocation*/true, 6979 getSpecifierRange(startSpecifier, specifierLen)); 6980 6981 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6982 << FixedLM->toString() 6983 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6984 6985 } else { 6986 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6987 << LM.toString() << 0, 6988 getLocationOfByte(LM.getStart()), 6989 /*IsStringLocation*/true, 6990 getSpecifierRange(startSpecifier, specifierLen)); 6991 } 6992 } 6993 6994 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6995 const analyze_format_string::ConversionSpecifier &CS, 6996 const char *startSpecifier, unsigned specifierLen) { 6997 using namespace analyze_format_string; 6998 6999 // See if we know how to fix this conversion specifier. 7000 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7001 if (FixedCS) { 7002 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7003 << CS.toString() << /*conversion specifier*/1, 7004 getLocationOfByte(CS.getStart()), 7005 /*IsStringLocation*/true, 7006 getSpecifierRange(startSpecifier, specifierLen)); 7007 7008 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7009 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7010 << FixedCS->toString() 7011 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7012 } else { 7013 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7014 << CS.toString() << /*conversion specifier*/1, 7015 getLocationOfByte(CS.getStart()), 7016 /*IsStringLocation*/true, 7017 getSpecifierRange(startSpecifier, specifierLen)); 7018 } 7019 } 7020 7021 void CheckFormatHandler::HandlePosition(const char *startPos, 7022 unsigned posLen) { 7023 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7024 getLocationOfByte(startPos), 7025 /*IsStringLocation*/true, 7026 getSpecifierRange(startPos, posLen)); 7027 } 7028 7029 void 7030 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7031 analyze_format_string::PositionContext p) { 7032 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7033 << (unsigned) p, 7034 getLocationOfByte(startPos), /*IsStringLocation*/true, 7035 getSpecifierRange(startPos, posLen)); 7036 } 7037 7038 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7039 unsigned posLen) { 7040 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7041 getLocationOfByte(startPos), 7042 /*IsStringLocation*/true, 7043 getSpecifierRange(startPos, posLen)); 7044 } 7045 7046 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7047 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7048 // The presence of a null character is likely an error. 7049 EmitFormatDiagnostic( 7050 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7051 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7052 getFormatStringRange()); 7053 } 7054 } 7055 7056 // Note that this may return NULL if there was an error parsing or building 7057 // one of the argument expressions. 7058 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7059 return Args[FirstDataArg + i]; 7060 } 7061 7062 void CheckFormatHandler::DoneProcessing() { 7063 // Does the number of data arguments exceed the number of 7064 // format conversions in the format string? 7065 if (!HasVAListArg) { 7066 // Find any arguments that weren't covered. 7067 CoveredArgs.flip(); 7068 signed notCoveredArg = CoveredArgs.find_first(); 7069 if (notCoveredArg >= 0) { 7070 assert((unsigned)notCoveredArg < NumDataArgs); 7071 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7072 } else { 7073 UncoveredArg.setAllCovered(); 7074 } 7075 } 7076 } 7077 7078 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7079 const Expr *ArgExpr) { 7080 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7081 "Invalid state"); 7082 7083 if (!ArgExpr) 7084 return; 7085 7086 SourceLocation Loc = ArgExpr->getBeginLoc(); 7087 7088 if (S.getSourceManager().isInSystemMacro(Loc)) 7089 return; 7090 7091 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7092 for (auto E : DiagnosticExprs) 7093 PDiag << E->getSourceRange(); 7094 7095 CheckFormatHandler::EmitFormatDiagnostic( 7096 S, IsFunctionCall, DiagnosticExprs[0], 7097 PDiag, Loc, /*IsStringLocation*/false, 7098 DiagnosticExprs[0]->getSourceRange()); 7099 } 7100 7101 bool 7102 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7103 SourceLocation Loc, 7104 const char *startSpec, 7105 unsigned specifierLen, 7106 const char *csStart, 7107 unsigned csLen) { 7108 bool keepGoing = true; 7109 if (argIndex < NumDataArgs) { 7110 // Consider the argument coverered, even though the specifier doesn't 7111 // make sense. 7112 CoveredArgs.set(argIndex); 7113 } 7114 else { 7115 // If argIndex exceeds the number of data arguments we 7116 // don't issue a warning because that is just a cascade of warnings (and 7117 // they may have intended '%%' anyway). We don't want to continue processing 7118 // the format string after this point, however, as we will like just get 7119 // gibberish when trying to match arguments. 7120 keepGoing = false; 7121 } 7122 7123 StringRef Specifier(csStart, csLen); 7124 7125 // If the specifier in non-printable, it could be the first byte of a UTF-8 7126 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7127 // hex value. 7128 std::string CodePointStr; 7129 if (!llvm::sys::locale::isPrint(*csStart)) { 7130 llvm::UTF32 CodePoint; 7131 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7132 const llvm::UTF8 *E = 7133 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7134 llvm::ConversionResult Result = 7135 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7136 7137 if (Result != llvm::conversionOK) { 7138 unsigned char FirstChar = *csStart; 7139 CodePoint = (llvm::UTF32)FirstChar; 7140 } 7141 7142 llvm::raw_string_ostream OS(CodePointStr); 7143 if (CodePoint < 256) 7144 OS << "\\x" << llvm::format("%02x", CodePoint); 7145 else if (CodePoint <= 0xFFFF) 7146 OS << "\\u" << llvm::format("%04x", CodePoint); 7147 else 7148 OS << "\\U" << llvm::format("%08x", CodePoint); 7149 OS.flush(); 7150 Specifier = CodePointStr; 7151 } 7152 7153 EmitFormatDiagnostic( 7154 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7155 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7156 7157 return keepGoing; 7158 } 7159 7160 void 7161 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7162 const char *startSpec, 7163 unsigned specifierLen) { 7164 EmitFormatDiagnostic( 7165 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7166 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7167 } 7168 7169 bool 7170 CheckFormatHandler::CheckNumArgs( 7171 const analyze_format_string::FormatSpecifier &FS, 7172 const analyze_format_string::ConversionSpecifier &CS, 7173 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7174 7175 if (argIndex >= NumDataArgs) { 7176 PartialDiagnostic PDiag = FS.usesPositionalArg() 7177 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7178 << (argIndex+1) << NumDataArgs) 7179 : S.PDiag(diag::warn_printf_insufficient_data_args); 7180 EmitFormatDiagnostic( 7181 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7182 getSpecifierRange(startSpecifier, specifierLen)); 7183 7184 // Since more arguments than conversion tokens are given, by extension 7185 // all arguments are covered, so mark this as so. 7186 UncoveredArg.setAllCovered(); 7187 return false; 7188 } 7189 return true; 7190 } 7191 7192 template<typename Range> 7193 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7194 SourceLocation Loc, 7195 bool IsStringLocation, 7196 Range StringRange, 7197 ArrayRef<FixItHint> FixIt) { 7198 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7199 Loc, IsStringLocation, StringRange, FixIt); 7200 } 7201 7202 /// If the format string is not within the function call, emit a note 7203 /// so that the function call and string are in diagnostic messages. 7204 /// 7205 /// \param InFunctionCall if true, the format string is within the function 7206 /// call and only one diagnostic message will be produced. Otherwise, an 7207 /// extra note will be emitted pointing to location of the format string. 7208 /// 7209 /// \param ArgumentExpr the expression that is passed as the format string 7210 /// argument in the function call. Used for getting locations when two 7211 /// diagnostics are emitted. 7212 /// 7213 /// \param PDiag the callee should already have provided any strings for the 7214 /// diagnostic message. This function only adds locations and fixits 7215 /// to diagnostics. 7216 /// 7217 /// \param Loc primary location for diagnostic. If two diagnostics are 7218 /// required, one will be at Loc and a new SourceLocation will be created for 7219 /// the other one. 7220 /// 7221 /// \param IsStringLocation if true, Loc points to the format string should be 7222 /// used for the note. Otherwise, Loc points to the argument list and will 7223 /// be used with PDiag. 7224 /// 7225 /// \param StringRange some or all of the string to highlight. This is 7226 /// templated so it can accept either a CharSourceRange or a SourceRange. 7227 /// 7228 /// \param FixIt optional fix it hint for the format string. 7229 template <typename Range> 7230 void CheckFormatHandler::EmitFormatDiagnostic( 7231 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7232 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7233 Range StringRange, ArrayRef<FixItHint> FixIt) { 7234 if (InFunctionCall) { 7235 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7236 D << StringRange; 7237 D << FixIt; 7238 } else { 7239 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7240 << ArgumentExpr->getSourceRange(); 7241 7242 const Sema::SemaDiagnosticBuilder &Note = 7243 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7244 diag::note_format_string_defined); 7245 7246 Note << StringRange; 7247 Note << FixIt; 7248 } 7249 } 7250 7251 //===--- CHECK: Printf format string checking ------------------------------===// 7252 7253 namespace { 7254 7255 class CheckPrintfHandler : public CheckFormatHandler { 7256 public: 7257 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7258 const Expr *origFormatExpr, 7259 const Sema::FormatStringType type, unsigned firstDataArg, 7260 unsigned numDataArgs, bool isObjC, const char *beg, 7261 bool hasVAListArg, ArrayRef<const Expr *> Args, 7262 unsigned formatIdx, bool inFunctionCall, 7263 Sema::VariadicCallType CallType, 7264 llvm::SmallBitVector &CheckedVarArgs, 7265 UncoveredArgHandler &UncoveredArg) 7266 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7267 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7268 inFunctionCall, CallType, CheckedVarArgs, 7269 UncoveredArg) {} 7270 7271 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7272 7273 /// Returns true if '%@' specifiers are allowed in the format string. 7274 bool allowsObjCArg() const { 7275 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7276 FSType == Sema::FST_OSTrace; 7277 } 7278 7279 bool HandleInvalidPrintfConversionSpecifier( 7280 const analyze_printf::PrintfSpecifier &FS, 7281 const char *startSpecifier, 7282 unsigned specifierLen) override; 7283 7284 void handleInvalidMaskType(StringRef MaskType) override; 7285 7286 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7287 const char *startSpecifier, 7288 unsigned specifierLen) override; 7289 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7290 const char *StartSpecifier, 7291 unsigned SpecifierLen, 7292 const Expr *E); 7293 7294 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7295 const char *startSpecifier, unsigned specifierLen); 7296 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7297 const analyze_printf::OptionalAmount &Amt, 7298 unsigned type, 7299 const char *startSpecifier, unsigned specifierLen); 7300 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7301 const analyze_printf::OptionalFlag &flag, 7302 const char *startSpecifier, unsigned specifierLen); 7303 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7304 const analyze_printf::OptionalFlag &ignoredFlag, 7305 const analyze_printf::OptionalFlag &flag, 7306 const char *startSpecifier, unsigned specifierLen); 7307 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7308 const Expr *E); 7309 7310 void HandleEmptyObjCModifierFlag(const char *startFlag, 7311 unsigned flagLen) override; 7312 7313 void HandleInvalidObjCModifierFlag(const char *startFlag, 7314 unsigned flagLen) override; 7315 7316 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7317 const char *flagsEnd, 7318 const char *conversionPosition) 7319 override; 7320 }; 7321 7322 } // namespace 7323 7324 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7325 const analyze_printf::PrintfSpecifier &FS, 7326 const char *startSpecifier, 7327 unsigned specifierLen) { 7328 const analyze_printf::PrintfConversionSpecifier &CS = 7329 FS.getConversionSpecifier(); 7330 7331 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7332 getLocationOfByte(CS.getStart()), 7333 startSpecifier, specifierLen, 7334 CS.getStart(), CS.getLength()); 7335 } 7336 7337 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7338 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7339 } 7340 7341 bool CheckPrintfHandler::HandleAmount( 7342 const analyze_format_string::OptionalAmount &Amt, 7343 unsigned k, const char *startSpecifier, 7344 unsigned specifierLen) { 7345 if (Amt.hasDataArgument()) { 7346 if (!HasVAListArg) { 7347 unsigned argIndex = Amt.getArgIndex(); 7348 if (argIndex >= NumDataArgs) { 7349 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7350 << k, 7351 getLocationOfByte(Amt.getStart()), 7352 /*IsStringLocation*/true, 7353 getSpecifierRange(startSpecifier, specifierLen)); 7354 // Don't do any more checking. We will just emit 7355 // spurious errors. 7356 return false; 7357 } 7358 7359 // Type check the data argument. It should be an 'int'. 7360 // Although not in conformance with C99, we also allow the argument to be 7361 // an 'unsigned int' as that is a reasonably safe case. GCC also 7362 // doesn't emit a warning for that case. 7363 CoveredArgs.set(argIndex); 7364 const Expr *Arg = getDataArg(argIndex); 7365 if (!Arg) 7366 return false; 7367 7368 QualType T = Arg->getType(); 7369 7370 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7371 assert(AT.isValid()); 7372 7373 if (!AT.matchesType(S.Context, T)) { 7374 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7375 << k << AT.getRepresentativeTypeName(S.Context) 7376 << T << Arg->getSourceRange(), 7377 getLocationOfByte(Amt.getStart()), 7378 /*IsStringLocation*/true, 7379 getSpecifierRange(startSpecifier, specifierLen)); 7380 // Don't do any more checking. We will just emit 7381 // spurious errors. 7382 return false; 7383 } 7384 } 7385 } 7386 return true; 7387 } 7388 7389 void CheckPrintfHandler::HandleInvalidAmount( 7390 const analyze_printf::PrintfSpecifier &FS, 7391 const analyze_printf::OptionalAmount &Amt, 7392 unsigned type, 7393 const char *startSpecifier, 7394 unsigned specifierLen) { 7395 const analyze_printf::PrintfConversionSpecifier &CS = 7396 FS.getConversionSpecifier(); 7397 7398 FixItHint fixit = 7399 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7400 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7401 Amt.getConstantLength())) 7402 : FixItHint(); 7403 7404 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7405 << type << CS.toString(), 7406 getLocationOfByte(Amt.getStart()), 7407 /*IsStringLocation*/true, 7408 getSpecifierRange(startSpecifier, specifierLen), 7409 fixit); 7410 } 7411 7412 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7413 const analyze_printf::OptionalFlag &flag, 7414 const char *startSpecifier, 7415 unsigned specifierLen) { 7416 // Warn about pointless flag with a fixit removal. 7417 const analyze_printf::PrintfConversionSpecifier &CS = 7418 FS.getConversionSpecifier(); 7419 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7420 << flag.toString() << CS.toString(), 7421 getLocationOfByte(flag.getPosition()), 7422 /*IsStringLocation*/true, 7423 getSpecifierRange(startSpecifier, specifierLen), 7424 FixItHint::CreateRemoval( 7425 getSpecifierRange(flag.getPosition(), 1))); 7426 } 7427 7428 void CheckPrintfHandler::HandleIgnoredFlag( 7429 const analyze_printf::PrintfSpecifier &FS, 7430 const analyze_printf::OptionalFlag &ignoredFlag, 7431 const analyze_printf::OptionalFlag &flag, 7432 const char *startSpecifier, 7433 unsigned specifierLen) { 7434 // Warn about ignored flag with a fixit removal. 7435 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7436 << ignoredFlag.toString() << flag.toString(), 7437 getLocationOfByte(ignoredFlag.getPosition()), 7438 /*IsStringLocation*/true, 7439 getSpecifierRange(startSpecifier, specifierLen), 7440 FixItHint::CreateRemoval( 7441 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7442 } 7443 7444 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7445 unsigned flagLen) { 7446 // Warn about an empty flag. 7447 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7448 getLocationOfByte(startFlag), 7449 /*IsStringLocation*/true, 7450 getSpecifierRange(startFlag, flagLen)); 7451 } 7452 7453 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7454 unsigned flagLen) { 7455 // Warn about an invalid flag. 7456 auto Range = getSpecifierRange(startFlag, flagLen); 7457 StringRef flag(startFlag, flagLen); 7458 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7459 getLocationOfByte(startFlag), 7460 /*IsStringLocation*/true, 7461 Range, FixItHint::CreateRemoval(Range)); 7462 } 7463 7464 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7465 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7466 // Warn about using '[...]' without a '@' conversion. 7467 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7468 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7469 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7470 getLocationOfByte(conversionPosition), 7471 /*IsStringLocation*/true, 7472 Range, FixItHint::CreateRemoval(Range)); 7473 } 7474 7475 // Determines if the specified is a C++ class or struct containing 7476 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7477 // "c_str()"). 7478 template<typename MemberKind> 7479 static llvm::SmallPtrSet<MemberKind*, 1> 7480 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7481 const RecordType *RT = Ty->getAs<RecordType>(); 7482 llvm::SmallPtrSet<MemberKind*, 1> Results; 7483 7484 if (!RT) 7485 return Results; 7486 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7487 if (!RD || !RD->getDefinition()) 7488 return Results; 7489 7490 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7491 Sema::LookupMemberName); 7492 R.suppressDiagnostics(); 7493 7494 // We just need to include all members of the right kind turned up by the 7495 // filter, at this point. 7496 if (S.LookupQualifiedName(R, RT->getDecl())) 7497 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7498 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7499 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7500 Results.insert(FK); 7501 } 7502 return Results; 7503 } 7504 7505 /// Check if we could call '.c_str()' on an object. 7506 /// 7507 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7508 /// allow the call, or if it would be ambiguous). 7509 bool Sema::hasCStrMethod(const Expr *E) { 7510 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7511 7512 MethodSet Results = 7513 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7514 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7515 MI != ME; ++MI) 7516 if ((*MI)->getMinRequiredArguments() == 0) 7517 return true; 7518 return false; 7519 } 7520 7521 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7522 // better diagnostic if so. AT is assumed to be valid. 7523 // Returns true when a c_str() conversion method is found. 7524 bool CheckPrintfHandler::checkForCStrMembers( 7525 const analyze_printf::ArgType &AT, const Expr *E) { 7526 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7527 7528 MethodSet Results = 7529 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7530 7531 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7532 MI != ME; ++MI) { 7533 const CXXMethodDecl *Method = *MI; 7534 if (Method->getMinRequiredArguments() == 0 && 7535 AT.matchesType(S.Context, Method->getReturnType())) { 7536 // FIXME: Suggest parens if the expression needs them. 7537 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7538 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7539 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7540 return true; 7541 } 7542 } 7543 7544 return false; 7545 } 7546 7547 bool 7548 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7549 &FS, 7550 const char *startSpecifier, 7551 unsigned specifierLen) { 7552 using namespace analyze_format_string; 7553 using namespace analyze_printf; 7554 7555 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7556 7557 if (FS.consumesDataArgument()) { 7558 if (atFirstArg) { 7559 atFirstArg = false; 7560 usesPositionalArgs = FS.usesPositionalArg(); 7561 } 7562 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7563 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7564 startSpecifier, specifierLen); 7565 return false; 7566 } 7567 } 7568 7569 // First check if the field width, precision, and conversion specifier 7570 // have matching data arguments. 7571 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7572 startSpecifier, specifierLen)) { 7573 return false; 7574 } 7575 7576 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7577 startSpecifier, specifierLen)) { 7578 return false; 7579 } 7580 7581 if (!CS.consumesDataArgument()) { 7582 // FIXME: Technically specifying a precision or field width here 7583 // makes no sense. Worth issuing a warning at some point. 7584 return true; 7585 } 7586 7587 // Consume the argument. 7588 unsigned argIndex = FS.getArgIndex(); 7589 if (argIndex < NumDataArgs) { 7590 // The check to see if the argIndex is valid will come later. 7591 // We set the bit here because we may exit early from this 7592 // function if we encounter some other error. 7593 CoveredArgs.set(argIndex); 7594 } 7595 7596 // FreeBSD kernel extensions. 7597 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7598 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7599 // We need at least two arguments. 7600 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7601 return false; 7602 7603 // Claim the second argument. 7604 CoveredArgs.set(argIndex + 1); 7605 7606 // Type check the first argument (int for %b, pointer for %D) 7607 const Expr *Ex = getDataArg(argIndex); 7608 const analyze_printf::ArgType &AT = 7609 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7610 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7611 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7612 EmitFormatDiagnostic( 7613 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7614 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7615 << false << Ex->getSourceRange(), 7616 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7617 getSpecifierRange(startSpecifier, specifierLen)); 7618 7619 // Type check the second argument (char * for both %b and %D) 7620 Ex = getDataArg(argIndex + 1); 7621 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7622 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7623 EmitFormatDiagnostic( 7624 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7625 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7626 << false << Ex->getSourceRange(), 7627 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7628 getSpecifierRange(startSpecifier, specifierLen)); 7629 7630 return true; 7631 } 7632 7633 // Check for using an Objective-C specific conversion specifier 7634 // in a non-ObjC literal. 7635 if (!allowsObjCArg() && CS.isObjCArg()) { 7636 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7637 specifierLen); 7638 } 7639 7640 // %P can only be used with os_log. 7641 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7642 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7643 specifierLen); 7644 } 7645 7646 // %n is not allowed with os_log. 7647 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7648 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7649 getLocationOfByte(CS.getStart()), 7650 /*IsStringLocation*/ false, 7651 getSpecifierRange(startSpecifier, specifierLen)); 7652 7653 return true; 7654 } 7655 7656 // Only scalars are allowed for os_trace. 7657 if (FSType == Sema::FST_OSTrace && 7658 (CS.getKind() == ConversionSpecifier::PArg || 7659 CS.getKind() == ConversionSpecifier::sArg || 7660 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7661 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7662 specifierLen); 7663 } 7664 7665 // Check for use of public/private annotation outside of os_log(). 7666 if (FSType != Sema::FST_OSLog) { 7667 if (FS.isPublic().isSet()) { 7668 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7669 << "public", 7670 getLocationOfByte(FS.isPublic().getPosition()), 7671 /*IsStringLocation*/ false, 7672 getSpecifierRange(startSpecifier, specifierLen)); 7673 } 7674 if (FS.isPrivate().isSet()) { 7675 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7676 << "private", 7677 getLocationOfByte(FS.isPrivate().getPosition()), 7678 /*IsStringLocation*/ false, 7679 getSpecifierRange(startSpecifier, specifierLen)); 7680 } 7681 } 7682 7683 // Check for invalid use of field width 7684 if (!FS.hasValidFieldWidth()) { 7685 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7686 startSpecifier, specifierLen); 7687 } 7688 7689 // Check for invalid use of precision 7690 if (!FS.hasValidPrecision()) { 7691 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7692 startSpecifier, specifierLen); 7693 } 7694 7695 // Precision is mandatory for %P specifier. 7696 if (CS.getKind() == ConversionSpecifier::PArg && 7697 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7698 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7699 getLocationOfByte(startSpecifier), 7700 /*IsStringLocation*/ false, 7701 getSpecifierRange(startSpecifier, specifierLen)); 7702 } 7703 7704 // Check each flag does not conflict with any other component. 7705 if (!FS.hasValidThousandsGroupingPrefix()) 7706 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7707 if (!FS.hasValidLeadingZeros()) 7708 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7709 if (!FS.hasValidPlusPrefix()) 7710 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7711 if (!FS.hasValidSpacePrefix()) 7712 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7713 if (!FS.hasValidAlternativeForm()) 7714 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7715 if (!FS.hasValidLeftJustified()) 7716 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7717 7718 // Check that flags are not ignored by another flag 7719 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7720 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7721 startSpecifier, specifierLen); 7722 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7723 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7724 startSpecifier, specifierLen); 7725 7726 // Check the length modifier is valid with the given conversion specifier. 7727 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7728 S.getLangOpts())) 7729 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7730 diag::warn_format_nonsensical_length); 7731 else if (!FS.hasStandardLengthModifier()) 7732 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7733 else if (!FS.hasStandardLengthConversionCombination()) 7734 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7735 diag::warn_format_non_standard_conversion_spec); 7736 7737 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7738 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7739 7740 // The remaining checks depend on the data arguments. 7741 if (HasVAListArg) 7742 return true; 7743 7744 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7745 return false; 7746 7747 const Expr *Arg = getDataArg(argIndex); 7748 if (!Arg) 7749 return true; 7750 7751 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7752 } 7753 7754 static bool requiresParensToAddCast(const Expr *E) { 7755 // FIXME: We should have a general way to reason about operator 7756 // precedence and whether parens are actually needed here. 7757 // Take care of a few common cases where they aren't. 7758 const Expr *Inside = E->IgnoreImpCasts(); 7759 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7760 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7761 7762 switch (Inside->getStmtClass()) { 7763 case Stmt::ArraySubscriptExprClass: 7764 case Stmt::CallExprClass: 7765 case Stmt::CharacterLiteralClass: 7766 case Stmt::CXXBoolLiteralExprClass: 7767 case Stmt::DeclRefExprClass: 7768 case Stmt::FloatingLiteralClass: 7769 case Stmt::IntegerLiteralClass: 7770 case Stmt::MemberExprClass: 7771 case Stmt::ObjCArrayLiteralClass: 7772 case Stmt::ObjCBoolLiteralExprClass: 7773 case Stmt::ObjCBoxedExprClass: 7774 case Stmt::ObjCDictionaryLiteralClass: 7775 case Stmt::ObjCEncodeExprClass: 7776 case Stmt::ObjCIvarRefExprClass: 7777 case Stmt::ObjCMessageExprClass: 7778 case Stmt::ObjCPropertyRefExprClass: 7779 case Stmt::ObjCStringLiteralClass: 7780 case Stmt::ObjCSubscriptRefExprClass: 7781 case Stmt::ParenExprClass: 7782 case Stmt::StringLiteralClass: 7783 case Stmt::UnaryOperatorClass: 7784 return false; 7785 default: 7786 return true; 7787 } 7788 } 7789 7790 static std::pair<QualType, StringRef> 7791 shouldNotPrintDirectly(const ASTContext &Context, 7792 QualType IntendedTy, 7793 const Expr *E) { 7794 // Use a 'while' to peel off layers of typedefs. 7795 QualType TyTy = IntendedTy; 7796 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7797 StringRef Name = UserTy->getDecl()->getName(); 7798 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7799 .Case("CFIndex", Context.getNSIntegerType()) 7800 .Case("NSInteger", Context.getNSIntegerType()) 7801 .Case("NSUInteger", Context.getNSUIntegerType()) 7802 .Case("SInt32", Context.IntTy) 7803 .Case("UInt32", Context.UnsignedIntTy) 7804 .Default(QualType()); 7805 7806 if (!CastTy.isNull()) 7807 return std::make_pair(CastTy, Name); 7808 7809 TyTy = UserTy->desugar(); 7810 } 7811 7812 // Strip parens if necessary. 7813 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7814 return shouldNotPrintDirectly(Context, 7815 PE->getSubExpr()->getType(), 7816 PE->getSubExpr()); 7817 7818 // If this is a conditional expression, then its result type is constructed 7819 // via usual arithmetic conversions and thus there might be no necessary 7820 // typedef sugar there. Recurse to operands to check for NSInteger & 7821 // Co. usage condition. 7822 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7823 QualType TrueTy, FalseTy; 7824 StringRef TrueName, FalseName; 7825 7826 std::tie(TrueTy, TrueName) = 7827 shouldNotPrintDirectly(Context, 7828 CO->getTrueExpr()->getType(), 7829 CO->getTrueExpr()); 7830 std::tie(FalseTy, FalseName) = 7831 shouldNotPrintDirectly(Context, 7832 CO->getFalseExpr()->getType(), 7833 CO->getFalseExpr()); 7834 7835 if (TrueTy == FalseTy) 7836 return std::make_pair(TrueTy, TrueName); 7837 else if (TrueTy.isNull()) 7838 return std::make_pair(FalseTy, FalseName); 7839 else if (FalseTy.isNull()) 7840 return std::make_pair(TrueTy, TrueName); 7841 } 7842 7843 return std::make_pair(QualType(), StringRef()); 7844 } 7845 7846 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 7847 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 7848 /// type do not count. 7849 static bool 7850 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 7851 QualType From = ICE->getSubExpr()->getType(); 7852 QualType To = ICE->getType(); 7853 // It's an integer promotion if the destination type is the promoted 7854 // source type. 7855 if (ICE->getCastKind() == CK_IntegralCast && 7856 From->isPromotableIntegerType() && 7857 S.Context.getPromotedIntegerType(From) == To) 7858 return true; 7859 // Look through vector types, since we do default argument promotion for 7860 // those in OpenCL. 7861 if (const auto *VecTy = From->getAs<ExtVectorType>()) 7862 From = VecTy->getElementType(); 7863 if (const auto *VecTy = To->getAs<ExtVectorType>()) 7864 To = VecTy->getElementType(); 7865 // It's a floating promotion if the source type is a lower rank. 7866 return ICE->getCastKind() == CK_FloatingCast && 7867 S.Context.getFloatingTypeOrder(From, To) < 0; 7868 } 7869 7870 bool 7871 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7872 const char *StartSpecifier, 7873 unsigned SpecifierLen, 7874 const Expr *E) { 7875 using namespace analyze_format_string; 7876 using namespace analyze_printf; 7877 7878 // Now type check the data expression that matches the 7879 // format specifier. 7880 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7881 if (!AT.isValid()) 7882 return true; 7883 7884 QualType ExprTy = E->getType(); 7885 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7886 ExprTy = TET->getUnderlyingExpr()->getType(); 7887 } 7888 7889 const analyze_printf::ArgType::MatchKind Match = 7890 AT.matchesType(S.Context, ExprTy); 7891 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 7892 if (Match == analyze_printf::ArgType::Match) 7893 return true; 7894 7895 // Look through argument promotions for our error message's reported type. 7896 // This includes the integral and floating promotions, but excludes array 7897 // and function pointer decay (seeing that an argument intended to be a 7898 // string has type 'char [6]' is probably more confusing than 'char *') and 7899 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 7900 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7901 if (isArithmeticArgumentPromotion(S, ICE)) { 7902 E = ICE->getSubExpr(); 7903 ExprTy = E->getType(); 7904 7905 // Check if we didn't match because of an implicit cast from a 'char' 7906 // or 'short' to an 'int'. This is done because printf is a varargs 7907 // function. 7908 if (ICE->getType() == S.Context.IntTy || 7909 ICE->getType() == S.Context.UnsignedIntTy) { 7910 // All further checking is done on the subexpression. 7911 if (AT.matchesType(S.Context, ExprTy)) 7912 return true; 7913 } 7914 } 7915 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7916 // Special case for 'a', which has type 'int' in C. 7917 // Note, however, that we do /not/ want to treat multibyte constants like 7918 // 'MooV' as characters! This form is deprecated but still exists. 7919 if (ExprTy == S.Context.IntTy) 7920 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7921 ExprTy = S.Context.CharTy; 7922 } 7923 7924 // Look through enums to their underlying type. 7925 bool IsEnum = false; 7926 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7927 ExprTy = EnumTy->getDecl()->getIntegerType(); 7928 IsEnum = true; 7929 } 7930 7931 // %C in an Objective-C context prints a unichar, not a wchar_t. 7932 // If the argument is an integer of some kind, believe the %C and suggest 7933 // a cast instead of changing the conversion specifier. 7934 QualType IntendedTy = ExprTy; 7935 if (isObjCContext() && 7936 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7937 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7938 !ExprTy->isCharType()) { 7939 // 'unichar' is defined as a typedef of unsigned short, but we should 7940 // prefer using the typedef if it is visible. 7941 IntendedTy = S.Context.UnsignedShortTy; 7942 7943 // While we are here, check if the value is an IntegerLiteral that happens 7944 // to be within the valid range. 7945 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7946 const llvm::APInt &V = IL->getValue(); 7947 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7948 return true; 7949 } 7950 7951 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7952 Sema::LookupOrdinaryName); 7953 if (S.LookupName(Result, S.getCurScope())) { 7954 NamedDecl *ND = Result.getFoundDecl(); 7955 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7956 if (TD->getUnderlyingType() == IntendedTy) 7957 IntendedTy = S.Context.getTypedefType(TD); 7958 } 7959 } 7960 } 7961 7962 // Special-case some of Darwin's platform-independence types by suggesting 7963 // casts to primitive types that are known to be large enough. 7964 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7965 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7966 QualType CastTy; 7967 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7968 if (!CastTy.isNull()) { 7969 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7970 // (long in ASTContext). Only complain to pedants. 7971 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7972 (AT.isSizeT() || AT.isPtrdiffT()) && 7973 AT.matchesType(S.Context, CastTy)) 7974 Pedantic = true; 7975 IntendedTy = CastTy; 7976 ShouldNotPrintDirectly = true; 7977 } 7978 } 7979 7980 // We may be able to offer a FixItHint if it is a supported type. 7981 PrintfSpecifier fixedFS = FS; 7982 bool Success = 7983 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7984 7985 if (Success) { 7986 // Get the fix string from the fixed format specifier 7987 SmallString<16> buf; 7988 llvm::raw_svector_ostream os(buf); 7989 fixedFS.toString(os); 7990 7991 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7992 7993 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7994 unsigned Diag = 7995 Pedantic 7996 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7997 : diag::warn_format_conversion_argument_type_mismatch; 7998 // In this case, the specifier is wrong and should be changed to match 7999 // the argument. 8000 EmitFormatDiagnostic(S.PDiag(Diag) 8001 << AT.getRepresentativeTypeName(S.Context) 8002 << IntendedTy << IsEnum << E->getSourceRange(), 8003 E->getBeginLoc(), 8004 /*IsStringLocation*/ false, SpecRange, 8005 FixItHint::CreateReplacement(SpecRange, os.str())); 8006 } else { 8007 // The canonical type for formatting this value is different from the 8008 // actual type of the expression. (This occurs, for example, with Darwin's 8009 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8010 // should be printed as 'long' for 64-bit compatibility.) 8011 // Rather than emitting a normal format/argument mismatch, we want to 8012 // add a cast to the recommended type (and correct the format string 8013 // if necessary). 8014 SmallString<16> CastBuf; 8015 llvm::raw_svector_ostream CastFix(CastBuf); 8016 CastFix << "("; 8017 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8018 CastFix << ")"; 8019 8020 SmallVector<FixItHint,4> Hints; 8021 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8022 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8023 8024 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8025 // If there's already a cast present, just replace it. 8026 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8027 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8028 8029 } else if (!requiresParensToAddCast(E)) { 8030 // If the expression has high enough precedence, 8031 // just write the C-style cast. 8032 Hints.push_back( 8033 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8034 } else { 8035 // Otherwise, add parens around the expression as well as the cast. 8036 CastFix << "("; 8037 Hints.push_back( 8038 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8039 8040 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8041 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8042 } 8043 8044 if (ShouldNotPrintDirectly) { 8045 // The expression has a type that should not be printed directly. 8046 // We extract the name from the typedef because we don't want to show 8047 // the underlying type in the diagnostic. 8048 StringRef Name; 8049 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8050 Name = TypedefTy->getDecl()->getName(); 8051 else 8052 Name = CastTyName; 8053 unsigned Diag = Pedantic 8054 ? diag::warn_format_argument_needs_cast_pedantic 8055 : diag::warn_format_argument_needs_cast; 8056 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8057 << E->getSourceRange(), 8058 E->getBeginLoc(), /*IsStringLocation=*/false, 8059 SpecRange, Hints); 8060 } else { 8061 // In this case, the expression could be printed using a different 8062 // specifier, but we've decided that the specifier is probably correct 8063 // and we should cast instead. Just use the normal warning message. 8064 EmitFormatDiagnostic( 8065 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8066 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8067 << E->getSourceRange(), 8068 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8069 } 8070 } 8071 } else { 8072 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8073 SpecifierLen); 8074 // Since the warning for passing non-POD types to variadic functions 8075 // was deferred until now, we emit a warning for non-POD 8076 // arguments here. 8077 switch (S.isValidVarArgType(ExprTy)) { 8078 case Sema::VAK_Valid: 8079 case Sema::VAK_ValidInCXX11: { 8080 unsigned Diag = 8081 Pedantic 8082 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8083 : diag::warn_format_conversion_argument_type_mismatch; 8084 8085 EmitFormatDiagnostic( 8086 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8087 << IsEnum << CSR << E->getSourceRange(), 8088 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8089 break; 8090 } 8091 case Sema::VAK_Undefined: 8092 case Sema::VAK_MSVCUndefined: 8093 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8094 << S.getLangOpts().CPlusPlus11 << ExprTy 8095 << CallType 8096 << AT.getRepresentativeTypeName(S.Context) << CSR 8097 << E->getSourceRange(), 8098 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8099 checkForCStrMembers(AT, E); 8100 break; 8101 8102 case Sema::VAK_Invalid: 8103 if (ExprTy->isObjCObjectType()) 8104 EmitFormatDiagnostic( 8105 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8106 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8107 << AT.getRepresentativeTypeName(S.Context) << CSR 8108 << E->getSourceRange(), 8109 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8110 else 8111 // FIXME: If this is an initializer list, suggest removing the braces 8112 // or inserting a cast to the target type. 8113 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8114 << isa<InitListExpr>(E) << ExprTy << CallType 8115 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8116 break; 8117 } 8118 8119 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8120 "format string specifier index out of range"); 8121 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8122 } 8123 8124 return true; 8125 } 8126 8127 //===--- CHECK: Scanf format string checking ------------------------------===// 8128 8129 namespace { 8130 8131 class CheckScanfHandler : public CheckFormatHandler { 8132 public: 8133 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8134 const Expr *origFormatExpr, Sema::FormatStringType type, 8135 unsigned firstDataArg, unsigned numDataArgs, 8136 const char *beg, bool hasVAListArg, 8137 ArrayRef<const Expr *> Args, unsigned formatIdx, 8138 bool inFunctionCall, Sema::VariadicCallType CallType, 8139 llvm::SmallBitVector &CheckedVarArgs, 8140 UncoveredArgHandler &UncoveredArg) 8141 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8142 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8143 inFunctionCall, CallType, CheckedVarArgs, 8144 UncoveredArg) {} 8145 8146 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8147 const char *startSpecifier, 8148 unsigned specifierLen) override; 8149 8150 bool HandleInvalidScanfConversionSpecifier( 8151 const analyze_scanf::ScanfSpecifier &FS, 8152 const char *startSpecifier, 8153 unsigned specifierLen) override; 8154 8155 void HandleIncompleteScanList(const char *start, const char *end) override; 8156 }; 8157 8158 } // namespace 8159 8160 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8161 const char *end) { 8162 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8163 getLocationOfByte(end), /*IsStringLocation*/true, 8164 getSpecifierRange(start, end - start)); 8165 } 8166 8167 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8168 const analyze_scanf::ScanfSpecifier &FS, 8169 const char *startSpecifier, 8170 unsigned specifierLen) { 8171 const analyze_scanf::ScanfConversionSpecifier &CS = 8172 FS.getConversionSpecifier(); 8173 8174 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8175 getLocationOfByte(CS.getStart()), 8176 startSpecifier, specifierLen, 8177 CS.getStart(), CS.getLength()); 8178 } 8179 8180 bool CheckScanfHandler::HandleScanfSpecifier( 8181 const analyze_scanf::ScanfSpecifier &FS, 8182 const char *startSpecifier, 8183 unsigned specifierLen) { 8184 using namespace analyze_scanf; 8185 using namespace analyze_format_string; 8186 8187 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8188 8189 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8190 // be used to decide if we are using positional arguments consistently. 8191 if (FS.consumesDataArgument()) { 8192 if (atFirstArg) { 8193 atFirstArg = false; 8194 usesPositionalArgs = FS.usesPositionalArg(); 8195 } 8196 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8197 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8198 startSpecifier, specifierLen); 8199 return false; 8200 } 8201 } 8202 8203 // Check if the field with is non-zero. 8204 const OptionalAmount &Amt = FS.getFieldWidth(); 8205 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8206 if (Amt.getConstantAmount() == 0) { 8207 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8208 Amt.getConstantLength()); 8209 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8210 getLocationOfByte(Amt.getStart()), 8211 /*IsStringLocation*/true, R, 8212 FixItHint::CreateRemoval(R)); 8213 } 8214 } 8215 8216 if (!FS.consumesDataArgument()) { 8217 // FIXME: Technically specifying a precision or field width here 8218 // makes no sense. Worth issuing a warning at some point. 8219 return true; 8220 } 8221 8222 // Consume the argument. 8223 unsigned argIndex = FS.getArgIndex(); 8224 if (argIndex < NumDataArgs) { 8225 // The check to see if the argIndex is valid will come later. 8226 // We set the bit here because we may exit early from this 8227 // function if we encounter some other error. 8228 CoveredArgs.set(argIndex); 8229 } 8230 8231 // Check the length modifier is valid with the given conversion specifier. 8232 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8233 S.getLangOpts())) 8234 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8235 diag::warn_format_nonsensical_length); 8236 else if (!FS.hasStandardLengthModifier()) 8237 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8238 else if (!FS.hasStandardLengthConversionCombination()) 8239 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8240 diag::warn_format_non_standard_conversion_spec); 8241 8242 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8243 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8244 8245 // The remaining checks depend on the data arguments. 8246 if (HasVAListArg) 8247 return true; 8248 8249 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8250 return false; 8251 8252 // Check that the argument type matches the format specifier. 8253 const Expr *Ex = getDataArg(argIndex); 8254 if (!Ex) 8255 return true; 8256 8257 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8258 8259 if (!AT.isValid()) { 8260 return true; 8261 } 8262 8263 analyze_format_string::ArgType::MatchKind Match = 8264 AT.matchesType(S.Context, Ex->getType()); 8265 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8266 if (Match == analyze_format_string::ArgType::Match) 8267 return true; 8268 8269 ScanfSpecifier fixedFS = FS; 8270 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8271 S.getLangOpts(), S.Context); 8272 8273 unsigned Diag = 8274 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8275 : diag::warn_format_conversion_argument_type_mismatch; 8276 8277 if (Success) { 8278 // Get the fix string from the fixed format specifier. 8279 SmallString<128> buf; 8280 llvm::raw_svector_ostream os(buf); 8281 fixedFS.toString(os); 8282 8283 EmitFormatDiagnostic( 8284 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8285 << Ex->getType() << false << Ex->getSourceRange(), 8286 Ex->getBeginLoc(), 8287 /*IsStringLocation*/ false, 8288 getSpecifierRange(startSpecifier, specifierLen), 8289 FixItHint::CreateReplacement( 8290 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8291 } else { 8292 EmitFormatDiagnostic(S.PDiag(Diag) 8293 << AT.getRepresentativeTypeName(S.Context) 8294 << Ex->getType() << false << Ex->getSourceRange(), 8295 Ex->getBeginLoc(), 8296 /*IsStringLocation*/ false, 8297 getSpecifierRange(startSpecifier, specifierLen)); 8298 } 8299 8300 return true; 8301 } 8302 8303 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8304 const Expr *OrigFormatExpr, 8305 ArrayRef<const Expr *> Args, 8306 bool HasVAListArg, unsigned format_idx, 8307 unsigned firstDataArg, 8308 Sema::FormatStringType Type, 8309 bool inFunctionCall, 8310 Sema::VariadicCallType CallType, 8311 llvm::SmallBitVector &CheckedVarArgs, 8312 UncoveredArgHandler &UncoveredArg) { 8313 // CHECK: is the format string a wide literal? 8314 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8315 CheckFormatHandler::EmitFormatDiagnostic( 8316 S, inFunctionCall, Args[format_idx], 8317 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8318 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8319 return; 8320 } 8321 8322 // Str - The format string. NOTE: this is NOT null-terminated! 8323 StringRef StrRef = FExpr->getString(); 8324 const char *Str = StrRef.data(); 8325 // Account for cases where the string literal is truncated in a declaration. 8326 const ConstantArrayType *T = 8327 S.Context.getAsConstantArrayType(FExpr->getType()); 8328 assert(T && "String literal not of constant array type!"); 8329 size_t TypeSize = T->getSize().getZExtValue(); 8330 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8331 const unsigned numDataArgs = Args.size() - firstDataArg; 8332 8333 // Emit a warning if the string literal is truncated and does not contain an 8334 // embedded null character. 8335 if (TypeSize <= StrRef.size() && 8336 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8337 CheckFormatHandler::EmitFormatDiagnostic( 8338 S, inFunctionCall, Args[format_idx], 8339 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8340 FExpr->getBeginLoc(), 8341 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8342 return; 8343 } 8344 8345 // CHECK: empty format string? 8346 if (StrLen == 0 && numDataArgs > 0) { 8347 CheckFormatHandler::EmitFormatDiagnostic( 8348 S, inFunctionCall, Args[format_idx], 8349 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8350 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8351 return; 8352 } 8353 8354 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8355 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8356 Type == Sema::FST_OSTrace) { 8357 CheckPrintfHandler H( 8358 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8359 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8360 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8361 CheckedVarArgs, UncoveredArg); 8362 8363 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8364 S.getLangOpts(), 8365 S.Context.getTargetInfo(), 8366 Type == Sema::FST_FreeBSDKPrintf)) 8367 H.DoneProcessing(); 8368 } else if (Type == Sema::FST_Scanf) { 8369 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8370 numDataArgs, Str, HasVAListArg, Args, format_idx, 8371 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8372 8373 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8374 S.getLangOpts(), 8375 S.Context.getTargetInfo())) 8376 H.DoneProcessing(); 8377 } // TODO: handle other formats 8378 } 8379 8380 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8381 // Str - The format string. NOTE: this is NOT null-terminated! 8382 StringRef StrRef = FExpr->getString(); 8383 const char *Str = StrRef.data(); 8384 // Account for cases where the string literal is truncated in a declaration. 8385 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8386 assert(T && "String literal not of constant array type!"); 8387 size_t TypeSize = T->getSize().getZExtValue(); 8388 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8389 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8390 getLangOpts(), 8391 Context.getTargetInfo()); 8392 } 8393 8394 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8395 8396 // Returns the related absolute value function that is larger, of 0 if one 8397 // does not exist. 8398 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8399 switch (AbsFunction) { 8400 default: 8401 return 0; 8402 8403 case Builtin::BI__builtin_abs: 8404 return Builtin::BI__builtin_labs; 8405 case Builtin::BI__builtin_labs: 8406 return Builtin::BI__builtin_llabs; 8407 case Builtin::BI__builtin_llabs: 8408 return 0; 8409 8410 case Builtin::BI__builtin_fabsf: 8411 return Builtin::BI__builtin_fabs; 8412 case Builtin::BI__builtin_fabs: 8413 return Builtin::BI__builtin_fabsl; 8414 case Builtin::BI__builtin_fabsl: 8415 return 0; 8416 8417 case Builtin::BI__builtin_cabsf: 8418 return Builtin::BI__builtin_cabs; 8419 case Builtin::BI__builtin_cabs: 8420 return Builtin::BI__builtin_cabsl; 8421 case Builtin::BI__builtin_cabsl: 8422 return 0; 8423 8424 case Builtin::BIabs: 8425 return Builtin::BIlabs; 8426 case Builtin::BIlabs: 8427 return Builtin::BIllabs; 8428 case Builtin::BIllabs: 8429 return 0; 8430 8431 case Builtin::BIfabsf: 8432 return Builtin::BIfabs; 8433 case Builtin::BIfabs: 8434 return Builtin::BIfabsl; 8435 case Builtin::BIfabsl: 8436 return 0; 8437 8438 case Builtin::BIcabsf: 8439 return Builtin::BIcabs; 8440 case Builtin::BIcabs: 8441 return Builtin::BIcabsl; 8442 case Builtin::BIcabsl: 8443 return 0; 8444 } 8445 } 8446 8447 // Returns the argument type of the absolute value function. 8448 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8449 unsigned AbsType) { 8450 if (AbsType == 0) 8451 return QualType(); 8452 8453 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8454 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8455 if (Error != ASTContext::GE_None) 8456 return QualType(); 8457 8458 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8459 if (!FT) 8460 return QualType(); 8461 8462 if (FT->getNumParams() != 1) 8463 return QualType(); 8464 8465 return FT->getParamType(0); 8466 } 8467 8468 // Returns the best absolute value function, or zero, based on type and 8469 // current absolute value function. 8470 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8471 unsigned AbsFunctionKind) { 8472 unsigned BestKind = 0; 8473 uint64_t ArgSize = Context.getTypeSize(ArgType); 8474 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8475 Kind = getLargerAbsoluteValueFunction(Kind)) { 8476 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8477 if (Context.getTypeSize(ParamType) >= ArgSize) { 8478 if (BestKind == 0) 8479 BestKind = Kind; 8480 else if (Context.hasSameType(ParamType, ArgType)) { 8481 BestKind = Kind; 8482 break; 8483 } 8484 } 8485 } 8486 return BestKind; 8487 } 8488 8489 enum AbsoluteValueKind { 8490 AVK_Integer, 8491 AVK_Floating, 8492 AVK_Complex 8493 }; 8494 8495 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8496 if (T->isIntegralOrEnumerationType()) 8497 return AVK_Integer; 8498 if (T->isRealFloatingType()) 8499 return AVK_Floating; 8500 if (T->isAnyComplexType()) 8501 return AVK_Complex; 8502 8503 llvm_unreachable("Type not integer, floating, or complex"); 8504 } 8505 8506 // Changes the absolute value function to a different type. Preserves whether 8507 // the function is a builtin. 8508 static unsigned changeAbsFunction(unsigned AbsKind, 8509 AbsoluteValueKind ValueKind) { 8510 switch (ValueKind) { 8511 case AVK_Integer: 8512 switch (AbsKind) { 8513 default: 8514 return 0; 8515 case Builtin::BI__builtin_fabsf: 8516 case Builtin::BI__builtin_fabs: 8517 case Builtin::BI__builtin_fabsl: 8518 case Builtin::BI__builtin_cabsf: 8519 case Builtin::BI__builtin_cabs: 8520 case Builtin::BI__builtin_cabsl: 8521 return Builtin::BI__builtin_abs; 8522 case Builtin::BIfabsf: 8523 case Builtin::BIfabs: 8524 case Builtin::BIfabsl: 8525 case Builtin::BIcabsf: 8526 case Builtin::BIcabs: 8527 case Builtin::BIcabsl: 8528 return Builtin::BIabs; 8529 } 8530 case AVK_Floating: 8531 switch (AbsKind) { 8532 default: 8533 return 0; 8534 case Builtin::BI__builtin_abs: 8535 case Builtin::BI__builtin_labs: 8536 case Builtin::BI__builtin_llabs: 8537 case Builtin::BI__builtin_cabsf: 8538 case Builtin::BI__builtin_cabs: 8539 case Builtin::BI__builtin_cabsl: 8540 return Builtin::BI__builtin_fabsf; 8541 case Builtin::BIabs: 8542 case Builtin::BIlabs: 8543 case Builtin::BIllabs: 8544 case Builtin::BIcabsf: 8545 case Builtin::BIcabs: 8546 case Builtin::BIcabsl: 8547 return Builtin::BIfabsf; 8548 } 8549 case AVK_Complex: 8550 switch (AbsKind) { 8551 default: 8552 return 0; 8553 case Builtin::BI__builtin_abs: 8554 case Builtin::BI__builtin_labs: 8555 case Builtin::BI__builtin_llabs: 8556 case Builtin::BI__builtin_fabsf: 8557 case Builtin::BI__builtin_fabs: 8558 case Builtin::BI__builtin_fabsl: 8559 return Builtin::BI__builtin_cabsf; 8560 case Builtin::BIabs: 8561 case Builtin::BIlabs: 8562 case Builtin::BIllabs: 8563 case Builtin::BIfabsf: 8564 case Builtin::BIfabs: 8565 case Builtin::BIfabsl: 8566 return Builtin::BIcabsf; 8567 } 8568 } 8569 llvm_unreachable("Unable to convert function"); 8570 } 8571 8572 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8573 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8574 if (!FnInfo) 8575 return 0; 8576 8577 switch (FDecl->getBuiltinID()) { 8578 default: 8579 return 0; 8580 case Builtin::BI__builtin_abs: 8581 case Builtin::BI__builtin_fabs: 8582 case Builtin::BI__builtin_fabsf: 8583 case Builtin::BI__builtin_fabsl: 8584 case Builtin::BI__builtin_labs: 8585 case Builtin::BI__builtin_llabs: 8586 case Builtin::BI__builtin_cabs: 8587 case Builtin::BI__builtin_cabsf: 8588 case Builtin::BI__builtin_cabsl: 8589 case Builtin::BIabs: 8590 case Builtin::BIlabs: 8591 case Builtin::BIllabs: 8592 case Builtin::BIfabs: 8593 case Builtin::BIfabsf: 8594 case Builtin::BIfabsl: 8595 case Builtin::BIcabs: 8596 case Builtin::BIcabsf: 8597 case Builtin::BIcabsl: 8598 return FDecl->getBuiltinID(); 8599 } 8600 llvm_unreachable("Unknown Builtin type"); 8601 } 8602 8603 // If the replacement is valid, emit a note with replacement function. 8604 // Additionally, suggest including the proper header if not already included. 8605 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8606 unsigned AbsKind, QualType ArgType) { 8607 bool EmitHeaderHint = true; 8608 const char *HeaderName = nullptr; 8609 const char *FunctionName = nullptr; 8610 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8611 FunctionName = "std::abs"; 8612 if (ArgType->isIntegralOrEnumerationType()) { 8613 HeaderName = "cstdlib"; 8614 } else if (ArgType->isRealFloatingType()) { 8615 HeaderName = "cmath"; 8616 } else { 8617 llvm_unreachable("Invalid Type"); 8618 } 8619 8620 // Lookup all std::abs 8621 if (NamespaceDecl *Std = S.getStdNamespace()) { 8622 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8623 R.suppressDiagnostics(); 8624 S.LookupQualifiedName(R, Std); 8625 8626 for (const auto *I : R) { 8627 const FunctionDecl *FDecl = nullptr; 8628 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8629 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8630 } else { 8631 FDecl = dyn_cast<FunctionDecl>(I); 8632 } 8633 if (!FDecl) 8634 continue; 8635 8636 // Found std::abs(), check that they are the right ones. 8637 if (FDecl->getNumParams() != 1) 8638 continue; 8639 8640 // Check that the parameter type can handle the argument. 8641 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8642 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8643 S.Context.getTypeSize(ArgType) <= 8644 S.Context.getTypeSize(ParamType)) { 8645 // Found a function, don't need the header hint. 8646 EmitHeaderHint = false; 8647 break; 8648 } 8649 } 8650 } 8651 } else { 8652 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8653 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8654 8655 if (HeaderName) { 8656 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8657 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8658 R.suppressDiagnostics(); 8659 S.LookupName(R, S.getCurScope()); 8660 8661 if (R.isSingleResult()) { 8662 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8663 if (FD && FD->getBuiltinID() == AbsKind) { 8664 EmitHeaderHint = false; 8665 } else { 8666 return; 8667 } 8668 } else if (!R.empty()) { 8669 return; 8670 } 8671 } 8672 } 8673 8674 S.Diag(Loc, diag::note_replace_abs_function) 8675 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8676 8677 if (!HeaderName) 8678 return; 8679 8680 if (!EmitHeaderHint) 8681 return; 8682 8683 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8684 << FunctionName; 8685 } 8686 8687 template <std::size_t StrLen> 8688 static bool IsStdFunction(const FunctionDecl *FDecl, 8689 const char (&Str)[StrLen]) { 8690 if (!FDecl) 8691 return false; 8692 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8693 return false; 8694 if (!FDecl->isInStdNamespace()) 8695 return false; 8696 8697 return true; 8698 } 8699 8700 // Warn when using the wrong abs() function. 8701 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8702 const FunctionDecl *FDecl) { 8703 if (Call->getNumArgs() != 1) 8704 return; 8705 8706 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8707 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8708 if (AbsKind == 0 && !IsStdAbs) 8709 return; 8710 8711 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8712 QualType ParamType = Call->getArg(0)->getType(); 8713 8714 // Unsigned types cannot be negative. Suggest removing the absolute value 8715 // function call. 8716 if (ArgType->isUnsignedIntegerType()) { 8717 const char *FunctionName = 8718 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8719 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8720 Diag(Call->getExprLoc(), diag::note_remove_abs) 8721 << FunctionName 8722 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8723 return; 8724 } 8725 8726 // Taking the absolute value of a pointer is very suspicious, they probably 8727 // wanted to index into an array, dereference a pointer, call a function, etc. 8728 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8729 unsigned DiagType = 0; 8730 if (ArgType->isFunctionType()) 8731 DiagType = 1; 8732 else if (ArgType->isArrayType()) 8733 DiagType = 2; 8734 8735 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8736 return; 8737 } 8738 8739 // std::abs has overloads which prevent most of the absolute value problems 8740 // from occurring. 8741 if (IsStdAbs) 8742 return; 8743 8744 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8745 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8746 8747 // The argument and parameter are the same kind. Check if they are the right 8748 // size. 8749 if (ArgValueKind == ParamValueKind) { 8750 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8751 return; 8752 8753 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8754 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8755 << FDecl << ArgType << ParamType; 8756 8757 if (NewAbsKind == 0) 8758 return; 8759 8760 emitReplacement(*this, Call->getExprLoc(), 8761 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8762 return; 8763 } 8764 8765 // ArgValueKind != ParamValueKind 8766 // The wrong type of absolute value function was used. Attempt to find the 8767 // proper one. 8768 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8769 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8770 if (NewAbsKind == 0) 8771 return; 8772 8773 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8774 << FDecl << ParamValueKind << ArgValueKind; 8775 8776 emitReplacement(*this, Call->getExprLoc(), 8777 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8778 } 8779 8780 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8781 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8782 const FunctionDecl *FDecl) { 8783 if (!Call || !FDecl) return; 8784 8785 // Ignore template specializations and macros. 8786 if (inTemplateInstantiation()) return; 8787 if (Call->getExprLoc().isMacroID()) return; 8788 8789 // Only care about the one template argument, two function parameter std::max 8790 if (Call->getNumArgs() != 2) return; 8791 if (!IsStdFunction(FDecl, "max")) return; 8792 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8793 if (!ArgList) return; 8794 if (ArgList->size() != 1) return; 8795 8796 // Check that template type argument is unsigned integer. 8797 const auto& TA = ArgList->get(0); 8798 if (TA.getKind() != TemplateArgument::Type) return; 8799 QualType ArgType = TA.getAsType(); 8800 if (!ArgType->isUnsignedIntegerType()) return; 8801 8802 // See if either argument is a literal zero. 8803 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8804 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8805 if (!MTE) return false; 8806 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8807 if (!Num) return false; 8808 if (Num->getValue() != 0) return false; 8809 return true; 8810 }; 8811 8812 const Expr *FirstArg = Call->getArg(0); 8813 const Expr *SecondArg = Call->getArg(1); 8814 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8815 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8816 8817 // Only warn when exactly one argument is zero. 8818 if (IsFirstArgZero == IsSecondArgZero) return; 8819 8820 SourceRange FirstRange = FirstArg->getSourceRange(); 8821 SourceRange SecondRange = SecondArg->getSourceRange(); 8822 8823 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8824 8825 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8826 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8827 8828 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8829 SourceRange RemovalRange; 8830 if (IsFirstArgZero) { 8831 RemovalRange = SourceRange(FirstRange.getBegin(), 8832 SecondRange.getBegin().getLocWithOffset(-1)); 8833 } else { 8834 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8835 SecondRange.getEnd()); 8836 } 8837 8838 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8839 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8840 << FixItHint::CreateRemoval(RemovalRange); 8841 } 8842 8843 //===--- CHECK: Standard memory functions ---------------------------------===// 8844 8845 /// Takes the expression passed to the size_t parameter of functions 8846 /// such as memcmp, strncat, etc and warns if it's a comparison. 8847 /// 8848 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8849 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8850 IdentifierInfo *FnName, 8851 SourceLocation FnLoc, 8852 SourceLocation RParenLoc) { 8853 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8854 if (!Size) 8855 return false; 8856 8857 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8858 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8859 return false; 8860 8861 SourceRange SizeRange = Size->getSourceRange(); 8862 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8863 << SizeRange << FnName; 8864 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8865 << FnName 8866 << FixItHint::CreateInsertion( 8867 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8868 << FixItHint::CreateRemoval(RParenLoc); 8869 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8870 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8871 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8872 ")"); 8873 8874 return true; 8875 } 8876 8877 /// Determine whether the given type is or contains a dynamic class type 8878 /// (e.g., whether it has a vtable). 8879 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8880 bool &IsContained) { 8881 // Look through array types while ignoring qualifiers. 8882 const Type *Ty = T->getBaseElementTypeUnsafe(); 8883 IsContained = false; 8884 8885 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8886 RD = RD ? RD->getDefinition() : nullptr; 8887 if (!RD || RD->isInvalidDecl()) 8888 return nullptr; 8889 8890 if (RD->isDynamicClass()) 8891 return RD; 8892 8893 // Check all the fields. If any bases were dynamic, the class is dynamic. 8894 // It's impossible for a class to transitively contain itself by value, so 8895 // infinite recursion is impossible. 8896 for (auto *FD : RD->fields()) { 8897 bool SubContained; 8898 if (const CXXRecordDecl *ContainedRD = 8899 getContainedDynamicClass(FD->getType(), SubContained)) { 8900 IsContained = true; 8901 return ContainedRD; 8902 } 8903 } 8904 8905 return nullptr; 8906 } 8907 8908 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8909 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8910 if (Unary->getKind() == UETT_SizeOf) 8911 return Unary; 8912 return nullptr; 8913 } 8914 8915 /// If E is a sizeof expression, returns its argument expression, 8916 /// otherwise returns NULL. 8917 static const Expr *getSizeOfExprArg(const Expr *E) { 8918 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8919 if (!SizeOf->isArgumentType()) 8920 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8921 return nullptr; 8922 } 8923 8924 /// If E is a sizeof expression, returns its argument type. 8925 static QualType getSizeOfArgType(const Expr *E) { 8926 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8927 return SizeOf->getTypeOfArgument(); 8928 return QualType(); 8929 } 8930 8931 namespace { 8932 8933 struct SearchNonTrivialToInitializeField 8934 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8935 using Super = 8936 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8937 8938 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8939 8940 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8941 SourceLocation SL) { 8942 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8943 asDerived().visitArray(PDIK, AT, SL); 8944 return; 8945 } 8946 8947 Super::visitWithKind(PDIK, FT, SL); 8948 } 8949 8950 void visitARCStrong(QualType FT, SourceLocation SL) { 8951 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8952 } 8953 void visitARCWeak(QualType FT, SourceLocation SL) { 8954 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8955 } 8956 void visitStruct(QualType FT, SourceLocation SL) { 8957 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8958 visit(FD->getType(), FD->getLocation()); 8959 } 8960 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8961 const ArrayType *AT, SourceLocation SL) { 8962 visit(getContext().getBaseElementType(AT), SL); 8963 } 8964 void visitTrivial(QualType FT, SourceLocation SL) {} 8965 8966 static void diag(QualType RT, const Expr *E, Sema &S) { 8967 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8968 } 8969 8970 ASTContext &getContext() { return S.getASTContext(); } 8971 8972 const Expr *E; 8973 Sema &S; 8974 }; 8975 8976 struct SearchNonTrivialToCopyField 8977 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8978 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8979 8980 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8981 8982 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8983 SourceLocation SL) { 8984 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8985 asDerived().visitArray(PCK, AT, SL); 8986 return; 8987 } 8988 8989 Super::visitWithKind(PCK, FT, SL); 8990 } 8991 8992 void visitARCStrong(QualType FT, SourceLocation SL) { 8993 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8994 } 8995 void visitARCWeak(QualType FT, SourceLocation SL) { 8996 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8997 } 8998 void visitStruct(QualType FT, SourceLocation SL) { 8999 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9000 visit(FD->getType(), FD->getLocation()); 9001 } 9002 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9003 SourceLocation SL) { 9004 visit(getContext().getBaseElementType(AT), SL); 9005 } 9006 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9007 SourceLocation SL) {} 9008 void visitTrivial(QualType FT, SourceLocation SL) {} 9009 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9010 9011 static void diag(QualType RT, const Expr *E, Sema &S) { 9012 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9013 } 9014 9015 ASTContext &getContext() { return S.getASTContext(); } 9016 9017 const Expr *E; 9018 Sema &S; 9019 }; 9020 9021 } 9022 9023 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9024 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9025 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9026 9027 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9028 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9029 return false; 9030 9031 return doesExprLikelyComputeSize(BO->getLHS()) || 9032 doesExprLikelyComputeSize(BO->getRHS()); 9033 } 9034 9035 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9036 } 9037 9038 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9039 /// 9040 /// \code 9041 /// #define MACRO 0 9042 /// foo(MACRO); 9043 /// foo(0); 9044 /// \endcode 9045 /// 9046 /// This should return true for the first call to foo, but not for the second 9047 /// (regardless of whether foo is a macro or function). 9048 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9049 SourceLocation CallLoc, 9050 SourceLocation ArgLoc) { 9051 if (!CallLoc.isMacroID()) 9052 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9053 9054 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9055 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9056 } 9057 9058 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9059 /// last two arguments transposed. 9060 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9061 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9062 return; 9063 9064 const Expr *SizeArg = 9065 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9066 9067 auto isLiteralZero = [](const Expr *E) { 9068 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9069 }; 9070 9071 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9072 SourceLocation CallLoc = Call->getRParenLoc(); 9073 SourceManager &SM = S.getSourceManager(); 9074 if (isLiteralZero(SizeArg) && 9075 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9076 9077 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9078 9079 // Some platforms #define bzero to __builtin_memset. See if this is the 9080 // case, and if so, emit a better diagnostic. 9081 if (BId == Builtin::BIbzero || 9082 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9083 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9084 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9085 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9086 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9087 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9088 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9089 } 9090 return; 9091 } 9092 9093 // If the second argument to a memset is a sizeof expression and the third 9094 // isn't, this is also likely an error. This should catch 9095 // 'memset(buf, sizeof(buf), 0xff)'. 9096 if (BId == Builtin::BImemset && 9097 doesExprLikelyComputeSize(Call->getArg(1)) && 9098 !doesExprLikelyComputeSize(Call->getArg(2))) { 9099 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9100 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9101 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9102 return; 9103 } 9104 } 9105 9106 /// Check for dangerous or invalid arguments to memset(). 9107 /// 9108 /// This issues warnings on known problematic, dangerous or unspecified 9109 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9110 /// function calls. 9111 /// 9112 /// \param Call The call expression to diagnose. 9113 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9114 unsigned BId, 9115 IdentifierInfo *FnName) { 9116 assert(BId != 0); 9117 9118 // It is possible to have a non-standard definition of memset. Validate 9119 // we have enough arguments, and if not, abort further checking. 9120 unsigned ExpectedNumArgs = 9121 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9122 if (Call->getNumArgs() < ExpectedNumArgs) 9123 return; 9124 9125 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9126 BId == Builtin::BIstrndup ? 1 : 2); 9127 unsigned LenArg = 9128 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9129 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9130 9131 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9132 Call->getBeginLoc(), Call->getRParenLoc())) 9133 return; 9134 9135 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9136 CheckMemaccessSize(*this, BId, Call); 9137 9138 // We have special checking when the length is a sizeof expression. 9139 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9140 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9141 llvm::FoldingSetNodeID SizeOfArgID; 9142 9143 // Although widely used, 'bzero' is not a standard function. Be more strict 9144 // with the argument types before allowing diagnostics and only allow the 9145 // form bzero(ptr, sizeof(...)). 9146 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9147 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9148 return; 9149 9150 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9151 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9152 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9153 9154 QualType DestTy = Dest->getType(); 9155 QualType PointeeTy; 9156 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9157 PointeeTy = DestPtrTy->getPointeeType(); 9158 9159 // Never warn about void type pointers. This can be used to suppress 9160 // false positives. 9161 if (PointeeTy->isVoidType()) 9162 continue; 9163 9164 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9165 // actually comparing the expressions for equality. Because computing the 9166 // expression IDs can be expensive, we only do this if the diagnostic is 9167 // enabled. 9168 if (SizeOfArg && 9169 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9170 SizeOfArg->getExprLoc())) { 9171 // We only compute IDs for expressions if the warning is enabled, and 9172 // cache the sizeof arg's ID. 9173 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9174 SizeOfArg->Profile(SizeOfArgID, Context, true); 9175 llvm::FoldingSetNodeID DestID; 9176 Dest->Profile(DestID, Context, true); 9177 if (DestID == SizeOfArgID) { 9178 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9179 // over sizeof(src) as well. 9180 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9181 StringRef ReadableName = FnName->getName(); 9182 9183 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9184 if (UnaryOp->getOpcode() == UO_AddrOf) 9185 ActionIdx = 1; // If its an address-of operator, just remove it. 9186 if (!PointeeTy->isIncompleteType() && 9187 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9188 ActionIdx = 2; // If the pointee's size is sizeof(char), 9189 // suggest an explicit length. 9190 9191 // If the function is defined as a builtin macro, do not show macro 9192 // expansion. 9193 SourceLocation SL = SizeOfArg->getExprLoc(); 9194 SourceRange DSR = Dest->getSourceRange(); 9195 SourceRange SSR = SizeOfArg->getSourceRange(); 9196 SourceManager &SM = getSourceManager(); 9197 9198 if (SM.isMacroArgExpansion(SL)) { 9199 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9200 SL = SM.getSpellingLoc(SL); 9201 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9202 SM.getSpellingLoc(DSR.getEnd())); 9203 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9204 SM.getSpellingLoc(SSR.getEnd())); 9205 } 9206 9207 DiagRuntimeBehavior(SL, SizeOfArg, 9208 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9209 << ReadableName 9210 << PointeeTy 9211 << DestTy 9212 << DSR 9213 << SSR); 9214 DiagRuntimeBehavior(SL, SizeOfArg, 9215 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9216 << ActionIdx 9217 << SSR); 9218 9219 break; 9220 } 9221 } 9222 9223 // Also check for cases where the sizeof argument is the exact same 9224 // type as the memory argument, and where it points to a user-defined 9225 // record type. 9226 if (SizeOfArgTy != QualType()) { 9227 if (PointeeTy->isRecordType() && 9228 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9229 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9230 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9231 << FnName << SizeOfArgTy << ArgIdx 9232 << PointeeTy << Dest->getSourceRange() 9233 << LenExpr->getSourceRange()); 9234 break; 9235 } 9236 } 9237 } else if (DestTy->isArrayType()) { 9238 PointeeTy = DestTy; 9239 } 9240 9241 if (PointeeTy == QualType()) 9242 continue; 9243 9244 // Always complain about dynamic classes. 9245 bool IsContained; 9246 if (const CXXRecordDecl *ContainedRD = 9247 getContainedDynamicClass(PointeeTy, IsContained)) { 9248 9249 unsigned OperationType = 0; 9250 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9251 // "overwritten" if we're warning about the destination for any call 9252 // but memcmp; otherwise a verb appropriate to the call. 9253 if (ArgIdx != 0 || IsCmp) { 9254 if (BId == Builtin::BImemcpy) 9255 OperationType = 1; 9256 else if(BId == Builtin::BImemmove) 9257 OperationType = 2; 9258 else if (IsCmp) 9259 OperationType = 3; 9260 } 9261 9262 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9263 PDiag(diag::warn_dyn_class_memaccess) 9264 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9265 << IsContained << ContainedRD << OperationType 9266 << Call->getCallee()->getSourceRange()); 9267 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9268 BId != Builtin::BImemset) 9269 DiagRuntimeBehavior( 9270 Dest->getExprLoc(), Dest, 9271 PDiag(diag::warn_arc_object_memaccess) 9272 << ArgIdx << FnName << PointeeTy 9273 << Call->getCallee()->getSourceRange()); 9274 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9275 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9276 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9277 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9278 PDiag(diag::warn_cstruct_memaccess) 9279 << ArgIdx << FnName << PointeeTy << 0); 9280 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9281 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9282 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9283 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9284 PDiag(diag::warn_cstruct_memaccess) 9285 << ArgIdx << FnName << PointeeTy << 1); 9286 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9287 } else { 9288 continue; 9289 } 9290 } else 9291 continue; 9292 9293 DiagRuntimeBehavior( 9294 Dest->getExprLoc(), Dest, 9295 PDiag(diag::note_bad_memaccess_silence) 9296 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9297 break; 9298 } 9299 } 9300 9301 // A little helper routine: ignore addition and subtraction of integer literals. 9302 // This intentionally does not ignore all integer constant expressions because 9303 // we don't want to remove sizeof(). 9304 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9305 Ex = Ex->IgnoreParenCasts(); 9306 9307 while (true) { 9308 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9309 if (!BO || !BO->isAdditiveOp()) 9310 break; 9311 9312 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9313 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9314 9315 if (isa<IntegerLiteral>(RHS)) 9316 Ex = LHS; 9317 else if (isa<IntegerLiteral>(LHS)) 9318 Ex = RHS; 9319 else 9320 break; 9321 } 9322 9323 return Ex; 9324 } 9325 9326 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9327 ASTContext &Context) { 9328 // Only handle constant-sized or VLAs, but not flexible members. 9329 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9330 // Only issue the FIXIT for arrays of size > 1. 9331 if (CAT->getSize().getSExtValue() <= 1) 9332 return false; 9333 } else if (!Ty->isVariableArrayType()) { 9334 return false; 9335 } 9336 return true; 9337 } 9338 9339 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9340 // be the size of the source, instead of the destination. 9341 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9342 IdentifierInfo *FnName) { 9343 9344 // Don't crash if the user has the wrong number of arguments 9345 unsigned NumArgs = Call->getNumArgs(); 9346 if ((NumArgs != 3) && (NumArgs != 4)) 9347 return; 9348 9349 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9350 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9351 const Expr *CompareWithSrc = nullptr; 9352 9353 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9354 Call->getBeginLoc(), Call->getRParenLoc())) 9355 return; 9356 9357 // Look for 'strlcpy(dst, x, sizeof(x))' 9358 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9359 CompareWithSrc = Ex; 9360 else { 9361 // Look for 'strlcpy(dst, x, strlen(x))' 9362 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9363 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9364 SizeCall->getNumArgs() == 1) 9365 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9366 } 9367 } 9368 9369 if (!CompareWithSrc) 9370 return; 9371 9372 // Determine if the argument to sizeof/strlen is equal to the source 9373 // argument. In principle there's all kinds of things you could do 9374 // here, for instance creating an == expression and evaluating it with 9375 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9376 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9377 if (!SrcArgDRE) 9378 return; 9379 9380 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9381 if (!CompareWithSrcDRE || 9382 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9383 return; 9384 9385 const Expr *OriginalSizeArg = Call->getArg(2); 9386 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9387 << OriginalSizeArg->getSourceRange() << FnName; 9388 9389 // Output a FIXIT hint if the destination is an array (rather than a 9390 // pointer to an array). This could be enhanced to handle some 9391 // pointers if we know the actual size, like if DstArg is 'array+2' 9392 // we could say 'sizeof(array)-2'. 9393 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9394 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9395 return; 9396 9397 SmallString<128> sizeString; 9398 llvm::raw_svector_ostream OS(sizeString); 9399 OS << "sizeof("; 9400 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9401 OS << ")"; 9402 9403 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9404 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9405 OS.str()); 9406 } 9407 9408 /// Check if two expressions refer to the same declaration. 9409 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9410 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9411 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9412 return D1->getDecl() == D2->getDecl(); 9413 return false; 9414 } 9415 9416 static const Expr *getStrlenExprArg(const Expr *E) { 9417 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9418 const FunctionDecl *FD = CE->getDirectCallee(); 9419 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9420 return nullptr; 9421 return CE->getArg(0)->IgnoreParenCasts(); 9422 } 9423 return nullptr; 9424 } 9425 9426 // Warn on anti-patterns as the 'size' argument to strncat. 9427 // The correct size argument should look like following: 9428 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9429 void Sema::CheckStrncatArguments(const CallExpr *CE, 9430 IdentifierInfo *FnName) { 9431 // Don't crash if the user has the wrong number of arguments. 9432 if (CE->getNumArgs() < 3) 9433 return; 9434 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9435 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9436 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9437 9438 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9439 CE->getRParenLoc())) 9440 return; 9441 9442 // Identify common expressions, which are wrongly used as the size argument 9443 // to strncat and may lead to buffer overflows. 9444 unsigned PatternType = 0; 9445 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9446 // - sizeof(dst) 9447 if (referToTheSameDecl(SizeOfArg, DstArg)) 9448 PatternType = 1; 9449 // - sizeof(src) 9450 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9451 PatternType = 2; 9452 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9453 if (BE->getOpcode() == BO_Sub) { 9454 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9455 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9456 // - sizeof(dst) - strlen(dst) 9457 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9458 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9459 PatternType = 1; 9460 // - sizeof(src) - (anything) 9461 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9462 PatternType = 2; 9463 } 9464 } 9465 9466 if (PatternType == 0) 9467 return; 9468 9469 // Generate the diagnostic. 9470 SourceLocation SL = LenArg->getBeginLoc(); 9471 SourceRange SR = LenArg->getSourceRange(); 9472 SourceManager &SM = getSourceManager(); 9473 9474 // If the function is defined as a builtin macro, do not show macro expansion. 9475 if (SM.isMacroArgExpansion(SL)) { 9476 SL = SM.getSpellingLoc(SL); 9477 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9478 SM.getSpellingLoc(SR.getEnd())); 9479 } 9480 9481 // Check if the destination is an array (rather than a pointer to an array). 9482 QualType DstTy = DstArg->getType(); 9483 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9484 Context); 9485 if (!isKnownSizeArray) { 9486 if (PatternType == 1) 9487 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9488 else 9489 Diag(SL, diag::warn_strncat_src_size) << SR; 9490 return; 9491 } 9492 9493 if (PatternType == 1) 9494 Diag(SL, diag::warn_strncat_large_size) << SR; 9495 else 9496 Diag(SL, diag::warn_strncat_src_size) << SR; 9497 9498 SmallString<128> sizeString; 9499 llvm::raw_svector_ostream OS(sizeString); 9500 OS << "sizeof("; 9501 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9502 OS << ") - "; 9503 OS << "strlen("; 9504 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9505 OS << ") - 1"; 9506 9507 Diag(SL, diag::note_strncat_wrong_size) 9508 << FixItHint::CreateReplacement(SR, OS.str()); 9509 } 9510 9511 void 9512 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9513 SourceLocation ReturnLoc, 9514 bool isObjCMethod, 9515 const AttrVec *Attrs, 9516 const FunctionDecl *FD) { 9517 // Check if the return value is null but should not be. 9518 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9519 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9520 CheckNonNullExpr(*this, RetValExp)) 9521 Diag(ReturnLoc, diag::warn_null_ret) 9522 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9523 9524 // C++11 [basic.stc.dynamic.allocation]p4: 9525 // If an allocation function declared with a non-throwing 9526 // exception-specification fails to allocate storage, it shall return 9527 // a null pointer. Any other allocation function that fails to allocate 9528 // storage shall indicate failure only by throwing an exception [...] 9529 if (FD) { 9530 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9531 if (Op == OO_New || Op == OO_Array_New) { 9532 const FunctionProtoType *Proto 9533 = FD->getType()->castAs<FunctionProtoType>(); 9534 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9535 CheckNonNullExpr(*this, RetValExp)) 9536 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9537 << FD << getLangOpts().CPlusPlus11; 9538 } 9539 } 9540 } 9541 9542 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9543 9544 /// Check for comparisons of floating point operands using != and ==. 9545 /// Issue a warning if these are no self-comparisons, as they are not likely 9546 /// to do what the programmer intended. 9547 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9548 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9549 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9550 9551 // Special case: check for x == x (which is OK). 9552 // Do not emit warnings for such cases. 9553 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9554 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9555 if (DRL->getDecl() == DRR->getDecl()) 9556 return; 9557 9558 // Special case: check for comparisons against literals that can be exactly 9559 // represented by APFloat. In such cases, do not emit a warning. This 9560 // is a heuristic: often comparison against such literals are used to 9561 // detect if a value in a variable has not changed. This clearly can 9562 // lead to false negatives. 9563 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9564 if (FLL->isExact()) 9565 return; 9566 } else 9567 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9568 if (FLR->isExact()) 9569 return; 9570 9571 // Check for comparisons with builtin types. 9572 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9573 if (CL->getBuiltinCallee()) 9574 return; 9575 9576 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9577 if (CR->getBuiltinCallee()) 9578 return; 9579 9580 // Emit the diagnostic. 9581 Diag(Loc, diag::warn_floatingpoint_eq) 9582 << LHS->getSourceRange() << RHS->getSourceRange(); 9583 } 9584 9585 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9586 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9587 9588 namespace { 9589 9590 /// Structure recording the 'active' range of an integer-valued 9591 /// expression. 9592 struct IntRange { 9593 /// The number of bits active in the int. 9594 unsigned Width; 9595 9596 /// True if the int is known not to have negative values. 9597 bool NonNegative; 9598 9599 IntRange(unsigned Width, bool NonNegative) 9600 : Width(Width), NonNegative(NonNegative) {} 9601 9602 /// Returns the range of the bool type. 9603 static IntRange forBoolType() { 9604 return IntRange(1, true); 9605 } 9606 9607 /// Returns the range of an opaque value of the given integral type. 9608 static IntRange forValueOfType(ASTContext &C, QualType T) { 9609 return forValueOfCanonicalType(C, 9610 T->getCanonicalTypeInternal().getTypePtr()); 9611 } 9612 9613 /// Returns the range of an opaque value of a canonical integral type. 9614 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9615 assert(T->isCanonicalUnqualified()); 9616 9617 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9618 T = VT->getElementType().getTypePtr(); 9619 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9620 T = CT->getElementType().getTypePtr(); 9621 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9622 T = AT->getValueType().getTypePtr(); 9623 9624 if (!C.getLangOpts().CPlusPlus) { 9625 // For enum types in C code, use the underlying datatype. 9626 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9627 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9628 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9629 // For enum types in C++, use the known bit width of the enumerators. 9630 EnumDecl *Enum = ET->getDecl(); 9631 // In C++11, enums can have a fixed underlying type. Use this type to 9632 // compute the range. 9633 if (Enum->isFixed()) { 9634 return IntRange(C.getIntWidth(QualType(T, 0)), 9635 !ET->isSignedIntegerOrEnumerationType()); 9636 } 9637 9638 unsigned NumPositive = Enum->getNumPositiveBits(); 9639 unsigned NumNegative = Enum->getNumNegativeBits(); 9640 9641 if (NumNegative == 0) 9642 return IntRange(NumPositive, true/*NonNegative*/); 9643 else 9644 return IntRange(std::max(NumPositive + 1, NumNegative), 9645 false/*NonNegative*/); 9646 } 9647 9648 const BuiltinType *BT = cast<BuiltinType>(T); 9649 assert(BT->isInteger()); 9650 9651 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9652 } 9653 9654 /// Returns the "target" range of a canonical integral type, i.e. 9655 /// the range of values expressible in the type. 9656 /// 9657 /// This matches forValueOfCanonicalType except that enums have the 9658 /// full range of their type, not the range of their enumerators. 9659 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9660 assert(T->isCanonicalUnqualified()); 9661 9662 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9663 T = VT->getElementType().getTypePtr(); 9664 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9665 T = CT->getElementType().getTypePtr(); 9666 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9667 T = AT->getValueType().getTypePtr(); 9668 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9669 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9670 9671 const BuiltinType *BT = cast<BuiltinType>(T); 9672 assert(BT->isInteger()); 9673 9674 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9675 } 9676 9677 /// Returns the supremum of two ranges: i.e. their conservative merge. 9678 static IntRange join(IntRange L, IntRange R) { 9679 return IntRange(std::max(L.Width, R.Width), 9680 L.NonNegative && R.NonNegative); 9681 } 9682 9683 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9684 static IntRange meet(IntRange L, IntRange R) { 9685 return IntRange(std::min(L.Width, R.Width), 9686 L.NonNegative || R.NonNegative); 9687 } 9688 }; 9689 9690 } // namespace 9691 9692 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9693 unsigned MaxWidth) { 9694 if (value.isSigned() && value.isNegative()) 9695 return IntRange(value.getMinSignedBits(), false); 9696 9697 if (value.getBitWidth() > MaxWidth) 9698 value = value.trunc(MaxWidth); 9699 9700 // isNonNegative() just checks the sign bit without considering 9701 // signedness. 9702 return IntRange(value.getActiveBits(), true); 9703 } 9704 9705 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9706 unsigned MaxWidth) { 9707 if (result.isInt()) 9708 return GetValueRange(C, result.getInt(), MaxWidth); 9709 9710 if (result.isVector()) { 9711 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9712 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9713 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9714 R = IntRange::join(R, El); 9715 } 9716 return R; 9717 } 9718 9719 if (result.isComplexInt()) { 9720 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9721 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9722 return IntRange::join(R, I); 9723 } 9724 9725 // This can happen with lossless casts to intptr_t of "based" lvalues. 9726 // Assume it might use arbitrary bits. 9727 // FIXME: The only reason we need to pass the type in here is to get 9728 // the sign right on this one case. It would be nice if APValue 9729 // preserved this. 9730 assert(result.isLValue() || result.isAddrLabelDiff()); 9731 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9732 } 9733 9734 static QualType GetExprType(const Expr *E) { 9735 QualType Ty = E->getType(); 9736 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9737 Ty = AtomicRHS->getValueType(); 9738 return Ty; 9739 } 9740 9741 /// Pseudo-evaluate the given integer expression, estimating the 9742 /// range of values it might take. 9743 /// 9744 /// \param MaxWidth - the width to which the value will be truncated 9745 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { 9746 E = E->IgnoreParens(); 9747 9748 // Try a full evaluation first. 9749 Expr::EvalResult result; 9750 if (E->EvaluateAsRValue(result, C)) 9751 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9752 9753 // I think we only want to look through implicit casts here; if the 9754 // user has an explicit widening cast, we should treat the value as 9755 // being of the new, wider type. 9756 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9757 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9758 return GetExprRange(C, CE->getSubExpr(), MaxWidth); 9759 9760 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9761 9762 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9763 CE->getCastKind() == CK_BooleanToSignedIntegral; 9764 9765 // Assume that non-integer casts can span the full range of the type. 9766 if (!isIntegerCast) 9767 return OutputTypeRange; 9768 9769 IntRange SubRange 9770 = GetExprRange(C, CE->getSubExpr(), 9771 std::min(MaxWidth, OutputTypeRange.Width)); 9772 9773 // Bail out if the subexpr's range is as wide as the cast type. 9774 if (SubRange.Width >= OutputTypeRange.Width) 9775 return OutputTypeRange; 9776 9777 // Otherwise, we take the smaller width, and we're non-negative if 9778 // either the output type or the subexpr is. 9779 return IntRange(SubRange.Width, 9780 SubRange.NonNegative || OutputTypeRange.NonNegative); 9781 } 9782 9783 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9784 // If we can fold the condition, just take that operand. 9785 bool CondResult; 9786 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9787 return GetExprRange(C, CondResult ? CO->getTrueExpr() 9788 : CO->getFalseExpr(), 9789 MaxWidth); 9790 9791 // Otherwise, conservatively merge. 9792 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth); 9793 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth); 9794 return IntRange::join(L, R); 9795 } 9796 9797 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9798 switch (BO->getOpcode()) { 9799 case BO_Cmp: 9800 llvm_unreachable("builtin <=> should have class type"); 9801 9802 // Boolean-valued operations are single-bit and positive. 9803 case BO_LAnd: 9804 case BO_LOr: 9805 case BO_LT: 9806 case BO_GT: 9807 case BO_LE: 9808 case BO_GE: 9809 case BO_EQ: 9810 case BO_NE: 9811 return IntRange::forBoolType(); 9812 9813 // The type of the assignments is the type of the LHS, so the RHS 9814 // is not necessarily the same type. 9815 case BO_MulAssign: 9816 case BO_DivAssign: 9817 case BO_RemAssign: 9818 case BO_AddAssign: 9819 case BO_SubAssign: 9820 case BO_XorAssign: 9821 case BO_OrAssign: 9822 // TODO: bitfields? 9823 return IntRange::forValueOfType(C, GetExprType(E)); 9824 9825 // Simple assignments just pass through the RHS, which will have 9826 // been coerced to the LHS type. 9827 case BO_Assign: 9828 // TODO: bitfields? 9829 return GetExprRange(C, BO->getRHS(), MaxWidth); 9830 9831 // Operations with opaque sources are black-listed. 9832 case BO_PtrMemD: 9833 case BO_PtrMemI: 9834 return IntRange::forValueOfType(C, GetExprType(E)); 9835 9836 // Bitwise-and uses the *infinum* of the two source ranges. 9837 case BO_And: 9838 case BO_AndAssign: 9839 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth), 9840 GetExprRange(C, BO->getRHS(), MaxWidth)); 9841 9842 // Left shift gets black-listed based on a judgement call. 9843 case BO_Shl: 9844 // ...except that we want to treat '1 << (blah)' as logically 9845 // positive. It's an important idiom. 9846 if (IntegerLiteral *I 9847 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9848 if (I->getValue() == 1) { 9849 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9850 return IntRange(R.Width, /*NonNegative*/ true); 9851 } 9852 } 9853 LLVM_FALLTHROUGH; 9854 9855 case BO_ShlAssign: 9856 return IntRange::forValueOfType(C, GetExprType(E)); 9857 9858 // Right shift by a constant can narrow its left argument. 9859 case BO_Shr: 9860 case BO_ShrAssign: { 9861 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9862 9863 // If the shift amount is a positive constant, drop the width by 9864 // that much. 9865 llvm::APSInt shift; 9866 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9867 shift.isNonNegative()) { 9868 unsigned zext = shift.getZExtValue(); 9869 if (zext >= L.Width) 9870 L.Width = (L.NonNegative ? 0 : 1); 9871 else 9872 L.Width -= zext; 9873 } 9874 9875 return L; 9876 } 9877 9878 // Comma acts as its right operand. 9879 case BO_Comma: 9880 return GetExprRange(C, BO->getRHS(), MaxWidth); 9881 9882 // Black-list pointer subtractions. 9883 case BO_Sub: 9884 if (BO->getLHS()->getType()->isPointerType()) 9885 return IntRange::forValueOfType(C, GetExprType(E)); 9886 break; 9887 9888 // The width of a division result is mostly determined by the size 9889 // of the LHS. 9890 case BO_Div: { 9891 // Don't 'pre-truncate' the operands. 9892 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9893 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9894 9895 // If the divisor is constant, use that. 9896 llvm::APSInt divisor; 9897 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9898 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9899 if (log2 >= L.Width) 9900 L.Width = (L.NonNegative ? 0 : 1); 9901 else 9902 L.Width = std::min(L.Width - log2, MaxWidth); 9903 return L; 9904 } 9905 9906 // Otherwise, just use the LHS's width. 9907 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9908 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9909 } 9910 9911 // The result of a remainder can't be larger than the result of 9912 // either side. 9913 case BO_Rem: { 9914 // Don't 'pre-truncate' the operands. 9915 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9916 IntRange L = GetExprRange(C, BO->getLHS(), opWidth); 9917 IntRange R = GetExprRange(C, BO->getRHS(), opWidth); 9918 9919 IntRange meet = IntRange::meet(L, R); 9920 meet.Width = std::min(meet.Width, MaxWidth); 9921 return meet; 9922 } 9923 9924 // The default behavior is okay for these. 9925 case BO_Mul: 9926 case BO_Add: 9927 case BO_Xor: 9928 case BO_Or: 9929 break; 9930 } 9931 9932 // The default case is to treat the operation as if it were closed 9933 // on the narrowest type that encompasses both operands. 9934 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth); 9935 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth); 9936 return IntRange::join(L, R); 9937 } 9938 9939 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9940 switch (UO->getOpcode()) { 9941 // Boolean-valued operations are white-listed. 9942 case UO_LNot: 9943 return IntRange::forBoolType(); 9944 9945 // Operations with opaque sources are black-listed. 9946 case UO_Deref: 9947 case UO_AddrOf: // should be impossible 9948 return IntRange::forValueOfType(C, GetExprType(E)); 9949 9950 default: 9951 return GetExprRange(C, UO->getSubExpr(), MaxWidth); 9952 } 9953 } 9954 9955 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9956 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); 9957 9958 if (const auto *BitField = E->getSourceBitField()) 9959 return IntRange(BitField->getBitWidthValue(C), 9960 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9961 9962 return IntRange::forValueOfType(C, GetExprType(E)); 9963 } 9964 9965 static IntRange GetExprRange(ASTContext &C, const Expr *E) { 9966 return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); 9967 } 9968 9969 /// Checks whether the given value, which currently has the given 9970 /// source semantics, has the same value when coerced through the 9971 /// target semantics. 9972 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 9973 const llvm::fltSemantics &Src, 9974 const llvm::fltSemantics &Tgt) { 9975 llvm::APFloat truncated = value; 9976 9977 bool ignored; 9978 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 9979 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 9980 9981 return truncated.bitwiseIsEqual(value); 9982 } 9983 9984 /// Checks whether the given value, which currently has the given 9985 /// source semantics, has the same value when coerced through the 9986 /// target semantics. 9987 /// 9988 /// The value might be a vector of floats (or a complex number). 9989 static bool IsSameFloatAfterCast(const APValue &value, 9990 const llvm::fltSemantics &Src, 9991 const llvm::fltSemantics &Tgt) { 9992 if (value.isFloat()) 9993 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 9994 9995 if (value.isVector()) { 9996 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 9997 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 9998 return false; 9999 return true; 10000 } 10001 10002 assert(value.isComplexFloat()); 10003 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10004 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10005 } 10006 10007 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 10008 10009 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10010 // Suppress cases where we are comparing against an enum constant. 10011 if (const DeclRefExpr *DR = 10012 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10013 if (isa<EnumConstantDecl>(DR->getDecl())) 10014 return true; 10015 10016 // Suppress cases where the '0' value is expanded from a macro. 10017 if (E->getBeginLoc().isMacroID()) 10018 return true; 10019 10020 return false; 10021 } 10022 10023 static bool isKnownToHaveUnsignedValue(Expr *E) { 10024 return E->getType()->isIntegerType() && 10025 (!E->getType()->isSignedIntegerType() || 10026 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10027 } 10028 10029 namespace { 10030 /// The promoted range of values of a type. In general this has the 10031 /// following structure: 10032 /// 10033 /// |-----------| . . . |-----------| 10034 /// ^ ^ ^ ^ 10035 /// Min HoleMin HoleMax Max 10036 /// 10037 /// ... where there is only a hole if a signed type is promoted to unsigned 10038 /// (in which case Min and Max are the smallest and largest representable 10039 /// values). 10040 struct PromotedRange { 10041 // Min, or HoleMax if there is a hole. 10042 llvm::APSInt PromotedMin; 10043 // Max, or HoleMin if there is a hole. 10044 llvm::APSInt PromotedMax; 10045 10046 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10047 if (R.Width == 0) 10048 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10049 else if (R.Width >= BitWidth && !Unsigned) { 10050 // Promotion made the type *narrower*. This happens when promoting 10051 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10052 // Treat all values of 'signed int' as being in range for now. 10053 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10054 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10055 } else { 10056 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10057 .extOrTrunc(BitWidth); 10058 PromotedMin.setIsUnsigned(Unsigned); 10059 10060 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10061 .extOrTrunc(BitWidth); 10062 PromotedMax.setIsUnsigned(Unsigned); 10063 } 10064 } 10065 10066 // Determine whether this range is contiguous (has no hole). 10067 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10068 10069 // Where a constant value is within the range. 10070 enum ComparisonResult { 10071 LT = 0x1, 10072 LE = 0x2, 10073 GT = 0x4, 10074 GE = 0x8, 10075 EQ = 0x10, 10076 NE = 0x20, 10077 InRangeFlag = 0x40, 10078 10079 Less = LE | LT | NE, 10080 Min = LE | InRangeFlag, 10081 InRange = InRangeFlag, 10082 Max = GE | InRangeFlag, 10083 Greater = GE | GT | NE, 10084 10085 OnlyValue = LE | GE | EQ | InRangeFlag, 10086 InHole = NE 10087 }; 10088 10089 ComparisonResult compare(const llvm::APSInt &Value) const { 10090 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10091 Value.isUnsigned() == PromotedMin.isUnsigned()); 10092 if (!isContiguous()) { 10093 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10094 if (Value.isMinValue()) return Min; 10095 if (Value.isMaxValue()) return Max; 10096 if (Value >= PromotedMin) return InRange; 10097 if (Value <= PromotedMax) return InRange; 10098 return InHole; 10099 } 10100 10101 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10102 case -1: return Less; 10103 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10104 case 1: 10105 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10106 case -1: return InRange; 10107 case 0: return Max; 10108 case 1: return Greater; 10109 } 10110 } 10111 10112 llvm_unreachable("impossible compare result"); 10113 } 10114 10115 static llvm::Optional<StringRef> 10116 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10117 if (Op == BO_Cmp) { 10118 ComparisonResult LTFlag = LT, GTFlag = GT; 10119 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10120 10121 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10122 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10123 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10124 return llvm::None; 10125 } 10126 10127 ComparisonResult TrueFlag, FalseFlag; 10128 if (Op == BO_EQ) { 10129 TrueFlag = EQ; 10130 FalseFlag = NE; 10131 } else if (Op == BO_NE) { 10132 TrueFlag = NE; 10133 FalseFlag = EQ; 10134 } else { 10135 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10136 TrueFlag = LT; 10137 FalseFlag = GE; 10138 } else { 10139 TrueFlag = GT; 10140 FalseFlag = LE; 10141 } 10142 if (Op == BO_GE || Op == BO_LE) 10143 std::swap(TrueFlag, FalseFlag); 10144 } 10145 if (R & TrueFlag) 10146 return StringRef("true"); 10147 if (R & FalseFlag) 10148 return StringRef("false"); 10149 return llvm::None; 10150 } 10151 }; 10152 } 10153 10154 static bool HasEnumType(Expr *E) { 10155 // Strip off implicit integral promotions. 10156 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10157 if (ICE->getCastKind() != CK_IntegralCast && 10158 ICE->getCastKind() != CK_NoOp) 10159 break; 10160 E = ICE->getSubExpr(); 10161 } 10162 10163 return E->getType()->isEnumeralType(); 10164 } 10165 10166 static int classifyConstantValue(Expr *Constant) { 10167 // The values of this enumeration are used in the diagnostics 10168 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10169 enum ConstantValueKind { 10170 Miscellaneous = 0, 10171 LiteralTrue, 10172 LiteralFalse 10173 }; 10174 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10175 return BL->getValue() ? ConstantValueKind::LiteralTrue 10176 : ConstantValueKind::LiteralFalse; 10177 return ConstantValueKind::Miscellaneous; 10178 } 10179 10180 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10181 Expr *Constant, Expr *Other, 10182 const llvm::APSInt &Value, 10183 bool RhsConstant) { 10184 if (S.inTemplateInstantiation()) 10185 return false; 10186 10187 Expr *OriginalOther = Other; 10188 10189 Constant = Constant->IgnoreParenImpCasts(); 10190 Other = Other->IgnoreParenImpCasts(); 10191 10192 // Suppress warnings on tautological comparisons between values of the same 10193 // enumeration type. There are only two ways we could warn on this: 10194 // - If the constant is outside the range of representable values of 10195 // the enumeration. In such a case, we should warn about the cast 10196 // to enumeration type, not about the comparison. 10197 // - If the constant is the maximum / minimum in-range value. For an 10198 // enumeratin type, such comparisons can be meaningful and useful. 10199 if (Constant->getType()->isEnumeralType() && 10200 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10201 return false; 10202 10203 // TODO: Investigate using GetExprRange() to get tighter bounds 10204 // on the bit ranges. 10205 QualType OtherT = Other->getType(); 10206 if (const auto *AT = OtherT->getAs<AtomicType>()) 10207 OtherT = AT->getValueType(); 10208 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10209 10210 // Whether we're treating Other as being a bool because of the form of 10211 // expression despite it having another type (typically 'int' in C). 10212 bool OtherIsBooleanDespiteType = 10213 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10214 if (OtherIsBooleanDespiteType) 10215 OtherRange = IntRange::forBoolType(); 10216 10217 // Determine the promoted range of the other type and see if a comparison of 10218 // the constant against that range is tautological. 10219 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10220 Value.isUnsigned()); 10221 auto Cmp = OtherPromotedRange.compare(Value); 10222 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10223 if (!Result) 10224 return false; 10225 10226 // Suppress the diagnostic for an in-range comparison if the constant comes 10227 // from a macro or enumerator. We don't want to diagnose 10228 // 10229 // some_long_value <= INT_MAX 10230 // 10231 // when sizeof(int) == sizeof(long). 10232 bool InRange = Cmp & PromotedRange::InRangeFlag; 10233 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10234 return false; 10235 10236 // If this is a comparison to an enum constant, include that 10237 // constant in the diagnostic. 10238 const EnumConstantDecl *ED = nullptr; 10239 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10240 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10241 10242 // Should be enough for uint128 (39 decimal digits) 10243 SmallString<64> PrettySourceValue; 10244 llvm::raw_svector_ostream OS(PrettySourceValue); 10245 if (ED) 10246 OS << '\'' << *ED << "' (" << Value << ")"; 10247 else 10248 OS << Value; 10249 10250 // FIXME: We use a somewhat different formatting for the in-range cases and 10251 // cases involving boolean values for historical reasons. We should pick a 10252 // consistent way of presenting these diagnostics. 10253 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10254 S.DiagRuntimeBehavior( 10255 E->getOperatorLoc(), E, 10256 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10257 : diag::warn_tautological_bool_compare) 10258 << OS.str() << classifyConstantValue(Constant) 10259 << OtherT << OtherIsBooleanDespiteType << *Result 10260 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10261 } else { 10262 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10263 ? (HasEnumType(OriginalOther) 10264 ? diag::warn_unsigned_enum_always_true_comparison 10265 : diag::warn_unsigned_always_true_comparison) 10266 : diag::warn_tautological_constant_compare; 10267 10268 S.Diag(E->getOperatorLoc(), Diag) 10269 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10270 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10271 } 10272 10273 return true; 10274 } 10275 10276 /// Analyze the operands of the given comparison. Implements the 10277 /// fallback case from AnalyzeComparison. 10278 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10279 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10280 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10281 } 10282 10283 /// Implements -Wsign-compare. 10284 /// 10285 /// \param E the binary operator to check for warnings 10286 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10287 // The type the comparison is being performed in. 10288 QualType T = E->getLHS()->getType(); 10289 10290 // Only analyze comparison operators where both sides have been converted to 10291 // the same type. 10292 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10293 return AnalyzeImpConvsInComparison(S, E); 10294 10295 // Don't analyze value-dependent comparisons directly. 10296 if (E->isValueDependent()) 10297 return AnalyzeImpConvsInComparison(S, E); 10298 10299 Expr *LHS = E->getLHS(); 10300 Expr *RHS = E->getRHS(); 10301 10302 if (T->isIntegralType(S.Context)) { 10303 llvm::APSInt RHSValue; 10304 llvm::APSInt LHSValue; 10305 10306 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10307 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10308 10309 // We don't care about expressions whose result is a constant. 10310 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10311 return AnalyzeImpConvsInComparison(S, E); 10312 10313 // We only care about expressions where just one side is literal 10314 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10315 // Is the constant on the RHS or LHS? 10316 const bool RhsConstant = IsRHSIntegralLiteral; 10317 Expr *Const = RhsConstant ? RHS : LHS; 10318 Expr *Other = RhsConstant ? LHS : RHS; 10319 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10320 10321 // Check whether an integer constant comparison results in a value 10322 // of 'true' or 'false'. 10323 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10324 return AnalyzeImpConvsInComparison(S, E); 10325 } 10326 } 10327 10328 if (!T->hasUnsignedIntegerRepresentation()) { 10329 // We don't do anything special if this isn't an unsigned integral 10330 // comparison: we're only interested in integral comparisons, and 10331 // signed comparisons only happen in cases we don't care to warn about. 10332 return AnalyzeImpConvsInComparison(S, E); 10333 } 10334 10335 LHS = LHS->IgnoreParenImpCasts(); 10336 RHS = RHS->IgnoreParenImpCasts(); 10337 10338 if (!S.getLangOpts().CPlusPlus) { 10339 // Avoid warning about comparison of integers with different signs when 10340 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10341 // the type of `E`. 10342 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10343 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10344 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10345 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10346 } 10347 10348 // Check to see if one of the (unmodified) operands is of different 10349 // signedness. 10350 Expr *signedOperand, *unsignedOperand; 10351 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10352 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10353 "unsigned comparison between two signed integer expressions?"); 10354 signedOperand = LHS; 10355 unsignedOperand = RHS; 10356 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10357 signedOperand = RHS; 10358 unsignedOperand = LHS; 10359 } else { 10360 return AnalyzeImpConvsInComparison(S, E); 10361 } 10362 10363 // Otherwise, calculate the effective range of the signed operand. 10364 IntRange signedRange = GetExprRange(S.Context, signedOperand); 10365 10366 // Go ahead and analyze implicit conversions in the operands. Note 10367 // that we skip the implicit conversions on both sides. 10368 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10369 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10370 10371 // If the signed range is non-negative, -Wsign-compare won't fire. 10372 if (signedRange.NonNegative) 10373 return; 10374 10375 // For (in)equality comparisons, if the unsigned operand is a 10376 // constant which cannot collide with a overflowed signed operand, 10377 // then reinterpreting the signed operand as unsigned will not 10378 // change the result of the comparison. 10379 if (E->isEqualityOp()) { 10380 unsigned comparisonWidth = S.Context.getIntWidth(T); 10381 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand); 10382 10383 // We should never be unable to prove that the unsigned operand is 10384 // non-negative. 10385 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10386 10387 if (unsignedRange.Width < comparisonWidth) 10388 return; 10389 } 10390 10391 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10392 S.PDiag(diag::warn_mixed_sign_comparison) 10393 << LHS->getType() << RHS->getType() 10394 << LHS->getSourceRange() << RHS->getSourceRange()); 10395 } 10396 10397 /// Analyzes an attempt to assign the given value to a bitfield. 10398 /// 10399 /// Returns true if there was something fishy about the attempt. 10400 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10401 SourceLocation InitLoc) { 10402 assert(Bitfield->isBitField()); 10403 if (Bitfield->isInvalidDecl()) 10404 return false; 10405 10406 // White-list bool bitfields. 10407 QualType BitfieldType = Bitfield->getType(); 10408 if (BitfieldType->isBooleanType()) 10409 return false; 10410 10411 if (BitfieldType->isEnumeralType()) { 10412 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10413 // If the underlying enum type was not explicitly specified as an unsigned 10414 // type and the enum contain only positive values, MSVC++ will cause an 10415 // inconsistency by storing this as a signed type. 10416 if (S.getLangOpts().CPlusPlus11 && 10417 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10418 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10419 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10420 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10421 << BitfieldEnumDecl->getNameAsString(); 10422 } 10423 } 10424 10425 if (Bitfield->getType()->isBooleanType()) 10426 return false; 10427 10428 // Ignore value- or type-dependent expressions. 10429 if (Bitfield->getBitWidth()->isValueDependent() || 10430 Bitfield->getBitWidth()->isTypeDependent() || 10431 Init->isValueDependent() || 10432 Init->isTypeDependent()) 10433 return false; 10434 10435 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10436 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10437 10438 Expr::EvalResult Result; 10439 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10440 Expr::SE_AllowSideEffects)) { 10441 // The RHS is not constant. If the RHS has an enum type, make sure the 10442 // bitfield is wide enough to hold all the values of the enum without 10443 // truncation. 10444 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10445 EnumDecl *ED = EnumTy->getDecl(); 10446 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10447 10448 // Enum types are implicitly signed on Windows, so check if there are any 10449 // negative enumerators to see if the enum was intended to be signed or 10450 // not. 10451 bool SignedEnum = ED->getNumNegativeBits() > 0; 10452 10453 // Check for surprising sign changes when assigning enum values to a 10454 // bitfield of different signedness. If the bitfield is signed and we 10455 // have exactly the right number of bits to store this unsigned enum, 10456 // suggest changing the enum to an unsigned type. This typically happens 10457 // on Windows where unfixed enums always use an underlying type of 'int'. 10458 unsigned DiagID = 0; 10459 if (SignedEnum && !SignedBitfield) { 10460 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10461 } else if (SignedBitfield && !SignedEnum && 10462 ED->getNumPositiveBits() == FieldWidth) { 10463 DiagID = diag::warn_signed_bitfield_enum_conversion; 10464 } 10465 10466 if (DiagID) { 10467 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10468 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10469 SourceRange TypeRange = 10470 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10471 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10472 << SignedEnum << TypeRange; 10473 } 10474 10475 // Compute the required bitwidth. If the enum has negative values, we need 10476 // one more bit than the normal number of positive bits to represent the 10477 // sign bit. 10478 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10479 ED->getNumNegativeBits()) 10480 : ED->getNumPositiveBits(); 10481 10482 // Check the bitwidth. 10483 if (BitsNeeded > FieldWidth) { 10484 Expr *WidthExpr = Bitfield->getBitWidth(); 10485 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10486 << Bitfield << ED; 10487 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10488 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10489 } 10490 } 10491 10492 return false; 10493 } 10494 10495 llvm::APSInt Value = Result.Val.getInt(); 10496 10497 unsigned OriginalWidth = Value.getBitWidth(); 10498 10499 if (!Value.isSigned() || Value.isNegative()) 10500 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10501 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10502 OriginalWidth = Value.getMinSignedBits(); 10503 10504 if (OriginalWidth <= FieldWidth) 10505 return false; 10506 10507 // Compute the value which the bitfield will contain. 10508 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10509 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10510 10511 // Check whether the stored value is equal to the original value. 10512 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10513 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10514 return false; 10515 10516 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10517 // therefore don't strictly fit into a signed bitfield of width 1. 10518 if (FieldWidth == 1 && Value == 1) 10519 return false; 10520 10521 std::string PrettyValue = Value.toString(10); 10522 std::string PrettyTrunc = TruncatedValue.toString(10); 10523 10524 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10525 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10526 << Init->getSourceRange(); 10527 10528 return true; 10529 } 10530 10531 /// Analyze the given simple or compound assignment for warning-worthy 10532 /// operations. 10533 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10534 // Just recurse on the LHS. 10535 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10536 10537 // We want to recurse on the RHS as normal unless we're assigning to 10538 // a bitfield. 10539 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10540 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10541 E->getOperatorLoc())) { 10542 // Recurse, ignoring any implicit conversions on the RHS. 10543 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10544 E->getOperatorLoc()); 10545 } 10546 } 10547 10548 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10549 10550 // Diagnose implicitly sequentially-consistent atomic assignment. 10551 if (E->getLHS()->getType()->isAtomicType()) 10552 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10553 } 10554 10555 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10556 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10557 SourceLocation CContext, unsigned diag, 10558 bool pruneControlFlow = false) { 10559 if (pruneControlFlow) { 10560 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10561 S.PDiag(diag) 10562 << SourceType << T << E->getSourceRange() 10563 << SourceRange(CContext)); 10564 return; 10565 } 10566 S.Diag(E->getExprLoc(), diag) 10567 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10568 } 10569 10570 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10571 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10572 SourceLocation CContext, 10573 unsigned diag, bool pruneControlFlow = false) { 10574 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10575 } 10576 10577 /// Diagnose an implicit cast from a floating point value to an integer value. 10578 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10579 SourceLocation CContext) { 10580 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10581 const bool PruneWarnings = S.inTemplateInstantiation(); 10582 10583 Expr *InnerE = E->IgnoreParenImpCasts(); 10584 // We also want to warn on, e.g., "int i = -1.234" 10585 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10586 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10587 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10588 10589 const bool IsLiteral = 10590 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10591 10592 llvm::APFloat Value(0.0); 10593 bool IsConstant = 10594 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10595 if (!IsConstant) { 10596 return DiagnoseImpCast(S, E, T, CContext, 10597 diag::warn_impcast_float_integer, PruneWarnings); 10598 } 10599 10600 bool isExact = false; 10601 10602 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10603 T->hasUnsignedIntegerRepresentation()); 10604 llvm::APFloat::opStatus Result = Value.convertToInteger( 10605 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10606 10607 if (Result == llvm::APFloat::opOK && isExact) { 10608 if (IsLiteral) return; 10609 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10610 PruneWarnings); 10611 } 10612 10613 // Conversion of a floating-point value to a non-bool integer where the 10614 // integral part cannot be represented by the integer type is undefined. 10615 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10616 return DiagnoseImpCast( 10617 S, E, T, CContext, 10618 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10619 : diag::warn_impcast_float_to_integer_out_of_range, 10620 PruneWarnings); 10621 10622 unsigned DiagID = 0; 10623 if (IsLiteral) { 10624 // Warn on floating point literal to integer. 10625 DiagID = diag::warn_impcast_literal_float_to_integer; 10626 } else if (IntegerValue == 0) { 10627 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10628 return DiagnoseImpCast(S, E, T, CContext, 10629 diag::warn_impcast_float_integer, PruneWarnings); 10630 } 10631 // Warn on non-zero to zero conversion. 10632 DiagID = diag::warn_impcast_float_to_integer_zero; 10633 } else { 10634 if (IntegerValue.isUnsigned()) { 10635 if (!IntegerValue.isMaxValue()) { 10636 return DiagnoseImpCast(S, E, T, CContext, 10637 diag::warn_impcast_float_integer, PruneWarnings); 10638 } 10639 } else { // IntegerValue.isSigned() 10640 if (!IntegerValue.isMaxSignedValue() && 10641 !IntegerValue.isMinSignedValue()) { 10642 return DiagnoseImpCast(S, E, T, CContext, 10643 diag::warn_impcast_float_integer, PruneWarnings); 10644 } 10645 } 10646 // Warn on evaluatable floating point expression to integer conversion. 10647 DiagID = diag::warn_impcast_float_to_integer; 10648 } 10649 10650 // FIXME: Force the precision of the source value down so we don't print 10651 // digits which are usually useless (we don't really care here if we 10652 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10653 // would automatically print the shortest representation, but it's a bit 10654 // tricky to implement. 10655 SmallString<16> PrettySourceValue; 10656 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10657 precision = (precision * 59 + 195) / 196; 10658 Value.toString(PrettySourceValue, precision); 10659 10660 SmallString<16> PrettyTargetValue; 10661 if (IsBool) 10662 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10663 else 10664 IntegerValue.toString(PrettyTargetValue); 10665 10666 if (PruneWarnings) { 10667 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10668 S.PDiag(DiagID) 10669 << E->getType() << T.getUnqualifiedType() 10670 << PrettySourceValue << PrettyTargetValue 10671 << E->getSourceRange() << SourceRange(CContext)); 10672 } else { 10673 S.Diag(E->getExprLoc(), DiagID) 10674 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10675 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10676 } 10677 } 10678 10679 /// Analyze the given compound assignment for the possible losing of 10680 /// floating-point precision. 10681 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10682 assert(isa<CompoundAssignOperator>(E) && 10683 "Must be compound assignment operation"); 10684 // Recurse on the LHS and RHS in here 10685 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10686 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10687 10688 if (E->getLHS()->getType()->isAtomicType()) 10689 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10690 10691 // Now check the outermost expression 10692 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10693 const auto *RBT = cast<CompoundAssignOperator>(E) 10694 ->getComputationResultType() 10695 ->getAs<BuiltinType>(); 10696 10697 // The below checks assume source is floating point. 10698 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10699 10700 // If source is floating point but target is an integer. 10701 if (ResultBT->isInteger()) 10702 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10703 E->getExprLoc(), diag::warn_impcast_float_integer); 10704 10705 if (!ResultBT->isFloatingPoint()) 10706 return; 10707 10708 // If both source and target are floating points, warn about losing precision. 10709 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10710 QualType(ResultBT, 0), QualType(RBT, 0)); 10711 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10712 // warn about dropping FP rank. 10713 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10714 diag::warn_impcast_float_result_precision); 10715 } 10716 10717 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10718 IntRange Range) { 10719 if (!Range.Width) return "0"; 10720 10721 llvm::APSInt ValueInRange = Value; 10722 ValueInRange.setIsSigned(!Range.NonNegative); 10723 ValueInRange = ValueInRange.trunc(Range.Width); 10724 return ValueInRange.toString(10); 10725 } 10726 10727 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10728 if (!isa<ImplicitCastExpr>(Ex)) 10729 return false; 10730 10731 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10732 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10733 const Type *Source = 10734 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10735 if (Target->isDependentType()) 10736 return false; 10737 10738 const BuiltinType *FloatCandidateBT = 10739 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10740 const Type *BoolCandidateType = ToBool ? Target : Source; 10741 10742 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10743 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10744 } 10745 10746 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10747 SourceLocation CC) { 10748 unsigned NumArgs = TheCall->getNumArgs(); 10749 for (unsigned i = 0; i < NumArgs; ++i) { 10750 Expr *CurrA = TheCall->getArg(i); 10751 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10752 continue; 10753 10754 bool IsSwapped = ((i > 0) && 10755 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10756 IsSwapped |= ((i < (NumArgs - 1)) && 10757 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10758 if (IsSwapped) { 10759 // Warn on this floating-point to bool conversion. 10760 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10761 CurrA->getType(), CC, 10762 diag::warn_impcast_floating_point_to_bool); 10763 } 10764 } 10765 } 10766 10767 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10768 SourceLocation CC) { 10769 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10770 E->getExprLoc())) 10771 return; 10772 10773 // Don't warn on functions which have return type nullptr_t. 10774 if (isa<CallExpr>(E)) 10775 return; 10776 10777 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10778 const Expr::NullPointerConstantKind NullKind = 10779 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10780 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10781 return; 10782 10783 // Return if target type is a safe conversion. 10784 if (T->isAnyPointerType() || T->isBlockPointerType() || 10785 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10786 return; 10787 10788 SourceLocation Loc = E->getSourceRange().getBegin(); 10789 10790 // Venture through the macro stacks to get to the source of macro arguments. 10791 // The new location is a better location than the complete location that was 10792 // passed in. 10793 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10794 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10795 10796 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10797 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10798 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10799 Loc, S.SourceMgr, S.getLangOpts()); 10800 if (MacroName == "NULL") 10801 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10802 } 10803 10804 // Only warn if the null and context location are in the same macro expansion. 10805 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10806 return; 10807 10808 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10809 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10810 << FixItHint::CreateReplacement(Loc, 10811 S.getFixItZeroLiteralForType(T, Loc)); 10812 } 10813 10814 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10815 ObjCArrayLiteral *ArrayLiteral); 10816 10817 static void 10818 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10819 ObjCDictionaryLiteral *DictionaryLiteral); 10820 10821 /// Check a single element within a collection literal against the 10822 /// target element type. 10823 static void checkObjCCollectionLiteralElement(Sema &S, 10824 QualType TargetElementType, 10825 Expr *Element, 10826 unsigned ElementKind) { 10827 // Skip a bitcast to 'id' or qualified 'id'. 10828 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10829 if (ICE->getCastKind() == CK_BitCast && 10830 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10831 Element = ICE->getSubExpr(); 10832 } 10833 10834 QualType ElementType = Element->getType(); 10835 ExprResult ElementResult(Element); 10836 if (ElementType->getAs<ObjCObjectPointerType>() && 10837 S.CheckSingleAssignmentConstraints(TargetElementType, 10838 ElementResult, 10839 false, false) 10840 != Sema::Compatible) { 10841 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10842 << ElementType << ElementKind << TargetElementType 10843 << Element->getSourceRange(); 10844 } 10845 10846 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10847 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10848 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10849 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10850 } 10851 10852 /// Check an Objective-C array literal being converted to the given 10853 /// target type. 10854 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10855 ObjCArrayLiteral *ArrayLiteral) { 10856 if (!S.NSArrayDecl) 10857 return; 10858 10859 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10860 if (!TargetObjCPtr) 10861 return; 10862 10863 if (TargetObjCPtr->isUnspecialized() || 10864 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10865 != S.NSArrayDecl->getCanonicalDecl()) 10866 return; 10867 10868 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10869 if (TypeArgs.size() != 1) 10870 return; 10871 10872 QualType TargetElementType = TypeArgs[0]; 10873 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10874 checkObjCCollectionLiteralElement(S, TargetElementType, 10875 ArrayLiteral->getElement(I), 10876 0); 10877 } 10878 } 10879 10880 /// Check an Objective-C dictionary literal being converted to the given 10881 /// target type. 10882 static void 10883 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10884 ObjCDictionaryLiteral *DictionaryLiteral) { 10885 if (!S.NSDictionaryDecl) 10886 return; 10887 10888 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10889 if (!TargetObjCPtr) 10890 return; 10891 10892 if (TargetObjCPtr->isUnspecialized() || 10893 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10894 != S.NSDictionaryDecl->getCanonicalDecl()) 10895 return; 10896 10897 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10898 if (TypeArgs.size() != 2) 10899 return; 10900 10901 QualType TargetKeyType = TypeArgs[0]; 10902 QualType TargetObjectType = TypeArgs[1]; 10903 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10904 auto Element = DictionaryLiteral->getKeyValueElement(I); 10905 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10906 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10907 } 10908 } 10909 10910 // Helper function to filter out cases for constant width constant conversion. 10911 // Don't warn on char array initialization or for non-decimal values. 10912 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 10913 SourceLocation CC) { 10914 // If initializing from a constant, and the constant starts with '0', 10915 // then it is a binary, octal, or hexadecimal. Allow these constants 10916 // to fill all the bits, even if there is a sign change. 10917 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 10918 const char FirstLiteralCharacter = 10919 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 10920 if (FirstLiteralCharacter == '0') 10921 return false; 10922 } 10923 10924 // If the CC location points to a '{', and the type is char, then assume 10925 // assume it is an array initialization. 10926 if (CC.isValid() && T->isCharType()) { 10927 const char FirstContextCharacter = 10928 S.getSourceManager().getCharacterData(CC)[0]; 10929 if (FirstContextCharacter == '{') 10930 return false; 10931 } 10932 10933 return true; 10934 } 10935 10936 static void 10937 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 10938 bool *ICContext = nullptr) { 10939 if (E->isTypeDependent() || E->isValueDependent()) return; 10940 10941 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 10942 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 10943 if (Source == Target) return; 10944 if (Target->isDependentType()) return; 10945 10946 // If the conversion context location is invalid don't complain. We also 10947 // don't want to emit a warning if the issue occurs from the expansion of 10948 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 10949 // delay this check as long as possible. Once we detect we are in that 10950 // scenario, we just return. 10951 if (CC.isInvalid()) 10952 return; 10953 10954 if (Source->isAtomicType()) 10955 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 10956 10957 // Diagnose implicit casts to bool. 10958 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 10959 if (isa<StringLiteral>(E)) 10960 // Warn on string literal to bool. Checks for string literals in logical 10961 // and expressions, for instance, assert(0 && "error here"), are 10962 // prevented by a check in AnalyzeImplicitConversions(). 10963 return DiagnoseImpCast(S, E, T, CC, 10964 diag::warn_impcast_string_literal_to_bool); 10965 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 10966 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 10967 // This covers the literal expressions that evaluate to Objective-C 10968 // objects. 10969 return DiagnoseImpCast(S, E, T, CC, 10970 diag::warn_impcast_objective_c_literal_to_bool); 10971 } 10972 if (Source->isPointerType() || Source->canDecayToPointerType()) { 10973 // Warn on pointer to bool conversion that is always true. 10974 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 10975 SourceRange(CC)); 10976 } 10977 } 10978 10979 // Check implicit casts from Objective-C collection literals to specialized 10980 // collection types, e.g., NSArray<NSString *> *. 10981 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 10982 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 10983 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 10984 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 10985 10986 // Strip vector types. 10987 if (isa<VectorType>(Source)) { 10988 if (!isa<VectorType>(Target)) { 10989 if (S.SourceMgr.isInSystemMacro(CC)) 10990 return; 10991 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 10992 } 10993 10994 // If the vector cast is cast between two vectors of the same size, it is 10995 // a bitcast, not a conversion. 10996 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 10997 return; 10998 10999 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11000 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11001 } 11002 if (auto VecTy = dyn_cast<VectorType>(Target)) 11003 Target = VecTy->getElementType().getTypePtr(); 11004 11005 // Strip complex types. 11006 if (isa<ComplexType>(Source)) { 11007 if (!isa<ComplexType>(Target)) { 11008 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11009 return; 11010 11011 return DiagnoseImpCast(S, E, T, CC, 11012 S.getLangOpts().CPlusPlus 11013 ? diag::err_impcast_complex_scalar 11014 : diag::warn_impcast_complex_scalar); 11015 } 11016 11017 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11018 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11019 } 11020 11021 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11022 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11023 11024 // If the source is floating point... 11025 if (SourceBT && SourceBT->isFloatingPoint()) { 11026 // ...and the target is floating point... 11027 if (TargetBT && TargetBT->isFloatingPoint()) { 11028 // ...then warn if we're dropping FP rank. 11029 11030 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11031 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11032 if (Order > 0) { 11033 // Don't warn about float constants that are precisely 11034 // representable in the target type. 11035 Expr::EvalResult result; 11036 if (E->EvaluateAsRValue(result, S.Context)) { 11037 // Value might be a float, a float vector, or a float complex. 11038 if (IsSameFloatAfterCast(result.Val, 11039 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11040 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11041 return; 11042 } 11043 11044 if (S.SourceMgr.isInSystemMacro(CC)) 11045 return; 11046 11047 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11048 } 11049 // ... or possibly if we're increasing rank, too 11050 else if (Order < 0) { 11051 if (S.SourceMgr.isInSystemMacro(CC)) 11052 return; 11053 11054 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11055 } 11056 return; 11057 } 11058 11059 // If the target is integral, always warn. 11060 if (TargetBT && TargetBT->isInteger()) { 11061 if (S.SourceMgr.isInSystemMacro(CC)) 11062 return; 11063 11064 DiagnoseFloatingImpCast(S, E, T, CC); 11065 } 11066 11067 // Detect the case where a call result is converted from floating-point to 11068 // to bool, and the final argument to the call is converted from bool, to 11069 // discover this typo: 11070 // 11071 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11072 // 11073 // FIXME: This is an incredibly special case; is there some more general 11074 // way to detect this class of misplaced-parentheses bug? 11075 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11076 // Check last argument of function call to see if it is an 11077 // implicit cast from a type matching the type the result 11078 // is being cast to. 11079 CallExpr *CEx = cast<CallExpr>(E); 11080 if (unsigned NumArgs = CEx->getNumArgs()) { 11081 Expr *LastA = CEx->getArg(NumArgs - 1); 11082 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11083 if (isa<ImplicitCastExpr>(LastA) && 11084 InnerE->getType()->isBooleanType()) { 11085 // Warn on this floating-point to bool conversion 11086 DiagnoseImpCast(S, E, T, CC, 11087 diag::warn_impcast_floating_point_to_bool); 11088 } 11089 } 11090 } 11091 return; 11092 } 11093 11094 // Valid casts involving fixed point types should be accounted for here. 11095 if (Source->isFixedPointType()) { 11096 if (Target->isUnsaturatedFixedPointType()) { 11097 Expr::EvalResult Result; 11098 if (E->EvaluateAsFixedPoint(Result, S.Context, 11099 Expr::SE_AllowSideEffects)) { 11100 APFixedPoint Value = Result.Val.getFixedPoint(); 11101 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11102 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11103 if (Value > MaxVal || Value < MinVal) { 11104 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11105 S.PDiag(diag::warn_impcast_fixed_point_range) 11106 << Value.toString() << T 11107 << E->getSourceRange() 11108 << clang::SourceRange(CC)); 11109 return; 11110 } 11111 } 11112 } else if (Target->isIntegerType()) { 11113 Expr::EvalResult Result; 11114 if (E->EvaluateAsFixedPoint(Result, S.Context, 11115 Expr::SE_AllowSideEffects)) { 11116 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11117 11118 bool Overflowed; 11119 llvm::APSInt IntResult = FXResult.convertToInt( 11120 S.Context.getIntWidth(T), 11121 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11122 11123 if (Overflowed) { 11124 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11125 S.PDiag(diag::warn_impcast_fixed_point_range) 11126 << FXResult.toString() << T 11127 << E->getSourceRange() 11128 << clang::SourceRange(CC)); 11129 return; 11130 } 11131 } 11132 } 11133 } else if (Target->isUnsaturatedFixedPointType()) { 11134 if (Source->isIntegerType()) { 11135 Expr::EvalResult Result; 11136 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11137 llvm::APSInt Value = Result.Val.getInt(); 11138 11139 bool Overflowed; 11140 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11141 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11142 11143 if (Overflowed) { 11144 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11145 S.PDiag(diag::warn_impcast_fixed_point_range) 11146 << Value.toString(/*radix=*/10) << T 11147 << E->getSourceRange() 11148 << clang::SourceRange(CC)); 11149 return; 11150 } 11151 } 11152 } 11153 } 11154 11155 DiagnoseNullConversion(S, E, T, CC); 11156 11157 S.DiscardMisalignedMemberAddress(Target, E); 11158 11159 if (!Source->isIntegerType() || !Target->isIntegerType()) 11160 return; 11161 11162 // TODO: remove this early return once the false positives for constant->bool 11163 // in templates, macros, etc, are reduced or removed. 11164 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11165 return; 11166 11167 IntRange SourceRange = GetExprRange(S.Context, E); 11168 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11169 11170 if (SourceRange.Width > TargetRange.Width) { 11171 // If the source is a constant, use a default-on diagnostic. 11172 // TODO: this should happen for bitfield stores, too. 11173 Expr::EvalResult Result; 11174 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11175 llvm::APSInt Value(32); 11176 Value = Result.Val.getInt(); 11177 11178 if (S.SourceMgr.isInSystemMacro(CC)) 11179 return; 11180 11181 std::string PrettySourceValue = Value.toString(10); 11182 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11183 11184 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11185 S.PDiag(diag::warn_impcast_integer_precision_constant) 11186 << PrettySourceValue << PrettyTargetValue 11187 << E->getType() << T << E->getSourceRange() 11188 << clang::SourceRange(CC)); 11189 return; 11190 } 11191 11192 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11193 if (S.SourceMgr.isInSystemMacro(CC)) 11194 return; 11195 11196 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11197 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11198 /* pruneControlFlow */ true); 11199 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11200 } 11201 11202 if (TargetRange.Width > SourceRange.Width) { 11203 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11204 if (UO->getOpcode() == UO_Minus) 11205 if (Source->isUnsignedIntegerType()) { 11206 if (Target->isUnsignedIntegerType()) 11207 return DiagnoseImpCast(S, E, T, CC, 11208 diag::warn_impcast_high_order_zero_bits); 11209 if (Target->isSignedIntegerType()) 11210 return DiagnoseImpCast(S, E, T, CC, 11211 diag::warn_impcast_nonnegative_result); 11212 } 11213 } 11214 11215 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11216 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11217 // Warn when doing a signed to signed conversion, warn if the positive 11218 // source value is exactly the width of the target type, which will 11219 // cause a negative value to be stored. 11220 11221 Expr::EvalResult Result; 11222 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11223 !S.SourceMgr.isInSystemMacro(CC)) { 11224 llvm::APSInt Value = Result.Val.getInt(); 11225 if (isSameWidthConstantConversion(S, E, T, CC)) { 11226 std::string PrettySourceValue = Value.toString(10); 11227 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11228 11229 S.DiagRuntimeBehavior( 11230 E->getExprLoc(), E, 11231 S.PDiag(diag::warn_impcast_integer_precision_constant) 11232 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11233 << E->getSourceRange() << clang::SourceRange(CC)); 11234 return; 11235 } 11236 } 11237 11238 // Fall through for non-constants to give a sign conversion warning. 11239 } 11240 11241 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11242 (!TargetRange.NonNegative && SourceRange.NonNegative && 11243 SourceRange.Width == TargetRange.Width)) { 11244 if (S.SourceMgr.isInSystemMacro(CC)) 11245 return; 11246 11247 unsigned DiagID = diag::warn_impcast_integer_sign; 11248 11249 // Traditionally, gcc has warned about this under -Wsign-compare. 11250 // We also want to warn about it in -Wconversion. 11251 // So if -Wconversion is off, use a completely identical diagnostic 11252 // in the sign-compare group. 11253 // The conditional-checking code will 11254 if (ICContext) { 11255 DiagID = diag::warn_impcast_integer_sign_conditional; 11256 *ICContext = true; 11257 } 11258 11259 return DiagnoseImpCast(S, E, T, CC, DiagID); 11260 } 11261 11262 // Diagnose conversions between different enumeration types. 11263 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11264 // type, to give us better diagnostics. 11265 QualType SourceType = E->getType(); 11266 if (!S.getLangOpts().CPlusPlus) { 11267 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11268 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11269 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11270 SourceType = S.Context.getTypeDeclType(Enum); 11271 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11272 } 11273 } 11274 11275 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11276 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11277 if (SourceEnum->getDecl()->hasNameForLinkage() && 11278 TargetEnum->getDecl()->hasNameForLinkage() && 11279 SourceEnum != TargetEnum) { 11280 if (S.SourceMgr.isInSystemMacro(CC)) 11281 return; 11282 11283 return DiagnoseImpCast(S, E, SourceType, T, CC, 11284 diag::warn_impcast_different_enum_types); 11285 } 11286 } 11287 11288 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11289 SourceLocation CC, QualType T); 11290 11291 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11292 SourceLocation CC, bool &ICContext) { 11293 E = E->IgnoreParenImpCasts(); 11294 11295 if (isa<ConditionalOperator>(E)) 11296 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11297 11298 AnalyzeImplicitConversions(S, E, CC); 11299 if (E->getType() != T) 11300 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11301 } 11302 11303 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11304 SourceLocation CC, QualType T) { 11305 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11306 11307 bool Suspicious = false; 11308 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11309 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11310 11311 // If -Wconversion would have warned about either of the candidates 11312 // for a signedness conversion to the context type... 11313 if (!Suspicious) return; 11314 11315 // ...but it's currently ignored... 11316 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11317 return; 11318 11319 // ...then check whether it would have warned about either of the 11320 // candidates for a signedness conversion to the condition type. 11321 if (E->getType() == T) return; 11322 11323 Suspicious = false; 11324 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11325 E->getType(), CC, &Suspicious); 11326 if (!Suspicious) 11327 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11328 E->getType(), CC, &Suspicious); 11329 } 11330 11331 /// Check conversion of given expression to boolean. 11332 /// Input argument E is a logical expression. 11333 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11334 if (S.getLangOpts().Bool) 11335 return; 11336 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11337 return; 11338 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11339 } 11340 11341 /// AnalyzeImplicitConversions - Find and report any interesting 11342 /// implicit conversions in the given expression. There are a couple 11343 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11344 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11345 SourceLocation CC) { 11346 QualType T = OrigE->getType(); 11347 Expr *E = OrigE->IgnoreParenImpCasts(); 11348 11349 if (E->isTypeDependent() || E->isValueDependent()) 11350 return; 11351 11352 // For conditional operators, we analyze the arguments as if they 11353 // were being fed directly into the output. 11354 if (isa<ConditionalOperator>(E)) { 11355 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11356 CheckConditionalOperator(S, CO, CC, T); 11357 return; 11358 } 11359 11360 // Check implicit argument conversions for function calls. 11361 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11362 CheckImplicitArgumentConversions(S, Call, CC); 11363 11364 // Go ahead and check any implicit conversions we might have skipped. 11365 // The non-canonical typecheck is just an optimization; 11366 // CheckImplicitConversion will filter out dead implicit conversions. 11367 if (E->getType() != T) 11368 CheckImplicitConversion(S, E, T, CC); 11369 11370 // Now continue drilling into this expression. 11371 11372 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11373 // The bound subexpressions in a PseudoObjectExpr are not reachable 11374 // as transitive children. 11375 // FIXME: Use a more uniform representation for this. 11376 for (auto *SE : POE->semantics()) 11377 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11378 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11379 } 11380 11381 // Skip past explicit casts. 11382 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11383 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11384 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11385 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11386 return AnalyzeImplicitConversions(S, E, CC); 11387 } 11388 11389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11390 // Do a somewhat different check with comparison operators. 11391 if (BO->isComparisonOp()) 11392 return AnalyzeComparison(S, BO); 11393 11394 // And with simple assignments. 11395 if (BO->getOpcode() == BO_Assign) 11396 return AnalyzeAssignment(S, BO); 11397 // And with compound assignments. 11398 if (BO->isAssignmentOp()) 11399 return AnalyzeCompoundAssignment(S, BO); 11400 } 11401 11402 // These break the otherwise-useful invariant below. Fortunately, 11403 // we don't really need to recurse into them, because any internal 11404 // expressions should have been analyzed already when they were 11405 // built into statements. 11406 if (isa<StmtExpr>(E)) return; 11407 11408 // Don't descend into unevaluated contexts. 11409 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11410 11411 // Now just recurse over the expression's children. 11412 CC = E->getExprLoc(); 11413 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11414 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11415 for (Stmt *SubStmt : E->children()) { 11416 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11417 if (!ChildExpr) 11418 continue; 11419 11420 if (IsLogicalAndOperator && 11421 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11422 // Ignore checking string literals that are in logical and operators. 11423 // This is a common pattern for asserts. 11424 continue; 11425 AnalyzeImplicitConversions(S, ChildExpr, CC); 11426 } 11427 11428 if (BO && BO->isLogicalOp()) { 11429 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11430 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11431 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11432 11433 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11434 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11435 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11436 } 11437 11438 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11439 if (U->getOpcode() == UO_LNot) { 11440 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11441 } else if (U->getOpcode() != UO_AddrOf) { 11442 if (U->getSubExpr()->getType()->isAtomicType()) 11443 S.Diag(U->getSubExpr()->getBeginLoc(), 11444 diag::warn_atomic_implicit_seq_cst); 11445 } 11446 } 11447 } 11448 11449 /// Diagnose integer type and any valid implicit conversion to it. 11450 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11451 // Taking into account implicit conversions, 11452 // allow any integer. 11453 if (!E->getType()->isIntegerType()) { 11454 S.Diag(E->getBeginLoc(), 11455 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11456 return true; 11457 } 11458 // Potentially emit standard warnings for implicit conversions if enabled 11459 // using -Wconversion. 11460 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11461 return false; 11462 } 11463 11464 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11465 // Returns true when emitting a warning about taking the address of a reference. 11466 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11467 const PartialDiagnostic &PD) { 11468 E = E->IgnoreParenImpCasts(); 11469 11470 const FunctionDecl *FD = nullptr; 11471 11472 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11473 if (!DRE->getDecl()->getType()->isReferenceType()) 11474 return false; 11475 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11476 if (!M->getMemberDecl()->getType()->isReferenceType()) 11477 return false; 11478 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11479 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11480 return false; 11481 FD = Call->getDirectCallee(); 11482 } else { 11483 return false; 11484 } 11485 11486 SemaRef.Diag(E->getExprLoc(), PD); 11487 11488 // If possible, point to location of function. 11489 if (FD) { 11490 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11491 } 11492 11493 return true; 11494 } 11495 11496 // Returns true if the SourceLocation is expanded from any macro body. 11497 // Returns false if the SourceLocation is invalid, is from not in a macro 11498 // expansion, or is from expanded from a top-level macro argument. 11499 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11500 if (Loc.isInvalid()) 11501 return false; 11502 11503 while (Loc.isMacroID()) { 11504 if (SM.isMacroBodyExpansion(Loc)) 11505 return true; 11506 Loc = SM.getImmediateMacroCallerLoc(Loc); 11507 } 11508 11509 return false; 11510 } 11511 11512 /// Diagnose pointers that are always non-null. 11513 /// \param E the expression containing the pointer 11514 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11515 /// compared to a null pointer 11516 /// \param IsEqual True when the comparison is equal to a null pointer 11517 /// \param Range Extra SourceRange to highlight in the diagnostic 11518 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11519 Expr::NullPointerConstantKind NullKind, 11520 bool IsEqual, SourceRange Range) { 11521 if (!E) 11522 return; 11523 11524 // Don't warn inside macros. 11525 if (E->getExprLoc().isMacroID()) { 11526 const SourceManager &SM = getSourceManager(); 11527 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11528 IsInAnyMacroBody(SM, Range.getBegin())) 11529 return; 11530 } 11531 E = E->IgnoreImpCasts(); 11532 11533 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11534 11535 if (isa<CXXThisExpr>(E)) { 11536 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11537 : diag::warn_this_bool_conversion; 11538 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11539 return; 11540 } 11541 11542 bool IsAddressOf = false; 11543 11544 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11545 if (UO->getOpcode() != UO_AddrOf) 11546 return; 11547 IsAddressOf = true; 11548 E = UO->getSubExpr(); 11549 } 11550 11551 if (IsAddressOf) { 11552 unsigned DiagID = IsCompare 11553 ? diag::warn_address_of_reference_null_compare 11554 : diag::warn_address_of_reference_bool_conversion; 11555 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11556 << IsEqual; 11557 if (CheckForReference(*this, E, PD)) { 11558 return; 11559 } 11560 } 11561 11562 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11563 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11564 std::string Str; 11565 llvm::raw_string_ostream S(Str); 11566 E->printPretty(S, nullptr, getPrintingPolicy()); 11567 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11568 : diag::warn_cast_nonnull_to_bool; 11569 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11570 << E->getSourceRange() << Range << IsEqual; 11571 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11572 }; 11573 11574 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11575 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11576 if (auto *Callee = Call->getDirectCallee()) { 11577 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11578 ComplainAboutNonnullParamOrCall(A); 11579 return; 11580 } 11581 } 11582 } 11583 11584 // Expect to find a single Decl. Skip anything more complicated. 11585 ValueDecl *D = nullptr; 11586 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11587 D = R->getDecl(); 11588 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11589 D = M->getMemberDecl(); 11590 } 11591 11592 // Weak Decls can be null. 11593 if (!D || D->isWeak()) 11594 return; 11595 11596 // Check for parameter decl with nonnull attribute 11597 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11598 if (getCurFunction() && 11599 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11600 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11601 ComplainAboutNonnullParamOrCall(A); 11602 return; 11603 } 11604 11605 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11606 // Skip function template not specialized yet. 11607 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11608 return; 11609 auto ParamIter = llvm::find(FD->parameters(), PV); 11610 assert(ParamIter != FD->param_end()); 11611 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11612 11613 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11614 if (!NonNull->args_size()) { 11615 ComplainAboutNonnullParamOrCall(NonNull); 11616 return; 11617 } 11618 11619 for (const ParamIdx &ArgNo : NonNull->args()) { 11620 if (ArgNo.getASTIndex() == ParamNo) { 11621 ComplainAboutNonnullParamOrCall(NonNull); 11622 return; 11623 } 11624 } 11625 } 11626 } 11627 } 11628 } 11629 11630 QualType T = D->getType(); 11631 const bool IsArray = T->isArrayType(); 11632 const bool IsFunction = T->isFunctionType(); 11633 11634 // Address of function is used to silence the function warning. 11635 if (IsAddressOf && IsFunction) { 11636 return; 11637 } 11638 11639 // Found nothing. 11640 if (!IsAddressOf && !IsFunction && !IsArray) 11641 return; 11642 11643 // Pretty print the expression for the diagnostic. 11644 std::string Str; 11645 llvm::raw_string_ostream S(Str); 11646 E->printPretty(S, nullptr, getPrintingPolicy()); 11647 11648 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11649 : diag::warn_impcast_pointer_to_bool; 11650 enum { 11651 AddressOf, 11652 FunctionPointer, 11653 ArrayPointer 11654 } DiagType; 11655 if (IsAddressOf) 11656 DiagType = AddressOf; 11657 else if (IsFunction) 11658 DiagType = FunctionPointer; 11659 else if (IsArray) 11660 DiagType = ArrayPointer; 11661 else 11662 llvm_unreachable("Could not determine diagnostic."); 11663 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11664 << Range << IsEqual; 11665 11666 if (!IsFunction) 11667 return; 11668 11669 // Suggest '&' to silence the function warning. 11670 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11671 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11672 11673 // Check to see if '()' fixit should be emitted. 11674 QualType ReturnType; 11675 UnresolvedSet<4> NonTemplateOverloads; 11676 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11677 if (ReturnType.isNull()) 11678 return; 11679 11680 if (IsCompare) { 11681 // There are two cases here. If there is null constant, the only suggest 11682 // for a pointer return type. If the null is 0, then suggest if the return 11683 // type is a pointer or an integer type. 11684 if (!ReturnType->isPointerType()) { 11685 if (NullKind == Expr::NPCK_ZeroExpression || 11686 NullKind == Expr::NPCK_ZeroLiteral) { 11687 if (!ReturnType->isIntegerType()) 11688 return; 11689 } else { 11690 return; 11691 } 11692 } 11693 } else { // !IsCompare 11694 // For function to bool, only suggest if the function pointer has bool 11695 // return type. 11696 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11697 return; 11698 } 11699 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11700 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11701 } 11702 11703 /// Diagnoses "dangerous" implicit conversions within the given 11704 /// expression (which is a full expression). Implements -Wconversion 11705 /// and -Wsign-compare. 11706 /// 11707 /// \param CC the "context" location of the implicit conversion, i.e. 11708 /// the most location of the syntactic entity requiring the implicit 11709 /// conversion 11710 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11711 // Don't diagnose in unevaluated contexts. 11712 if (isUnevaluatedContext()) 11713 return; 11714 11715 // Don't diagnose for value- or type-dependent expressions. 11716 if (E->isTypeDependent() || E->isValueDependent()) 11717 return; 11718 11719 // Check for array bounds violations in cases where the check isn't triggered 11720 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11721 // ArraySubscriptExpr is on the RHS of a variable initialization. 11722 CheckArrayAccess(E); 11723 11724 // This is not the right CC for (e.g.) a variable initialization. 11725 AnalyzeImplicitConversions(*this, E, CC); 11726 } 11727 11728 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11729 /// Input argument E is a logical expression. 11730 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11731 ::CheckBoolLikeConversion(*this, E, CC); 11732 } 11733 11734 /// Diagnose when expression is an integer constant expression and its evaluation 11735 /// results in integer overflow 11736 void Sema::CheckForIntOverflow (Expr *E) { 11737 // Use a work list to deal with nested struct initializers. 11738 SmallVector<Expr *, 2> Exprs(1, E); 11739 11740 do { 11741 Expr *OriginalE = Exprs.pop_back_val(); 11742 Expr *E = OriginalE->IgnoreParenCasts(); 11743 11744 if (isa<BinaryOperator>(E)) { 11745 E->EvaluateForOverflow(Context); 11746 continue; 11747 } 11748 11749 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11750 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11751 else if (isa<ObjCBoxedExpr>(OriginalE)) 11752 E->EvaluateForOverflow(Context); 11753 else if (auto Call = dyn_cast<CallExpr>(E)) 11754 Exprs.append(Call->arg_begin(), Call->arg_end()); 11755 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11756 Exprs.append(Message->arg_begin(), Message->arg_end()); 11757 } while (!Exprs.empty()); 11758 } 11759 11760 namespace { 11761 11762 /// Visitor for expressions which looks for unsequenced operations on the 11763 /// same object. 11764 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 11765 using Base = EvaluatedExprVisitor<SequenceChecker>; 11766 11767 /// A tree of sequenced regions within an expression. Two regions are 11768 /// unsequenced if one is an ancestor or a descendent of the other. When we 11769 /// finish processing an expression with sequencing, such as a comma 11770 /// expression, we fold its tree nodes into its parent, since they are 11771 /// unsequenced with respect to nodes we will visit later. 11772 class SequenceTree { 11773 struct Value { 11774 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 11775 unsigned Parent : 31; 11776 unsigned Merged : 1; 11777 }; 11778 SmallVector<Value, 8> Values; 11779 11780 public: 11781 /// A region within an expression which may be sequenced with respect 11782 /// to some other region. 11783 class Seq { 11784 friend class SequenceTree; 11785 11786 unsigned Index; 11787 11788 explicit Seq(unsigned N) : Index(N) {} 11789 11790 public: 11791 Seq() : Index(0) {} 11792 }; 11793 11794 SequenceTree() { Values.push_back(Value(0)); } 11795 Seq root() const { return Seq(0); } 11796 11797 /// Create a new sequence of operations, which is an unsequenced 11798 /// subset of \p Parent. This sequence of operations is sequenced with 11799 /// respect to other children of \p Parent. 11800 Seq allocate(Seq Parent) { 11801 Values.push_back(Value(Parent.Index)); 11802 return Seq(Values.size() - 1); 11803 } 11804 11805 /// Merge a sequence of operations into its parent. 11806 void merge(Seq S) { 11807 Values[S.Index].Merged = true; 11808 } 11809 11810 /// Determine whether two operations are unsequenced. This operation 11811 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 11812 /// should have been merged into its parent as appropriate. 11813 bool isUnsequenced(Seq Cur, Seq Old) { 11814 unsigned C = representative(Cur.Index); 11815 unsigned Target = representative(Old.Index); 11816 while (C >= Target) { 11817 if (C == Target) 11818 return true; 11819 C = Values[C].Parent; 11820 } 11821 return false; 11822 } 11823 11824 private: 11825 /// Pick a representative for a sequence. 11826 unsigned representative(unsigned K) { 11827 if (Values[K].Merged) 11828 // Perform path compression as we go. 11829 return Values[K].Parent = representative(Values[K].Parent); 11830 return K; 11831 } 11832 }; 11833 11834 /// An object for which we can track unsequenced uses. 11835 using Object = NamedDecl *; 11836 11837 /// Different flavors of object usage which we track. We only track the 11838 /// least-sequenced usage of each kind. 11839 enum UsageKind { 11840 /// A read of an object. Multiple unsequenced reads are OK. 11841 UK_Use, 11842 11843 /// A modification of an object which is sequenced before the value 11844 /// computation of the expression, such as ++n in C++. 11845 UK_ModAsValue, 11846 11847 /// A modification of an object which is not sequenced before the value 11848 /// computation of the expression, such as n++. 11849 UK_ModAsSideEffect, 11850 11851 UK_Count = UK_ModAsSideEffect + 1 11852 }; 11853 11854 struct Usage { 11855 Expr *Use; 11856 SequenceTree::Seq Seq; 11857 11858 Usage() : Use(nullptr), Seq() {} 11859 }; 11860 11861 struct UsageInfo { 11862 Usage Uses[UK_Count]; 11863 11864 /// Have we issued a diagnostic for this variable already? 11865 bool Diagnosed; 11866 11867 UsageInfo() : Uses(), Diagnosed(false) {} 11868 }; 11869 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 11870 11871 Sema &SemaRef; 11872 11873 /// Sequenced regions within the expression. 11874 SequenceTree Tree; 11875 11876 /// Declaration modifications and references which we have seen. 11877 UsageInfoMap UsageMap; 11878 11879 /// The region we are currently within. 11880 SequenceTree::Seq Region; 11881 11882 /// Filled in with declarations which were modified as a side-effect 11883 /// (that is, post-increment operations). 11884 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 11885 11886 /// Expressions to check later. We defer checking these to reduce 11887 /// stack usage. 11888 SmallVectorImpl<Expr *> &WorkList; 11889 11890 /// RAII object wrapping the visitation of a sequenced subexpression of an 11891 /// expression. At the end of this process, the side-effects of the evaluation 11892 /// become sequenced with respect to the value computation of the result, so 11893 /// we downgrade any UK_ModAsSideEffect within the evaluation to 11894 /// UK_ModAsValue. 11895 struct SequencedSubexpression { 11896 SequencedSubexpression(SequenceChecker &Self) 11897 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 11898 Self.ModAsSideEffect = &ModAsSideEffect; 11899 } 11900 11901 ~SequencedSubexpression() { 11902 for (auto &M : llvm::reverse(ModAsSideEffect)) { 11903 UsageInfo &U = Self.UsageMap[M.first]; 11904 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 11905 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 11906 SideEffectUsage = M.second; 11907 } 11908 Self.ModAsSideEffect = OldModAsSideEffect; 11909 } 11910 11911 SequenceChecker &Self; 11912 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 11913 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 11914 }; 11915 11916 /// RAII object wrapping the visitation of a subexpression which we might 11917 /// choose to evaluate as a constant. If any subexpression is evaluated and 11918 /// found to be non-constant, this allows us to suppress the evaluation of 11919 /// the outer expression. 11920 class EvaluationTracker { 11921 public: 11922 EvaluationTracker(SequenceChecker &Self) 11923 : Self(Self), Prev(Self.EvalTracker) { 11924 Self.EvalTracker = this; 11925 } 11926 11927 ~EvaluationTracker() { 11928 Self.EvalTracker = Prev; 11929 if (Prev) 11930 Prev->EvalOK &= EvalOK; 11931 } 11932 11933 bool evaluate(const Expr *E, bool &Result) { 11934 if (!EvalOK || E->isValueDependent()) 11935 return false; 11936 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context); 11937 return EvalOK; 11938 } 11939 11940 private: 11941 SequenceChecker &Self; 11942 EvaluationTracker *Prev; 11943 bool EvalOK = true; 11944 } *EvalTracker = nullptr; 11945 11946 /// Find the object which is produced by the specified expression, 11947 /// if any. 11948 Object getObject(Expr *E, bool Mod) const { 11949 E = E->IgnoreParenCasts(); 11950 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11951 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 11952 return getObject(UO->getSubExpr(), Mod); 11953 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11954 if (BO->getOpcode() == BO_Comma) 11955 return getObject(BO->getRHS(), Mod); 11956 if (Mod && BO->isAssignmentOp()) 11957 return getObject(BO->getLHS(), Mod); 11958 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11959 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 11960 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 11961 return ME->getMemberDecl(); 11962 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11963 // FIXME: If this is a reference, map through to its value. 11964 return DRE->getDecl(); 11965 return nullptr; 11966 } 11967 11968 /// Note that an object was modified or used by an expression. 11969 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 11970 Usage &U = UI.Uses[UK]; 11971 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 11972 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 11973 ModAsSideEffect->push_back(std::make_pair(O, U)); 11974 U.Use = Ref; 11975 U.Seq = Region; 11976 } 11977 } 11978 11979 /// Check whether a modification or use conflicts with a prior usage. 11980 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 11981 bool IsModMod) { 11982 if (UI.Diagnosed) 11983 return; 11984 11985 const Usage &U = UI.Uses[OtherKind]; 11986 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 11987 return; 11988 11989 Expr *Mod = U.Use; 11990 Expr *ModOrUse = Ref; 11991 if (OtherKind == UK_Use) 11992 std::swap(Mod, ModOrUse); 11993 11994 SemaRef.Diag(Mod->getExprLoc(), 11995 IsModMod ? diag::warn_unsequenced_mod_mod 11996 : diag::warn_unsequenced_mod_use) 11997 << O << SourceRange(ModOrUse->getExprLoc()); 11998 UI.Diagnosed = true; 11999 } 12000 12001 void notePreUse(Object O, Expr *Use) { 12002 UsageInfo &U = UsageMap[O]; 12003 // Uses conflict with other modifications. 12004 checkUsage(O, U, Use, UK_ModAsValue, false); 12005 } 12006 12007 void notePostUse(Object O, Expr *Use) { 12008 UsageInfo &U = UsageMap[O]; 12009 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 12010 addUsage(U, O, Use, UK_Use); 12011 } 12012 12013 void notePreMod(Object O, Expr *Mod) { 12014 UsageInfo &U = UsageMap[O]; 12015 // Modifications conflict with other modifications and with uses. 12016 checkUsage(O, U, Mod, UK_ModAsValue, true); 12017 checkUsage(O, U, Mod, UK_Use, false); 12018 } 12019 12020 void notePostMod(Object O, Expr *Use, UsageKind UK) { 12021 UsageInfo &U = UsageMap[O]; 12022 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 12023 addUsage(U, O, Use, UK); 12024 } 12025 12026 public: 12027 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 12028 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12029 Visit(E); 12030 } 12031 12032 void VisitStmt(Stmt *S) { 12033 // Skip all statements which aren't expressions for now. 12034 } 12035 12036 void VisitExpr(Expr *E) { 12037 // By default, just recurse to evaluated subexpressions. 12038 Base::VisitStmt(E); 12039 } 12040 12041 void VisitCastExpr(CastExpr *E) { 12042 Object O = Object(); 12043 if (E->getCastKind() == CK_LValueToRValue) 12044 O = getObject(E->getSubExpr(), false); 12045 12046 if (O) 12047 notePreUse(O, E); 12048 VisitExpr(E); 12049 if (O) 12050 notePostUse(O, E); 12051 } 12052 12053 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) { 12054 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12055 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12056 SequenceTree::Seq OldRegion = Region; 12057 12058 { 12059 SequencedSubexpression SeqBefore(*this); 12060 Region = BeforeRegion; 12061 Visit(SequencedBefore); 12062 } 12063 12064 Region = AfterRegion; 12065 Visit(SequencedAfter); 12066 12067 Region = OldRegion; 12068 12069 Tree.merge(BeforeRegion); 12070 Tree.merge(AfterRegion); 12071 } 12072 12073 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) { 12074 // C++17 [expr.sub]p1: 12075 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12076 // expression E1 is sequenced before the expression E2. 12077 if (SemaRef.getLangOpts().CPlusPlus17) 12078 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12079 else 12080 Base::VisitStmt(ASE); 12081 } 12082 12083 void VisitBinComma(BinaryOperator *BO) { 12084 // C++11 [expr.comma]p1: 12085 // Every value computation and side effect associated with the left 12086 // expression is sequenced before every value computation and side 12087 // effect associated with the right expression. 12088 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12089 } 12090 12091 void VisitBinAssign(BinaryOperator *BO) { 12092 // The modification is sequenced after the value computation of the LHS 12093 // and RHS, so check it before inspecting the operands and update the 12094 // map afterwards. 12095 Object O = getObject(BO->getLHS(), true); 12096 if (!O) 12097 return VisitExpr(BO); 12098 12099 notePreMod(O, BO); 12100 12101 // C++11 [expr.ass]p7: 12102 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 12103 // only once. 12104 // 12105 // Therefore, for a compound assignment operator, O is considered used 12106 // everywhere except within the evaluation of E1 itself. 12107 if (isa<CompoundAssignOperator>(BO)) 12108 notePreUse(O, BO); 12109 12110 Visit(BO->getLHS()); 12111 12112 if (isa<CompoundAssignOperator>(BO)) 12113 notePostUse(O, BO); 12114 12115 Visit(BO->getRHS()); 12116 12117 // C++11 [expr.ass]p1: 12118 // the assignment is sequenced [...] before the value computation of the 12119 // assignment expression. 12120 // C11 6.5.16/3 has no such rule. 12121 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12122 : UK_ModAsSideEffect); 12123 } 12124 12125 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 12126 VisitBinAssign(CAO); 12127 } 12128 12129 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12130 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12131 void VisitUnaryPreIncDec(UnaryOperator *UO) { 12132 Object O = getObject(UO->getSubExpr(), true); 12133 if (!O) 12134 return VisitExpr(UO); 12135 12136 notePreMod(O, UO); 12137 Visit(UO->getSubExpr()); 12138 // C++11 [expr.pre.incr]p1: 12139 // the expression ++x is equivalent to x+=1 12140 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12141 : UK_ModAsSideEffect); 12142 } 12143 12144 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12145 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12146 void VisitUnaryPostIncDec(UnaryOperator *UO) { 12147 Object O = getObject(UO->getSubExpr(), true); 12148 if (!O) 12149 return VisitExpr(UO); 12150 12151 notePreMod(O, UO); 12152 Visit(UO->getSubExpr()); 12153 notePostMod(O, UO, UK_ModAsSideEffect); 12154 } 12155 12156 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 12157 void VisitBinLOr(BinaryOperator *BO) { 12158 // The side-effects of the LHS of an '&&' are sequenced before the 12159 // value computation of the RHS, and hence before the value computation 12160 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 12161 // as if they were unconditionally sequenced. 12162 EvaluationTracker Eval(*this); 12163 { 12164 SequencedSubexpression Sequenced(*this); 12165 Visit(BO->getLHS()); 12166 } 12167 12168 bool Result; 12169 if (Eval.evaluate(BO->getLHS(), Result)) { 12170 if (!Result) 12171 Visit(BO->getRHS()); 12172 } else { 12173 // Check for unsequenced operations in the RHS, treating it as an 12174 // entirely separate evaluation. 12175 // 12176 // FIXME: If there are operations in the RHS which are unsequenced 12177 // with respect to operations outside the RHS, and those operations 12178 // are unconditionally evaluated, diagnose them. 12179 WorkList.push_back(BO->getRHS()); 12180 } 12181 } 12182 void VisitBinLAnd(BinaryOperator *BO) { 12183 EvaluationTracker Eval(*this); 12184 { 12185 SequencedSubexpression Sequenced(*this); 12186 Visit(BO->getLHS()); 12187 } 12188 12189 bool Result; 12190 if (Eval.evaluate(BO->getLHS(), Result)) { 12191 if (Result) 12192 Visit(BO->getRHS()); 12193 } else { 12194 WorkList.push_back(BO->getRHS()); 12195 } 12196 } 12197 12198 // Only visit the condition, unless we can be sure which subexpression will 12199 // be chosen. 12200 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 12201 EvaluationTracker Eval(*this); 12202 { 12203 SequencedSubexpression Sequenced(*this); 12204 Visit(CO->getCond()); 12205 } 12206 12207 bool Result; 12208 if (Eval.evaluate(CO->getCond(), Result)) 12209 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 12210 else { 12211 WorkList.push_back(CO->getTrueExpr()); 12212 WorkList.push_back(CO->getFalseExpr()); 12213 } 12214 } 12215 12216 void VisitCallExpr(CallExpr *CE) { 12217 // C++11 [intro.execution]p15: 12218 // When calling a function [...], every value computation and side effect 12219 // associated with any argument expression, or with the postfix expression 12220 // designating the called function, is sequenced before execution of every 12221 // expression or statement in the body of the function [and thus before 12222 // the value computation of its result]. 12223 SequencedSubexpression Sequenced(*this); 12224 Base::VisitCallExpr(CE); 12225 12226 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12227 } 12228 12229 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 12230 // This is a call, so all subexpressions are sequenced before the result. 12231 SequencedSubexpression Sequenced(*this); 12232 12233 if (!CCE->isListInitialization()) 12234 return VisitExpr(CCE); 12235 12236 // In C++11, list initializations are sequenced. 12237 SmallVector<SequenceTree::Seq, 32> Elts; 12238 SequenceTree::Seq Parent = Region; 12239 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12240 E = CCE->arg_end(); 12241 I != E; ++I) { 12242 Region = Tree.allocate(Parent); 12243 Elts.push_back(Region); 12244 Visit(*I); 12245 } 12246 12247 // Forget that the initializers are sequenced. 12248 Region = Parent; 12249 for (unsigned I = 0; I < Elts.size(); ++I) 12250 Tree.merge(Elts[I]); 12251 } 12252 12253 void VisitInitListExpr(InitListExpr *ILE) { 12254 if (!SemaRef.getLangOpts().CPlusPlus11) 12255 return VisitExpr(ILE); 12256 12257 // In C++11, list initializations are sequenced. 12258 SmallVector<SequenceTree::Seq, 32> Elts; 12259 SequenceTree::Seq Parent = Region; 12260 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12261 Expr *E = ILE->getInit(I); 12262 if (!E) continue; 12263 Region = Tree.allocate(Parent); 12264 Elts.push_back(Region); 12265 Visit(E); 12266 } 12267 12268 // Forget that the initializers are sequenced. 12269 Region = Parent; 12270 for (unsigned I = 0; I < Elts.size(); ++I) 12271 Tree.merge(Elts[I]); 12272 } 12273 }; 12274 12275 } // namespace 12276 12277 void Sema::CheckUnsequencedOperations(Expr *E) { 12278 SmallVector<Expr *, 8> WorkList; 12279 WorkList.push_back(E); 12280 while (!WorkList.empty()) { 12281 Expr *Item = WorkList.pop_back_val(); 12282 SequenceChecker(*this, Item, WorkList); 12283 } 12284 } 12285 12286 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12287 bool IsConstexpr) { 12288 CheckImplicitConversions(E, CheckLoc); 12289 if (!E->isInstantiationDependent()) 12290 CheckUnsequencedOperations(E); 12291 if (!IsConstexpr && !E->isValueDependent()) 12292 CheckForIntOverflow(E); 12293 DiagnoseMisalignedMembers(); 12294 } 12295 12296 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12297 FieldDecl *BitField, 12298 Expr *Init) { 12299 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12300 } 12301 12302 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12303 SourceLocation Loc) { 12304 if (!PType->isVariablyModifiedType()) 12305 return; 12306 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12307 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12308 return; 12309 } 12310 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12311 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12312 return; 12313 } 12314 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12315 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12316 return; 12317 } 12318 12319 const ArrayType *AT = S.Context.getAsArrayType(PType); 12320 if (!AT) 12321 return; 12322 12323 if (AT->getSizeModifier() != ArrayType::Star) { 12324 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12325 return; 12326 } 12327 12328 S.Diag(Loc, diag::err_array_star_in_function_definition); 12329 } 12330 12331 /// CheckParmsForFunctionDef - Check that the parameters of the given 12332 /// function are appropriate for the definition of a function. This 12333 /// takes care of any checks that cannot be performed on the 12334 /// declaration itself, e.g., that the types of each of the function 12335 /// parameters are complete. 12336 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12337 bool CheckParameterNames) { 12338 bool HasInvalidParm = false; 12339 for (ParmVarDecl *Param : Parameters) { 12340 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12341 // function declarator that is part of a function definition of 12342 // that function shall not have incomplete type. 12343 // 12344 // This is also C++ [dcl.fct]p6. 12345 if (!Param->isInvalidDecl() && 12346 RequireCompleteType(Param->getLocation(), Param->getType(), 12347 diag::err_typecheck_decl_incomplete_type)) { 12348 Param->setInvalidDecl(); 12349 HasInvalidParm = true; 12350 } 12351 12352 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12353 // declaration of each parameter shall include an identifier. 12354 if (CheckParameterNames && 12355 Param->getIdentifier() == nullptr && 12356 !Param->isImplicit() && 12357 !getLangOpts().CPlusPlus) 12358 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12359 12360 // C99 6.7.5.3p12: 12361 // If the function declarator is not part of a definition of that 12362 // function, parameters may have incomplete type and may use the [*] 12363 // notation in their sequences of declarator specifiers to specify 12364 // variable length array types. 12365 QualType PType = Param->getOriginalType(); 12366 // FIXME: This diagnostic should point the '[*]' if source-location 12367 // information is added for it. 12368 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12369 12370 // If the parameter is a c++ class type and it has to be destructed in the 12371 // callee function, declare the destructor so that it can be called by the 12372 // callee function. Do not perform any direct access check on the dtor here. 12373 if (!Param->isInvalidDecl()) { 12374 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12375 if (!ClassDecl->isInvalidDecl() && 12376 !ClassDecl->hasIrrelevantDestructor() && 12377 !ClassDecl->isDependentContext() && 12378 ClassDecl->isParamDestroyedInCallee()) { 12379 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12380 MarkFunctionReferenced(Param->getLocation(), Destructor); 12381 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12382 } 12383 } 12384 } 12385 12386 // Parameters with the pass_object_size attribute only need to be marked 12387 // constant at function definitions. Because we lack information about 12388 // whether we're on a declaration or definition when we're instantiating the 12389 // attribute, we need to check for constness here. 12390 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12391 if (!Param->getType().isConstQualified()) 12392 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12393 << Attr->getSpelling() << 1; 12394 12395 // Check for parameter names shadowing fields from the class. 12396 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12397 // The owning context for the parameter should be the function, but we 12398 // want to see if this function's declaration context is a record. 12399 DeclContext *DC = Param->getDeclContext(); 12400 if (DC && DC->isFunctionOrMethod()) { 12401 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12402 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12403 RD, /*DeclIsField*/ false); 12404 } 12405 } 12406 } 12407 12408 return HasInvalidParm; 12409 } 12410 12411 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12412 /// or MemberExpr. 12413 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12414 ASTContext &Context) { 12415 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12416 return Context.getDeclAlign(DRE->getDecl()); 12417 12418 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12419 return Context.getDeclAlign(ME->getMemberDecl()); 12420 12421 return TypeAlign; 12422 } 12423 12424 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12425 /// pointer cast increases the alignment requirements. 12426 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12427 // This is actually a lot of work to potentially be doing on every 12428 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12429 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12430 return; 12431 12432 // Ignore dependent types. 12433 if (T->isDependentType() || Op->getType()->isDependentType()) 12434 return; 12435 12436 // Require that the destination be a pointer type. 12437 const PointerType *DestPtr = T->getAs<PointerType>(); 12438 if (!DestPtr) return; 12439 12440 // If the destination has alignment 1, we're done. 12441 QualType DestPointee = DestPtr->getPointeeType(); 12442 if (DestPointee->isIncompleteType()) return; 12443 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12444 if (DestAlign.isOne()) return; 12445 12446 // Require that the source be a pointer type. 12447 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12448 if (!SrcPtr) return; 12449 QualType SrcPointee = SrcPtr->getPointeeType(); 12450 12451 // Whitelist casts from cv void*. We already implicitly 12452 // whitelisted casts to cv void*, since they have alignment 1. 12453 // Also whitelist casts involving incomplete types, which implicitly 12454 // includes 'void'. 12455 if (SrcPointee->isIncompleteType()) return; 12456 12457 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12458 12459 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12460 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12461 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12462 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12463 if (UO->getOpcode() == UO_AddrOf) 12464 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12465 } 12466 12467 if (SrcAlign >= DestAlign) return; 12468 12469 Diag(TRange.getBegin(), diag::warn_cast_align) 12470 << Op->getType() << T 12471 << static_cast<unsigned>(SrcAlign.getQuantity()) 12472 << static_cast<unsigned>(DestAlign.getQuantity()) 12473 << TRange << Op->getSourceRange(); 12474 } 12475 12476 /// Check whether this array fits the idiom of a size-one tail padded 12477 /// array member of a struct. 12478 /// 12479 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12480 /// commonly used to emulate flexible arrays in C89 code. 12481 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12482 const NamedDecl *ND) { 12483 if (Size != 1 || !ND) return false; 12484 12485 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12486 if (!FD) return false; 12487 12488 // Don't consider sizes resulting from macro expansions or template argument 12489 // substitution to form C89 tail-padded arrays. 12490 12491 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12492 while (TInfo) { 12493 TypeLoc TL = TInfo->getTypeLoc(); 12494 // Look through typedefs. 12495 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12496 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12497 TInfo = TDL->getTypeSourceInfo(); 12498 continue; 12499 } 12500 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12501 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12502 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12503 return false; 12504 } 12505 break; 12506 } 12507 12508 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12509 if (!RD) return false; 12510 if (RD->isUnion()) return false; 12511 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12512 if (!CRD->isStandardLayout()) return false; 12513 } 12514 12515 // See if this is the last field decl in the record. 12516 const Decl *D = FD; 12517 while ((D = D->getNextDeclInContext())) 12518 if (isa<FieldDecl>(D)) 12519 return false; 12520 return true; 12521 } 12522 12523 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12524 const ArraySubscriptExpr *ASE, 12525 bool AllowOnePastEnd, bool IndexNegated) { 12526 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12527 if (IndexExpr->isValueDependent()) 12528 return; 12529 12530 const Type *EffectiveType = 12531 BaseExpr->getType()->getPointeeOrArrayElementType(); 12532 BaseExpr = BaseExpr->IgnoreParenCasts(); 12533 const ConstantArrayType *ArrayTy = 12534 Context.getAsConstantArrayType(BaseExpr->getType()); 12535 12536 if (!ArrayTy) 12537 return; 12538 12539 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 12540 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 12541 return; 12542 12543 Expr::EvalResult Result; 12544 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12545 return; 12546 12547 llvm::APSInt index = Result.Val.getInt(); 12548 if (IndexNegated) 12549 index = -index; 12550 12551 const NamedDecl *ND = nullptr; 12552 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12553 ND = DRE->getDecl(); 12554 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12555 ND = ME->getMemberDecl(); 12556 12557 if (index.isUnsigned() || !index.isNegative()) { 12558 // It is possible that the type of the base expression after 12559 // IgnoreParenCasts is incomplete, even though the type of the base 12560 // expression before IgnoreParenCasts is complete (see PR39746 for an 12561 // example). In this case we have no information about whether the array 12562 // access exceeds the array bounds. However we can still diagnose an array 12563 // access which precedes the array bounds. 12564 if (BaseType->isIncompleteType()) 12565 return; 12566 12567 llvm::APInt size = ArrayTy->getSize(); 12568 if (!size.isStrictlyPositive()) 12569 return; 12570 12571 if (BaseType != EffectiveType) { 12572 // Make sure we're comparing apples to apples when comparing index to size 12573 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12574 uint64_t array_typesize = Context.getTypeSize(BaseType); 12575 // Handle ptrarith_typesize being zero, such as when casting to void* 12576 if (!ptrarith_typesize) ptrarith_typesize = 1; 12577 if (ptrarith_typesize != array_typesize) { 12578 // There's a cast to a different size type involved 12579 uint64_t ratio = array_typesize / ptrarith_typesize; 12580 // TODO: Be smarter about handling cases where array_typesize is not a 12581 // multiple of ptrarith_typesize 12582 if (ptrarith_typesize * ratio == array_typesize) 12583 size *= llvm::APInt(size.getBitWidth(), ratio); 12584 } 12585 } 12586 12587 if (size.getBitWidth() > index.getBitWidth()) 12588 index = index.zext(size.getBitWidth()); 12589 else if (size.getBitWidth() < index.getBitWidth()) 12590 size = size.zext(index.getBitWidth()); 12591 12592 // For array subscripting the index must be less than size, but for pointer 12593 // arithmetic also allow the index (offset) to be equal to size since 12594 // computing the next address after the end of the array is legal and 12595 // commonly done e.g. in C++ iterators and range-based for loops. 12596 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12597 return; 12598 12599 // Also don't warn for arrays of size 1 which are members of some 12600 // structure. These are often used to approximate flexible arrays in C89 12601 // code. 12602 if (IsTailPaddedMemberArray(*this, size, ND)) 12603 return; 12604 12605 // Suppress the warning if the subscript expression (as identified by the 12606 // ']' location) and the index expression are both from macro expansions 12607 // within a system header. 12608 if (ASE) { 12609 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12610 ASE->getRBracketLoc()); 12611 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12612 SourceLocation IndexLoc = 12613 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12614 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12615 return; 12616 } 12617 } 12618 12619 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12620 if (ASE) 12621 DiagID = diag::warn_array_index_exceeds_bounds; 12622 12623 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12624 PDiag(DiagID) << index.toString(10, true) 12625 << size.toString(10, true) 12626 << (unsigned)size.getLimitedValue(~0U) 12627 << IndexExpr->getSourceRange()); 12628 } else { 12629 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12630 if (!ASE) { 12631 DiagID = diag::warn_ptr_arith_precedes_bounds; 12632 if (index.isNegative()) index = -index; 12633 } 12634 12635 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12636 PDiag(DiagID) << index.toString(10, true) 12637 << IndexExpr->getSourceRange()); 12638 } 12639 12640 if (!ND) { 12641 // Try harder to find a NamedDecl to point at in the note. 12642 while (const ArraySubscriptExpr *ASE = 12643 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12644 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12645 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12646 ND = DRE->getDecl(); 12647 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12648 ND = ME->getMemberDecl(); 12649 } 12650 12651 if (ND) 12652 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12653 PDiag(diag::note_array_index_out_of_bounds) 12654 << ND->getDeclName()); 12655 } 12656 12657 void Sema::CheckArrayAccess(const Expr *expr) { 12658 int AllowOnePastEnd = 0; 12659 while (expr) { 12660 expr = expr->IgnoreParenImpCasts(); 12661 switch (expr->getStmtClass()) { 12662 case Stmt::ArraySubscriptExprClass: { 12663 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12664 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12665 AllowOnePastEnd > 0); 12666 expr = ASE->getBase(); 12667 break; 12668 } 12669 case Stmt::MemberExprClass: { 12670 expr = cast<MemberExpr>(expr)->getBase(); 12671 break; 12672 } 12673 case Stmt::OMPArraySectionExprClass: { 12674 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12675 if (ASE->getLowerBound()) 12676 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12677 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12678 return; 12679 } 12680 case Stmt::UnaryOperatorClass: { 12681 // Only unwrap the * and & unary operators 12682 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12683 expr = UO->getSubExpr(); 12684 switch (UO->getOpcode()) { 12685 case UO_AddrOf: 12686 AllowOnePastEnd++; 12687 break; 12688 case UO_Deref: 12689 AllowOnePastEnd--; 12690 break; 12691 default: 12692 return; 12693 } 12694 break; 12695 } 12696 case Stmt::ConditionalOperatorClass: { 12697 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12698 if (const Expr *lhs = cond->getLHS()) 12699 CheckArrayAccess(lhs); 12700 if (const Expr *rhs = cond->getRHS()) 12701 CheckArrayAccess(rhs); 12702 return; 12703 } 12704 case Stmt::CXXOperatorCallExprClass: { 12705 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12706 for (const auto *Arg : OCE->arguments()) 12707 CheckArrayAccess(Arg); 12708 return; 12709 } 12710 default: 12711 return; 12712 } 12713 } 12714 } 12715 12716 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12717 12718 namespace { 12719 12720 struct RetainCycleOwner { 12721 VarDecl *Variable = nullptr; 12722 SourceRange Range; 12723 SourceLocation Loc; 12724 bool Indirect = false; 12725 12726 RetainCycleOwner() = default; 12727 12728 void setLocsFrom(Expr *e) { 12729 Loc = e->getExprLoc(); 12730 Range = e->getSourceRange(); 12731 } 12732 }; 12733 12734 } // namespace 12735 12736 /// Consider whether capturing the given variable can possibly lead to 12737 /// a retain cycle. 12738 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12739 // In ARC, it's captured strongly iff the variable has __strong 12740 // lifetime. In MRR, it's captured strongly if the variable is 12741 // __block and has an appropriate type. 12742 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12743 return false; 12744 12745 owner.Variable = var; 12746 if (ref) 12747 owner.setLocsFrom(ref); 12748 return true; 12749 } 12750 12751 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 12752 while (true) { 12753 e = e->IgnoreParens(); 12754 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 12755 switch (cast->getCastKind()) { 12756 case CK_BitCast: 12757 case CK_LValueBitCast: 12758 case CK_LValueToRValue: 12759 case CK_ARCReclaimReturnedObject: 12760 e = cast->getSubExpr(); 12761 continue; 12762 12763 default: 12764 return false; 12765 } 12766 } 12767 12768 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 12769 ObjCIvarDecl *ivar = ref->getDecl(); 12770 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12771 return false; 12772 12773 // Try to find a retain cycle in the base. 12774 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 12775 return false; 12776 12777 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 12778 owner.Indirect = true; 12779 return true; 12780 } 12781 12782 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 12783 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 12784 if (!var) return false; 12785 return considerVariable(var, ref, owner); 12786 } 12787 12788 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 12789 if (member->isArrow()) return false; 12790 12791 // Don't count this as an indirect ownership. 12792 e = member->getBase(); 12793 continue; 12794 } 12795 12796 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 12797 // Only pay attention to pseudo-objects on property references. 12798 ObjCPropertyRefExpr *pre 12799 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 12800 ->IgnoreParens()); 12801 if (!pre) return false; 12802 if (pre->isImplicitProperty()) return false; 12803 ObjCPropertyDecl *property = pre->getExplicitProperty(); 12804 if (!property->isRetaining() && 12805 !(property->getPropertyIvarDecl() && 12806 property->getPropertyIvarDecl()->getType() 12807 .getObjCLifetime() == Qualifiers::OCL_Strong)) 12808 return false; 12809 12810 owner.Indirect = true; 12811 if (pre->isSuperReceiver()) { 12812 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 12813 if (!owner.Variable) 12814 return false; 12815 owner.Loc = pre->getLocation(); 12816 owner.Range = pre->getSourceRange(); 12817 return true; 12818 } 12819 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 12820 ->getSourceExpr()); 12821 continue; 12822 } 12823 12824 // Array ivars? 12825 12826 return false; 12827 } 12828 } 12829 12830 namespace { 12831 12832 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 12833 ASTContext &Context; 12834 VarDecl *Variable; 12835 Expr *Capturer = nullptr; 12836 bool VarWillBeReased = false; 12837 12838 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 12839 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 12840 Context(Context), Variable(variable) {} 12841 12842 void VisitDeclRefExpr(DeclRefExpr *ref) { 12843 if (ref->getDecl() == Variable && !Capturer) 12844 Capturer = ref; 12845 } 12846 12847 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 12848 if (Capturer) return; 12849 Visit(ref->getBase()); 12850 if (Capturer && ref->isFreeIvar()) 12851 Capturer = ref; 12852 } 12853 12854 void VisitBlockExpr(BlockExpr *block) { 12855 // Look inside nested blocks 12856 if (block->getBlockDecl()->capturesVariable(Variable)) 12857 Visit(block->getBlockDecl()->getBody()); 12858 } 12859 12860 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 12861 if (Capturer) return; 12862 if (OVE->getSourceExpr()) 12863 Visit(OVE->getSourceExpr()); 12864 } 12865 12866 void VisitBinaryOperator(BinaryOperator *BinOp) { 12867 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 12868 return; 12869 Expr *LHS = BinOp->getLHS(); 12870 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 12871 if (DRE->getDecl() != Variable) 12872 return; 12873 if (Expr *RHS = BinOp->getRHS()) { 12874 RHS = RHS->IgnoreParenCasts(); 12875 llvm::APSInt Value; 12876 VarWillBeReased = 12877 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 12878 } 12879 } 12880 } 12881 }; 12882 12883 } // namespace 12884 12885 /// Check whether the given argument is a block which captures a 12886 /// variable. 12887 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 12888 assert(owner.Variable && owner.Loc.isValid()); 12889 12890 e = e->IgnoreParenCasts(); 12891 12892 // Look through [^{...} copy] and Block_copy(^{...}). 12893 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 12894 Selector Cmd = ME->getSelector(); 12895 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 12896 e = ME->getInstanceReceiver(); 12897 if (!e) 12898 return nullptr; 12899 e = e->IgnoreParenCasts(); 12900 } 12901 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 12902 if (CE->getNumArgs() == 1) { 12903 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 12904 if (Fn) { 12905 const IdentifierInfo *FnI = Fn->getIdentifier(); 12906 if (FnI && FnI->isStr("_Block_copy")) { 12907 e = CE->getArg(0)->IgnoreParenCasts(); 12908 } 12909 } 12910 } 12911 } 12912 12913 BlockExpr *block = dyn_cast<BlockExpr>(e); 12914 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 12915 return nullptr; 12916 12917 FindCaptureVisitor visitor(S.Context, owner.Variable); 12918 visitor.Visit(block->getBlockDecl()->getBody()); 12919 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 12920 } 12921 12922 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 12923 RetainCycleOwner &owner) { 12924 assert(capturer); 12925 assert(owner.Variable && owner.Loc.isValid()); 12926 12927 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 12928 << owner.Variable << capturer->getSourceRange(); 12929 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 12930 << owner.Indirect << owner.Range; 12931 } 12932 12933 /// Check for a keyword selector that starts with the word 'add' or 12934 /// 'set'. 12935 static bool isSetterLikeSelector(Selector sel) { 12936 if (sel.isUnarySelector()) return false; 12937 12938 StringRef str = sel.getNameForSlot(0); 12939 while (!str.empty() && str.front() == '_') str = str.substr(1); 12940 if (str.startswith("set")) 12941 str = str.substr(3); 12942 else if (str.startswith("add")) { 12943 // Specially whitelist 'addOperationWithBlock:'. 12944 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 12945 return false; 12946 str = str.substr(3); 12947 } 12948 else 12949 return false; 12950 12951 if (str.empty()) return true; 12952 return !isLowercase(str.front()); 12953 } 12954 12955 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 12956 ObjCMessageExpr *Message) { 12957 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 12958 Message->getReceiverInterface(), 12959 NSAPI::ClassId_NSMutableArray); 12960 if (!IsMutableArray) { 12961 return None; 12962 } 12963 12964 Selector Sel = Message->getSelector(); 12965 12966 Optional<NSAPI::NSArrayMethodKind> MKOpt = 12967 S.NSAPIObj->getNSArrayMethodKind(Sel); 12968 if (!MKOpt) { 12969 return None; 12970 } 12971 12972 NSAPI::NSArrayMethodKind MK = *MKOpt; 12973 12974 switch (MK) { 12975 case NSAPI::NSMutableArr_addObject: 12976 case NSAPI::NSMutableArr_insertObjectAtIndex: 12977 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 12978 return 0; 12979 case NSAPI::NSMutableArr_replaceObjectAtIndex: 12980 return 1; 12981 12982 default: 12983 return None; 12984 } 12985 12986 return None; 12987 } 12988 12989 static 12990 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 12991 ObjCMessageExpr *Message) { 12992 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 12993 Message->getReceiverInterface(), 12994 NSAPI::ClassId_NSMutableDictionary); 12995 if (!IsMutableDictionary) { 12996 return None; 12997 } 12998 12999 Selector Sel = Message->getSelector(); 13000 13001 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13002 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13003 if (!MKOpt) { 13004 return None; 13005 } 13006 13007 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13008 13009 switch (MK) { 13010 case NSAPI::NSMutableDict_setObjectForKey: 13011 case NSAPI::NSMutableDict_setValueForKey: 13012 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13013 return 0; 13014 13015 default: 13016 return None; 13017 } 13018 13019 return None; 13020 } 13021 13022 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13023 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13024 Message->getReceiverInterface(), 13025 NSAPI::ClassId_NSMutableSet); 13026 13027 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13028 Message->getReceiverInterface(), 13029 NSAPI::ClassId_NSMutableOrderedSet); 13030 if (!IsMutableSet && !IsMutableOrderedSet) { 13031 return None; 13032 } 13033 13034 Selector Sel = Message->getSelector(); 13035 13036 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13037 if (!MKOpt) { 13038 return None; 13039 } 13040 13041 NSAPI::NSSetMethodKind MK = *MKOpt; 13042 13043 switch (MK) { 13044 case NSAPI::NSMutableSet_addObject: 13045 case NSAPI::NSOrderedSet_setObjectAtIndex: 13046 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13047 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13048 return 0; 13049 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13050 return 1; 13051 } 13052 13053 return None; 13054 } 13055 13056 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13057 if (!Message->isInstanceMessage()) { 13058 return; 13059 } 13060 13061 Optional<int> ArgOpt; 13062 13063 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13064 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13065 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13066 return; 13067 } 13068 13069 int ArgIndex = *ArgOpt; 13070 13071 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13072 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13073 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13074 } 13075 13076 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13077 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13078 if (ArgRE->isObjCSelfExpr()) { 13079 Diag(Message->getSourceRange().getBegin(), 13080 diag::warn_objc_circular_container) 13081 << ArgRE->getDecl() << StringRef("'super'"); 13082 } 13083 } 13084 } else { 13085 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13086 13087 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13088 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13089 } 13090 13091 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13092 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13093 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13094 ValueDecl *Decl = ReceiverRE->getDecl(); 13095 Diag(Message->getSourceRange().getBegin(), 13096 diag::warn_objc_circular_container) 13097 << Decl << Decl; 13098 if (!ArgRE->isObjCSelfExpr()) { 13099 Diag(Decl->getLocation(), 13100 diag::note_objc_circular_container_declared_here) 13101 << Decl; 13102 } 13103 } 13104 } 13105 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13106 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13107 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13108 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13109 Diag(Message->getSourceRange().getBegin(), 13110 diag::warn_objc_circular_container) 13111 << Decl << Decl; 13112 Diag(Decl->getLocation(), 13113 diag::note_objc_circular_container_declared_here) 13114 << Decl; 13115 } 13116 } 13117 } 13118 } 13119 } 13120 13121 /// Check a message send to see if it's likely to cause a retain cycle. 13122 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13123 // Only check instance methods whose selector looks like a setter. 13124 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13125 return; 13126 13127 // Try to find a variable that the receiver is strongly owned by. 13128 RetainCycleOwner owner; 13129 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13130 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13131 return; 13132 } else { 13133 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13134 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13135 owner.Loc = msg->getSuperLoc(); 13136 owner.Range = msg->getSuperLoc(); 13137 } 13138 13139 // Check whether the receiver is captured by any of the arguments. 13140 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13141 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13142 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13143 // noescape blocks should not be retained by the method. 13144 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13145 continue; 13146 return diagnoseRetainCycle(*this, capturer, owner); 13147 } 13148 } 13149 } 13150 13151 /// Check a property assign to see if it's likely to cause a retain cycle. 13152 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13153 RetainCycleOwner owner; 13154 if (!findRetainCycleOwner(*this, receiver, owner)) 13155 return; 13156 13157 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13158 diagnoseRetainCycle(*this, capturer, owner); 13159 } 13160 13161 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13162 RetainCycleOwner Owner; 13163 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13164 return; 13165 13166 // Because we don't have an expression for the variable, we have to set the 13167 // location explicitly here. 13168 Owner.Loc = Var->getLocation(); 13169 Owner.Range = Var->getSourceRange(); 13170 13171 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13172 diagnoseRetainCycle(*this, Capturer, Owner); 13173 } 13174 13175 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13176 Expr *RHS, bool isProperty) { 13177 // Check if RHS is an Objective-C object literal, which also can get 13178 // immediately zapped in a weak reference. Note that we explicitly 13179 // allow ObjCStringLiterals, since those are designed to never really die. 13180 RHS = RHS->IgnoreParenImpCasts(); 13181 13182 // This enum needs to match with the 'select' in 13183 // warn_objc_arc_literal_assign (off-by-1). 13184 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13185 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13186 return false; 13187 13188 S.Diag(Loc, diag::warn_arc_literal_assign) 13189 << (unsigned) Kind 13190 << (isProperty ? 0 : 1) 13191 << RHS->getSourceRange(); 13192 13193 return true; 13194 } 13195 13196 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13197 Qualifiers::ObjCLifetime LT, 13198 Expr *RHS, bool isProperty) { 13199 // Strip off any implicit cast added to get to the one ARC-specific. 13200 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13201 if (cast->getCastKind() == CK_ARCConsumeObject) { 13202 S.Diag(Loc, diag::warn_arc_retained_assign) 13203 << (LT == Qualifiers::OCL_ExplicitNone) 13204 << (isProperty ? 0 : 1) 13205 << RHS->getSourceRange(); 13206 return true; 13207 } 13208 RHS = cast->getSubExpr(); 13209 } 13210 13211 if (LT == Qualifiers::OCL_Weak && 13212 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13213 return true; 13214 13215 return false; 13216 } 13217 13218 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13219 QualType LHS, Expr *RHS) { 13220 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13221 13222 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13223 return false; 13224 13225 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13226 return true; 13227 13228 return false; 13229 } 13230 13231 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13232 Expr *LHS, Expr *RHS) { 13233 QualType LHSType; 13234 // PropertyRef on LHS type need be directly obtained from 13235 // its declaration as it has a PseudoType. 13236 ObjCPropertyRefExpr *PRE 13237 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13238 if (PRE && !PRE->isImplicitProperty()) { 13239 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13240 if (PD) 13241 LHSType = PD->getType(); 13242 } 13243 13244 if (LHSType.isNull()) 13245 LHSType = LHS->getType(); 13246 13247 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13248 13249 if (LT == Qualifiers::OCL_Weak) { 13250 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13251 getCurFunction()->markSafeWeakUse(LHS); 13252 } 13253 13254 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13255 return; 13256 13257 // FIXME. Check for other life times. 13258 if (LT != Qualifiers::OCL_None) 13259 return; 13260 13261 if (PRE) { 13262 if (PRE->isImplicitProperty()) 13263 return; 13264 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13265 if (!PD) 13266 return; 13267 13268 unsigned Attributes = PD->getPropertyAttributes(); 13269 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13270 // when 'assign' attribute was not explicitly specified 13271 // by user, ignore it and rely on property type itself 13272 // for lifetime info. 13273 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13274 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13275 LHSType->isObjCRetainableType()) 13276 return; 13277 13278 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13279 if (cast->getCastKind() == CK_ARCConsumeObject) { 13280 Diag(Loc, diag::warn_arc_retained_property_assign) 13281 << RHS->getSourceRange(); 13282 return; 13283 } 13284 RHS = cast->getSubExpr(); 13285 } 13286 } 13287 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13288 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13289 return; 13290 } 13291 } 13292 } 13293 13294 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13295 13296 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13297 SourceLocation StmtLoc, 13298 const NullStmt *Body) { 13299 // Do not warn if the body is a macro that expands to nothing, e.g: 13300 // 13301 // #define CALL(x) 13302 // if (condition) 13303 // CALL(0); 13304 if (Body->hasLeadingEmptyMacro()) 13305 return false; 13306 13307 // Get line numbers of statement and body. 13308 bool StmtLineInvalid; 13309 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13310 &StmtLineInvalid); 13311 if (StmtLineInvalid) 13312 return false; 13313 13314 bool BodyLineInvalid; 13315 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13316 &BodyLineInvalid); 13317 if (BodyLineInvalid) 13318 return false; 13319 13320 // Warn if null statement and body are on the same line. 13321 if (StmtLine != BodyLine) 13322 return false; 13323 13324 return true; 13325 } 13326 13327 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13328 const Stmt *Body, 13329 unsigned DiagID) { 13330 // Since this is a syntactic check, don't emit diagnostic for template 13331 // instantiations, this just adds noise. 13332 if (CurrentInstantiationScope) 13333 return; 13334 13335 // The body should be a null statement. 13336 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13337 if (!NBody) 13338 return; 13339 13340 // Do the usual checks. 13341 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13342 return; 13343 13344 Diag(NBody->getSemiLoc(), DiagID); 13345 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13346 } 13347 13348 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13349 const Stmt *PossibleBody) { 13350 assert(!CurrentInstantiationScope); // Ensured by caller 13351 13352 SourceLocation StmtLoc; 13353 const Stmt *Body; 13354 unsigned DiagID; 13355 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13356 StmtLoc = FS->getRParenLoc(); 13357 Body = FS->getBody(); 13358 DiagID = diag::warn_empty_for_body; 13359 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13360 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13361 Body = WS->getBody(); 13362 DiagID = diag::warn_empty_while_body; 13363 } else 13364 return; // Neither `for' nor `while'. 13365 13366 // The body should be a null statement. 13367 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13368 if (!NBody) 13369 return; 13370 13371 // Skip expensive checks if diagnostic is disabled. 13372 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13373 return; 13374 13375 // Do the usual checks. 13376 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13377 return; 13378 13379 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13380 // noise level low, emit diagnostics only if for/while is followed by a 13381 // CompoundStmt, e.g.: 13382 // for (int i = 0; i < n; i++); 13383 // { 13384 // a(i); 13385 // } 13386 // or if for/while is followed by a statement with more indentation 13387 // than for/while itself: 13388 // for (int i = 0; i < n; i++); 13389 // a(i); 13390 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13391 if (!ProbableTypo) { 13392 bool BodyColInvalid; 13393 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13394 PossibleBody->getBeginLoc(), &BodyColInvalid); 13395 if (BodyColInvalid) 13396 return; 13397 13398 bool StmtColInvalid; 13399 unsigned StmtCol = 13400 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13401 if (StmtColInvalid) 13402 return; 13403 13404 if (BodyCol > StmtCol) 13405 ProbableTypo = true; 13406 } 13407 13408 if (ProbableTypo) { 13409 Diag(NBody->getSemiLoc(), DiagID); 13410 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13411 } 13412 } 13413 13414 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13415 13416 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13417 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13418 SourceLocation OpLoc) { 13419 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13420 return; 13421 13422 if (inTemplateInstantiation()) 13423 return; 13424 13425 // Strip parens and casts away. 13426 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13427 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13428 13429 // Check for a call expression 13430 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13431 if (!CE || CE->getNumArgs() != 1) 13432 return; 13433 13434 // Check for a call to std::move 13435 if (!CE->isCallToStdMove()) 13436 return; 13437 13438 // Get argument from std::move 13439 RHSExpr = CE->getArg(0); 13440 13441 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13442 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13443 13444 // Two DeclRefExpr's, check that the decls are the same. 13445 if (LHSDeclRef && RHSDeclRef) { 13446 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13447 return; 13448 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13449 RHSDeclRef->getDecl()->getCanonicalDecl()) 13450 return; 13451 13452 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13453 << LHSExpr->getSourceRange() 13454 << RHSExpr->getSourceRange(); 13455 return; 13456 } 13457 13458 // Member variables require a different approach to check for self moves. 13459 // MemberExpr's are the same if every nested MemberExpr refers to the same 13460 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13461 // the base Expr's are CXXThisExpr's. 13462 const Expr *LHSBase = LHSExpr; 13463 const Expr *RHSBase = RHSExpr; 13464 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13465 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13466 if (!LHSME || !RHSME) 13467 return; 13468 13469 while (LHSME && RHSME) { 13470 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13471 RHSME->getMemberDecl()->getCanonicalDecl()) 13472 return; 13473 13474 LHSBase = LHSME->getBase(); 13475 RHSBase = RHSME->getBase(); 13476 LHSME = dyn_cast<MemberExpr>(LHSBase); 13477 RHSME = dyn_cast<MemberExpr>(RHSBase); 13478 } 13479 13480 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13481 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13482 if (LHSDeclRef && RHSDeclRef) { 13483 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13484 return; 13485 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13486 RHSDeclRef->getDecl()->getCanonicalDecl()) 13487 return; 13488 13489 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13490 << LHSExpr->getSourceRange() 13491 << RHSExpr->getSourceRange(); 13492 return; 13493 } 13494 13495 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13496 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13497 << LHSExpr->getSourceRange() 13498 << RHSExpr->getSourceRange(); 13499 } 13500 13501 //===--- Layout compatibility ----------------------------------------------// 13502 13503 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13504 13505 /// Check if two enumeration types are layout-compatible. 13506 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13507 // C++11 [dcl.enum] p8: 13508 // Two enumeration types are layout-compatible if they have the same 13509 // underlying type. 13510 return ED1->isComplete() && ED2->isComplete() && 13511 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13512 } 13513 13514 /// Check if two fields are layout-compatible. 13515 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13516 FieldDecl *Field2) { 13517 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13518 return false; 13519 13520 if (Field1->isBitField() != Field2->isBitField()) 13521 return false; 13522 13523 if (Field1->isBitField()) { 13524 // Make sure that the bit-fields are the same length. 13525 unsigned Bits1 = Field1->getBitWidthValue(C); 13526 unsigned Bits2 = Field2->getBitWidthValue(C); 13527 13528 if (Bits1 != Bits2) 13529 return false; 13530 } 13531 13532 return true; 13533 } 13534 13535 /// Check if two standard-layout structs are layout-compatible. 13536 /// (C++11 [class.mem] p17) 13537 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13538 RecordDecl *RD2) { 13539 // If both records are C++ classes, check that base classes match. 13540 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13541 // If one of records is a CXXRecordDecl we are in C++ mode, 13542 // thus the other one is a CXXRecordDecl, too. 13543 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13544 // Check number of base classes. 13545 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13546 return false; 13547 13548 // Check the base classes. 13549 for (CXXRecordDecl::base_class_const_iterator 13550 Base1 = D1CXX->bases_begin(), 13551 BaseEnd1 = D1CXX->bases_end(), 13552 Base2 = D2CXX->bases_begin(); 13553 Base1 != BaseEnd1; 13554 ++Base1, ++Base2) { 13555 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13556 return false; 13557 } 13558 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13559 // If only RD2 is a C++ class, it should have zero base classes. 13560 if (D2CXX->getNumBases() > 0) 13561 return false; 13562 } 13563 13564 // Check the fields. 13565 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13566 Field2End = RD2->field_end(), 13567 Field1 = RD1->field_begin(), 13568 Field1End = RD1->field_end(); 13569 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13570 if (!isLayoutCompatible(C, *Field1, *Field2)) 13571 return false; 13572 } 13573 if (Field1 != Field1End || Field2 != Field2End) 13574 return false; 13575 13576 return true; 13577 } 13578 13579 /// Check if two standard-layout unions are layout-compatible. 13580 /// (C++11 [class.mem] p18) 13581 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13582 RecordDecl *RD2) { 13583 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13584 for (auto *Field2 : RD2->fields()) 13585 UnmatchedFields.insert(Field2); 13586 13587 for (auto *Field1 : RD1->fields()) { 13588 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13589 I = UnmatchedFields.begin(), 13590 E = UnmatchedFields.end(); 13591 13592 for ( ; I != E; ++I) { 13593 if (isLayoutCompatible(C, Field1, *I)) { 13594 bool Result = UnmatchedFields.erase(*I); 13595 (void) Result; 13596 assert(Result); 13597 break; 13598 } 13599 } 13600 if (I == E) 13601 return false; 13602 } 13603 13604 return UnmatchedFields.empty(); 13605 } 13606 13607 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13608 RecordDecl *RD2) { 13609 if (RD1->isUnion() != RD2->isUnion()) 13610 return false; 13611 13612 if (RD1->isUnion()) 13613 return isLayoutCompatibleUnion(C, RD1, RD2); 13614 else 13615 return isLayoutCompatibleStruct(C, RD1, RD2); 13616 } 13617 13618 /// Check if two types are layout-compatible in C++11 sense. 13619 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13620 if (T1.isNull() || T2.isNull()) 13621 return false; 13622 13623 // C++11 [basic.types] p11: 13624 // If two types T1 and T2 are the same type, then T1 and T2 are 13625 // layout-compatible types. 13626 if (C.hasSameType(T1, T2)) 13627 return true; 13628 13629 T1 = T1.getCanonicalType().getUnqualifiedType(); 13630 T2 = T2.getCanonicalType().getUnqualifiedType(); 13631 13632 const Type::TypeClass TC1 = T1->getTypeClass(); 13633 const Type::TypeClass TC2 = T2->getTypeClass(); 13634 13635 if (TC1 != TC2) 13636 return false; 13637 13638 if (TC1 == Type::Enum) { 13639 return isLayoutCompatible(C, 13640 cast<EnumType>(T1)->getDecl(), 13641 cast<EnumType>(T2)->getDecl()); 13642 } else if (TC1 == Type::Record) { 13643 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13644 return false; 13645 13646 return isLayoutCompatible(C, 13647 cast<RecordType>(T1)->getDecl(), 13648 cast<RecordType>(T2)->getDecl()); 13649 } 13650 13651 return false; 13652 } 13653 13654 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13655 13656 /// Given a type tag expression find the type tag itself. 13657 /// 13658 /// \param TypeExpr Type tag expression, as it appears in user's code. 13659 /// 13660 /// \param VD Declaration of an identifier that appears in a type tag. 13661 /// 13662 /// \param MagicValue Type tag magic value. 13663 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13664 const ValueDecl **VD, uint64_t *MagicValue) { 13665 while(true) { 13666 if (!TypeExpr) 13667 return false; 13668 13669 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13670 13671 switch (TypeExpr->getStmtClass()) { 13672 case Stmt::UnaryOperatorClass: { 13673 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13674 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13675 TypeExpr = UO->getSubExpr(); 13676 continue; 13677 } 13678 return false; 13679 } 13680 13681 case Stmt::DeclRefExprClass: { 13682 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13683 *VD = DRE->getDecl(); 13684 return true; 13685 } 13686 13687 case Stmt::IntegerLiteralClass: { 13688 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13689 llvm::APInt MagicValueAPInt = IL->getValue(); 13690 if (MagicValueAPInt.getActiveBits() <= 64) { 13691 *MagicValue = MagicValueAPInt.getZExtValue(); 13692 return true; 13693 } else 13694 return false; 13695 } 13696 13697 case Stmt::BinaryConditionalOperatorClass: 13698 case Stmt::ConditionalOperatorClass: { 13699 const AbstractConditionalOperator *ACO = 13700 cast<AbstractConditionalOperator>(TypeExpr); 13701 bool Result; 13702 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) { 13703 if (Result) 13704 TypeExpr = ACO->getTrueExpr(); 13705 else 13706 TypeExpr = ACO->getFalseExpr(); 13707 continue; 13708 } 13709 return false; 13710 } 13711 13712 case Stmt::BinaryOperatorClass: { 13713 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13714 if (BO->getOpcode() == BO_Comma) { 13715 TypeExpr = BO->getRHS(); 13716 continue; 13717 } 13718 return false; 13719 } 13720 13721 default: 13722 return false; 13723 } 13724 } 13725 } 13726 13727 /// Retrieve the C type corresponding to type tag TypeExpr. 13728 /// 13729 /// \param TypeExpr Expression that specifies a type tag. 13730 /// 13731 /// \param MagicValues Registered magic values. 13732 /// 13733 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13734 /// kind. 13735 /// 13736 /// \param TypeInfo Information about the corresponding C type. 13737 /// 13738 /// \returns true if the corresponding C type was found. 13739 static bool GetMatchingCType( 13740 const IdentifierInfo *ArgumentKind, 13741 const Expr *TypeExpr, const ASTContext &Ctx, 13742 const llvm::DenseMap<Sema::TypeTagMagicValue, 13743 Sema::TypeTagData> *MagicValues, 13744 bool &FoundWrongKind, 13745 Sema::TypeTagData &TypeInfo) { 13746 FoundWrongKind = false; 13747 13748 // Variable declaration that has type_tag_for_datatype attribute. 13749 const ValueDecl *VD = nullptr; 13750 13751 uint64_t MagicValue; 13752 13753 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue)) 13754 return false; 13755 13756 if (VD) { 13757 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 13758 if (I->getArgumentKind() != ArgumentKind) { 13759 FoundWrongKind = true; 13760 return false; 13761 } 13762 TypeInfo.Type = I->getMatchingCType(); 13763 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 13764 TypeInfo.MustBeNull = I->getMustBeNull(); 13765 return true; 13766 } 13767 return false; 13768 } 13769 13770 if (!MagicValues) 13771 return false; 13772 13773 llvm::DenseMap<Sema::TypeTagMagicValue, 13774 Sema::TypeTagData>::const_iterator I = 13775 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 13776 if (I == MagicValues->end()) 13777 return false; 13778 13779 TypeInfo = I->second; 13780 return true; 13781 } 13782 13783 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 13784 uint64_t MagicValue, QualType Type, 13785 bool LayoutCompatible, 13786 bool MustBeNull) { 13787 if (!TypeTagForDatatypeMagicValues) 13788 TypeTagForDatatypeMagicValues.reset( 13789 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 13790 13791 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 13792 (*TypeTagForDatatypeMagicValues)[Magic] = 13793 TypeTagData(Type, LayoutCompatible, MustBeNull); 13794 } 13795 13796 static bool IsSameCharType(QualType T1, QualType T2) { 13797 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 13798 if (!BT1) 13799 return false; 13800 13801 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 13802 if (!BT2) 13803 return false; 13804 13805 BuiltinType::Kind T1Kind = BT1->getKind(); 13806 BuiltinType::Kind T2Kind = BT2->getKind(); 13807 13808 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 13809 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 13810 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 13811 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 13812 } 13813 13814 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 13815 const ArrayRef<const Expr *> ExprArgs, 13816 SourceLocation CallSiteLoc) { 13817 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 13818 bool IsPointerAttr = Attr->getIsPointer(); 13819 13820 // Retrieve the argument representing the 'type_tag'. 13821 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 13822 if (TypeTagIdxAST >= ExprArgs.size()) { 13823 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13824 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 13825 return; 13826 } 13827 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 13828 bool FoundWrongKind; 13829 TypeTagData TypeInfo; 13830 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 13831 TypeTagForDatatypeMagicValues.get(), 13832 FoundWrongKind, TypeInfo)) { 13833 if (FoundWrongKind) 13834 Diag(TypeTagExpr->getExprLoc(), 13835 diag::warn_type_tag_for_datatype_wrong_kind) 13836 << TypeTagExpr->getSourceRange(); 13837 return; 13838 } 13839 13840 // Retrieve the argument representing the 'arg_idx'. 13841 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 13842 if (ArgumentIdxAST >= ExprArgs.size()) { 13843 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 13844 << 1 << Attr->getArgumentIdx().getSourceIndex(); 13845 return; 13846 } 13847 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 13848 if (IsPointerAttr) { 13849 // Skip implicit cast of pointer to `void *' (as a function argument). 13850 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 13851 if (ICE->getType()->isVoidPointerType() && 13852 ICE->getCastKind() == CK_BitCast) 13853 ArgumentExpr = ICE->getSubExpr(); 13854 } 13855 QualType ArgumentType = ArgumentExpr->getType(); 13856 13857 // Passing a `void*' pointer shouldn't trigger a warning. 13858 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 13859 return; 13860 13861 if (TypeInfo.MustBeNull) { 13862 // Type tag with matching void type requires a null pointer. 13863 if (!ArgumentExpr->isNullPointerConstant(Context, 13864 Expr::NPC_ValueDependentIsNotNull)) { 13865 Diag(ArgumentExpr->getExprLoc(), 13866 diag::warn_type_safety_null_pointer_required) 13867 << ArgumentKind->getName() 13868 << ArgumentExpr->getSourceRange() 13869 << TypeTagExpr->getSourceRange(); 13870 } 13871 return; 13872 } 13873 13874 QualType RequiredType = TypeInfo.Type; 13875 if (IsPointerAttr) 13876 RequiredType = Context.getPointerType(RequiredType); 13877 13878 bool mismatch = false; 13879 if (!TypeInfo.LayoutCompatible) { 13880 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 13881 13882 // C++11 [basic.fundamental] p1: 13883 // Plain char, signed char, and unsigned char are three distinct types. 13884 // 13885 // But we treat plain `char' as equivalent to `signed char' or `unsigned 13886 // char' depending on the current char signedness mode. 13887 if (mismatch) 13888 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 13889 RequiredType->getPointeeType())) || 13890 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 13891 mismatch = false; 13892 } else 13893 if (IsPointerAttr) 13894 mismatch = !isLayoutCompatible(Context, 13895 ArgumentType->getPointeeType(), 13896 RequiredType->getPointeeType()); 13897 else 13898 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 13899 13900 if (mismatch) 13901 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 13902 << ArgumentType << ArgumentKind 13903 << TypeInfo.LayoutCompatible << RequiredType 13904 << ArgumentExpr->getSourceRange() 13905 << TypeTagExpr->getSourceRange(); 13906 } 13907 13908 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 13909 CharUnits Alignment) { 13910 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 13911 } 13912 13913 void Sema::DiagnoseMisalignedMembers() { 13914 for (MisalignedMember &m : MisalignedMembers) { 13915 const NamedDecl *ND = m.RD; 13916 if (ND->getName().empty()) { 13917 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 13918 ND = TD; 13919 } 13920 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 13921 << m.MD << ND << m.E->getSourceRange(); 13922 } 13923 MisalignedMembers.clear(); 13924 } 13925 13926 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 13927 E = E->IgnoreParens(); 13928 if (!T->isPointerType() && !T->isIntegerType()) 13929 return; 13930 if (isa<UnaryOperator>(E) && 13931 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 13932 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 13933 if (isa<MemberExpr>(Op)) { 13934 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 13935 if (MA != MisalignedMembers.end() && 13936 (T->isIntegerType() || 13937 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 13938 Context.getTypeAlignInChars( 13939 T->getPointeeType()) <= MA->Alignment)))) 13940 MisalignedMembers.erase(MA); 13941 } 13942 } 13943 } 13944 13945 void Sema::RefersToMemberWithReducedAlignment( 13946 Expr *E, 13947 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 13948 Action) { 13949 const auto *ME = dyn_cast<MemberExpr>(E); 13950 if (!ME) 13951 return; 13952 13953 // No need to check expressions with an __unaligned-qualified type. 13954 if (E->getType().getQualifiers().hasUnaligned()) 13955 return; 13956 13957 // For a chain of MemberExpr like "a.b.c.d" this list 13958 // will keep FieldDecl's like [d, c, b]. 13959 SmallVector<FieldDecl *, 4> ReverseMemberChain; 13960 const MemberExpr *TopME = nullptr; 13961 bool AnyIsPacked = false; 13962 do { 13963 QualType BaseType = ME->getBase()->getType(); 13964 if (ME->isArrow()) 13965 BaseType = BaseType->getPointeeType(); 13966 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 13967 if (RD->isInvalidDecl()) 13968 return; 13969 13970 ValueDecl *MD = ME->getMemberDecl(); 13971 auto *FD = dyn_cast<FieldDecl>(MD); 13972 // We do not care about non-data members. 13973 if (!FD || FD->isInvalidDecl()) 13974 return; 13975 13976 AnyIsPacked = 13977 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 13978 ReverseMemberChain.push_back(FD); 13979 13980 TopME = ME; 13981 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 13982 } while (ME); 13983 assert(TopME && "We did not compute a topmost MemberExpr!"); 13984 13985 // Not the scope of this diagnostic. 13986 if (!AnyIsPacked) 13987 return; 13988 13989 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 13990 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 13991 // TODO: The innermost base of the member expression may be too complicated. 13992 // For now, just disregard these cases. This is left for future 13993 // improvement. 13994 if (!DRE && !isa<CXXThisExpr>(TopBase)) 13995 return; 13996 13997 // Alignment expected by the whole expression. 13998 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 13999 14000 // No need to do anything else with this case. 14001 if (ExpectedAlignment.isOne()) 14002 return; 14003 14004 // Synthesize offset of the whole access. 14005 CharUnits Offset; 14006 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14007 I++) { 14008 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14009 } 14010 14011 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14012 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14013 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14014 14015 // The base expression of the innermost MemberExpr may give 14016 // stronger guarantees than the class containing the member. 14017 if (DRE && !TopME->isArrow()) { 14018 const ValueDecl *VD = DRE->getDecl(); 14019 if (!VD->getType()->isReferenceType()) 14020 CompleteObjectAlignment = 14021 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14022 } 14023 14024 // Check if the synthesized offset fulfills the alignment. 14025 if (Offset % ExpectedAlignment != 0 || 14026 // It may fulfill the offset it but the effective alignment may still be 14027 // lower than the expected expression alignment. 14028 CompleteObjectAlignment < ExpectedAlignment) { 14029 // If this happens, we want to determine a sensible culprit of this. 14030 // Intuitively, watching the chain of member expressions from right to 14031 // left, we start with the required alignment (as required by the field 14032 // type) but some packed attribute in that chain has reduced the alignment. 14033 // It may happen that another packed structure increases it again. But if 14034 // we are here such increase has not been enough. So pointing the first 14035 // FieldDecl that either is packed or else its RecordDecl is, 14036 // seems reasonable. 14037 FieldDecl *FD = nullptr; 14038 CharUnits Alignment; 14039 for (FieldDecl *FDI : ReverseMemberChain) { 14040 if (FDI->hasAttr<PackedAttr>() || 14041 FDI->getParent()->hasAttr<PackedAttr>()) { 14042 FD = FDI; 14043 Alignment = std::min( 14044 Context.getTypeAlignInChars(FD->getType()), 14045 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14046 break; 14047 } 14048 } 14049 assert(FD && "We did not find a packed FieldDecl!"); 14050 Action(E, FD->getParent(), FD, Alignment); 14051 } 14052 } 14053 14054 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14055 using namespace std::placeholders; 14056 14057 RefersToMemberWithReducedAlignment( 14058 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14059 _2, _3, _4)); 14060 } 14061