1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/SaveAndRestore.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 121 call->getArg(argCount - 1)->getEndLoc()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 /// Check the number of arguments and set the result type to 195 /// the argument type. 196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 197 if (checkArgCount(S, TheCall, 1)) 198 return true; 199 200 TheCall->setType(TheCall->getArg(0)->getType()); 201 return false; 202 } 203 204 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 205 if (checkArgCount(S, TheCall, 3)) 206 return true; 207 208 // First two arguments should be integers. 209 for (unsigned I = 0; I < 2; ++I) { 210 ExprResult Arg = TheCall->getArg(I); 211 QualType Ty = Arg.get()->getType(); 212 if (!Ty->isIntegerType()) { 213 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 214 << Ty << Arg.get()->getSourceRange(); 215 return true; 216 } 217 InitializedEntity Entity = InitializedEntity::InitializeParameter( 218 S.getASTContext(), Ty, /*consume*/ false); 219 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 220 if (Arg.isInvalid()) 221 return true; 222 TheCall->setArg(I, Arg.get()); 223 } 224 225 // Third argument should be a pointer to a non-const integer. 226 // IRGen correctly handles volatile, restrict, and address spaces, and 227 // the other qualifiers aren't possible. 228 { 229 ExprResult Arg = TheCall->getArg(2); 230 QualType Ty = Arg.get()->getType(); 231 const auto *PtrTy = Ty->getAs<PointerType>(); 232 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 233 !PtrTy->getPointeeType().isConstQualified())) { 234 S.Diag(Arg.get()->getBeginLoc(), 235 diag::err_overflow_builtin_must_be_ptr_int) 236 << Ty << Arg.get()->getSourceRange(); 237 return true; 238 } 239 InitializedEntity Entity = InitializedEntity::InitializeParameter( 240 S.getASTContext(), Ty, /*consume*/ false); 241 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 242 if (Arg.isInvalid()) 243 return true; 244 TheCall->setArg(2, Arg.get()); 245 } 246 return false; 247 } 248 249 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 250 if (checkArgCount(S, BuiltinCall, 2)) 251 return true; 252 253 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 254 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 255 Expr *Call = BuiltinCall->getArg(0); 256 Expr *Chain = BuiltinCall->getArg(1); 257 258 if (Call->getStmtClass() != Stmt::CallExprClass) { 259 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 260 << Call->getSourceRange(); 261 return true; 262 } 263 264 auto CE = cast<CallExpr>(Call); 265 if (CE->getCallee()->getType()->isBlockPointerType()) { 266 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 267 << Call->getSourceRange(); 268 return true; 269 } 270 271 const Decl *TargetDecl = CE->getCalleeDecl(); 272 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 273 if (FD->getBuiltinID()) { 274 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 275 << Call->getSourceRange(); 276 return true; 277 } 278 279 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 281 << Call->getSourceRange(); 282 return true; 283 } 284 285 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 286 if (ChainResult.isInvalid()) 287 return true; 288 if (!ChainResult.get()->getType()->isPointerType()) { 289 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 290 << Chain->getSourceRange(); 291 return true; 292 } 293 294 QualType ReturnTy = CE->getCallReturnType(S.Context); 295 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 296 QualType BuiltinTy = S.Context.getFunctionType( 297 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 298 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 299 300 Builtin = 301 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 302 303 BuiltinCall->setType(CE->getType()); 304 BuiltinCall->setValueKind(CE->getValueKind()); 305 BuiltinCall->setObjectKind(CE->getObjectKind()); 306 BuiltinCall->setCallee(Builtin); 307 BuiltinCall->setArg(1, ChainResult.get()); 308 309 return false; 310 } 311 312 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 313 /// __builtin_*_chk function, then use the object size argument specified in the 314 /// source. Otherwise, infer the object size using __builtin_object_size. 315 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 316 CallExpr *TheCall) { 317 // FIXME: There are some more useful checks we could be doing here: 318 // - Analyze the format string of sprintf to see how much of buffer is used. 319 // - Evaluate strlen of strcpy arguments, use as object size. 320 321 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 322 isConstantEvaluated()) 323 return; 324 325 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 326 if (!BuiltinID) 327 return; 328 329 unsigned DiagID = 0; 330 bool IsChkVariant = false; 331 unsigned SizeIndex, ObjectIndex; 332 switch (BuiltinID) { 333 default: 334 return; 335 case Builtin::BI__builtin___memcpy_chk: 336 case Builtin::BI__builtin___memmove_chk: 337 case Builtin::BI__builtin___memset_chk: 338 case Builtin::BI__builtin___strlcat_chk: 339 case Builtin::BI__builtin___strlcpy_chk: 340 case Builtin::BI__builtin___strncat_chk: 341 case Builtin::BI__builtin___strncpy_chk: 342 case Builtin::BI__builtin___stpncpy_chk: 343 case Builtin::BI__builtin___memccpy_chk: { 344 DiagID = diag::warn_builtin_chk_overflow; 345 IsChkVariant = true; 346 SizeIndex = TheCall->getNumArgs() - 2; 347 ObjectIndex = TheCall->getNumArgs() - 1; 348 break; 349 } 350 351 case Builtin::BI__builtin___snprintf_chk: 352 case Builtin::BI__builtin___vsnprintf_chk: { 353 DiagID = diag::warn_builtin_chk_overflow; 354 IsChkVariant = true; 355 SizeIndex = 1; 356 ObjectIndex = 3; 357 break; 358 } 359 360 case Builtin::BIstrncat: 361 case Builtin::BI__builtin_strncat: 362 case Builtin::BIstrncpy: 363 case Builtin::BI__builtin_strncpy: 364 case Builtin::BIstpncpy: 365 case Builtin::BI__builtin_stpncpy: { 366 // Whether these functions overflow depends on the runtime strlen of the 367 // string, not just the buffer size, so emitting the "always overflow" 368 // diagnostic isn't quite right. We should still diagnose passing a buffer 369 // size larger than the destination buffer though; this is a runtime abort 370 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 371 DiagID = diag::warn_fortify_source_size_mismatch; 372 SizeIndex = TheCall->getNumArgs() - 1; 373 ObjectIndex = 0; 374 break; 375 } 376 377 case Builtin::BImemcpy: 378 case Builtin::BI__builtin_memcpy: 379 case Builtin::BImemmove: 380 case Builtin::BI__builtin_memmove: 381 case Builtin::BImemset: 382 case Builtin::BI__builtin_memset: { 383 DiagID = diag::warn_fortify_source_overflow; 384 SizeIndex = TheCall->getNumArgs() - 1; 385 ObjectIndex = 0; 386 break; 387 } 388 case Builtin::BIsnprintf: 389 case Builtin::BI__builtin_snprintf: 390 case Builtin::BIvsnprintf: 391 case Builtin::BI__builtin_vsnprintf: { 392 DiagID = diag::warn_fortify_source_size_mismatch; 393 SizeIndex = 1; 394 ObjectIndex = 0; 395 break; 396 } 397 } 398 399 llvm::APSInt ObjectSize; 400 // For __builtin___*_chk, the object size is explicitly provided by the caller 401 // (usually using __builtin_object_size). Use that value to check this call. 402 if (IsChkVariant) { 403 Expr::EvalResult Result; 404 Expr *SizeArg = TheCall->getArg(ObjectIndex); 405 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 406 return; 407 ObjectSize = Result.Val.getInt(); 408 409 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 410 } else { 411 // If the parameter has a pass_object_size attribute, then we should use its 412 // (potentially) more strict checking mode. Otherwise, conservatively assume 413 // type 0. 414 int BOSType = 0; 415 if (const auto *POS = 416 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 417 BOSType = POS->getType(); 418 419 Expr *ObjArg = TheCall->getArg(ObjectIndex); 420 uint64_t Result; 421 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 422 return; 423 // Get the object size in the target's size_t width. 424 const TargetInfo &TI = getASTContext().getTargetInfo(); 425 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 426 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 427 } 428 429 // Evaluate the number of bytes of the object that this call will use. 430 Expr::EvalResult Result; 431 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 432 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 433 return; 434 llvm::APSInt UsedSize = Result.Val.getInt(); 435 436 if (UsedSize.ule(ObjectSize)) 437 return; 438 439 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 440 // Skim off the details of whichever builtin was called to produce a better 441 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 442 if (IsChkVariant) { 443 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 444 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 445 } else if (FunctionName.startswith("__builtin_")) { 446 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 447 } 448 449 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 450 PDiag(DiagID) 451 << FunctionName << ObjectSize.toString(/*Radix=*/10) 452 << UsedSize.toString(/*Radix=*/10)); 453 } 454 455 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 456 Scope::ScopeFlags NeededScopeFlags, 457 unsigned DiagID) { 458 // Scopes aren't available during instantiation. Fortunately, builtin 459 // functions cannot be template args so they cannot be formed through template 460 // instantiation. Therefore checking once during the parse is sufficient. 461 if (SemaRef.inTemplateInstantiation()) 462 return false; 463 464 Scope *S = SemaRef.getCurScope(); 465 while (S && !S->isSEHExceptScope()) 466 S = S->getParent(); 467 if (!S || !(S->getFlags() & NeededScopeFlags)) { 468 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 469 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 470 << DRE->getDecl()->getIdentifier(); 471 return true; 472 } 473 474 return false; 475 } 476 477 static inline bool isBlockPointer(Expr *Arg) { 478 return Arg->getType()->isBlockPointerType(); 479 } 480 481 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 482 /// void*, which is a requirement of device side enqueue. 483 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 484 const BlockPointerType *BPT = 485 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 486 ArrayRef<QualType> Params = 487 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 488 unsigned ArgCounter = 0; 489 bool IllegalParams = false; 490 // Iterate through the block parameters until either one is found that is not 491 // a local void*, or the block is valid. 492 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 493 I != E; ++I, ++ArgCounter) { 494 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 495 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 496 LangAS::opencl_local) { 497 // Get the location of the error. If a block literal has been passed 498 // (BlockExpr) then we can point straight to the offending argument, 499 // else we just point to the variable reference. 500 SourceLocation ErrorLoc; 501 if (isa<BlockExpr>(BlockArg)) { 502 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 503 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 504 } else if (isa<DeclRefExpr>(BlockArg)) { 505 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 506 } 507 S.Diag(ErrorLoc, 508 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 509 IllegalParams = true; 510 } 511 } 512 513 return IllegalParams; 514 } 515 516 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 517 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 518 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 519 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 520 return true; 521 } 522 return false; 523 } 524 525 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 526 if (checkArgCount(S, TheCall, 2)) 527 return true; 528 529 if (checkOpenCLSubgroupExt(S, TheCall)) 530 return true; 531 532 // First argument is an ndrange_t type. 533 Expr *NDRangeArg = TheCall->getArg(0); 534 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 535 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 536 << TheCall->getDirectCallee() << "'ndrange_t'"; 537 return true; 538 } 539 540 Expr *BlockArg = TheCall->getArg(1); 541 if (!isBlockPointer(BlockArg)) { 542 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 543 << TheCall->getDirectCallee() << "block"; 544 return true; 545 } 546 return checkOpenCLBlockArgs(S, BlockArg); 547 } 548 549 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 550 /// get_kernel_work_group_size 551 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 552 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 553 if (checkArgCount(S, TheCall, 1)) 554 return true; 555 556 Expr *BlockArg = TheCall->getArg(0); 557 if (!isBlockPointer(BlockArg)) { 558 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 559 << TheCall->getDirectCallee() << "block"; 560 return true; 561 } 562 return checkOpenCLBlockArgs(S, BlockArg); 563 } 564 565 /// Diagnose integer type and any valid implicit conversion to it. 566 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 567 const QualType &IntType); 568 569 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 570 unsigned Start, unsigned End) { 571 bool IllegalParams = false; 572 for (unsigned I = Start; I <= End; ++I) 573 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 574 S.Context.getSizeType()); 575 return IllegalParams; 576 } 577 578 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 579 /// 'local void*' parameter of passed block. 580 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 581 Expr *BlockArg, 582 unsigned NumNonVarArgs) { 583 const BlockPointerType *BPT = 584 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 585 unsigned NumBlockParams = 586 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 587 unsigned TotalNumArgs = TheCall->getNumArgs(); 588 589 // For each argument passed to the block, a corresponding uint needs to 590 // be passed to describe the size of the local memory. 591 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 592 S.Diag(TheCall->getBeginLoc(), 593 diag::err_opencl_enqueue_kernel_local_size_args); 594 return true; 595 } 596 597 // Check that the sizes of the local memory are specified by integers. 598 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 599 TotalNumArgs - 1); 600 } 601 602 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 603 /// overload formats specified in Table 6.13.17.1. 604 /// int enqueue_kernel(queue_t queue, 605 /// kernel_enqueue_flags_t flags, 606 /// const ndrange_t ndrange, 607 /// void (^block)(void)) 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)(void)) 615 /// int enqueue_kernel(queue_t queue, 616 /// kernel_enqueue_flags_t flags, 617 /// const ndrange_t ndrange, 618 /// void (^block)(local void*, ...), 619 /// uint size0, ...) 620 /// int enqueue_kernel(queue_t queue, 621 /// kernel_enqueue_flags_t flags, 622 /// const ndrange_t ndrange, 623 /// uint num_events_in_wait_list, 624 /// clk_event_t *event_wait_list, 625 /// clk_event_t *event_ret, 626 /// void (^block)(local void*, ...), 627 /// uint size0, ...) 628 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 629 unsigned NumArgs = TheCall->getNumArgs(); 630 631 if (NumArgs < 4) { 632 S.Diag(TheCall->getBeginLoc(), 633 diag::err_typecheck_call_too_few_args_at_least) 634 << 0 << 4 << NumArgs; 635 return true; 636 } 637 638 Expr *Arg0 = TheCall->getArg(0); 639 Expr *Arg1 = TheCall->getArg(1); 640 Expr *Arg2 = TheCall->getArg(2); 641 Expr *Arg3 = TheCall->getArg(3); 642 643 // First argument always needs to be a queue_t type. 644 if (!Arg0->getType()->isQueueT()) { 645 S.Diag(TheCall->getArg(0)->getBeginLoc(), 646 diag::err_opencl_builtin_expected_type) 647 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 648 return true; 649 } 650 651 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 652 if (!Arg1->getType()->isIntegerType()) { 653 S.Diag(TheCall->getArg(1)->getBeginLoc(), 654 diag::err_opencl_builtin_expected_type) 655 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 656 return true; 657 } 658 659 // Third argument is always an ndrange_t type. 660 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 661 S.Diag(TheCall->getArg(2)->getBeginLoc(), 662 diag::err_opencl_builtin_expected_type) 663 << TheCall->getDirectCallee() << "'ndrange_t'"; 664 return true; 665 } 666 667 // With four arguments, there is only one form that the function could be 668 // called in: no events and no variable arguments. 669 if (NumArgs == 4) { 670 // check that the last argument is the right block type. 671 if (!isBlockPointer(Arg3)) { 672 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 673 << TheCall->getDirectCallee() << "block"; 674 return true; 675 } 676 // we have a block type, check the prototype 677 const BlockPointerType *BPT = 678 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 679 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 680 S.Diag(Arg3->getBeginLoc(), 681 diag::err_opencl_enqueue_kernel_blocks_no_args); 682 return true; 683 } 684 return false; 685 } 686 // we can have block + varargs. 687 if (isBlockPointer(Arg3)) 688 return (checkOpenCLBlockArgs(S, Arg3) || 689 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 690 // last two cases with either exactly 7 args or 7 args and varargs. 691 if (NumArgs >= 7) { 692 // check common block argument. 693 Expr *Arg6 = TheCall->getArg(6); 694 if (!isBlockPointer(Arg6)) { 695 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 696 << TheCall->getDirectCallee() << "block"; 697 return true; 698 } 699 if (checkOpenCLBlockArgs(S, Arg6)) 700 return true; 701 702 // Forth argument has to be any integer type. 703 if (!Arg3->getType()->isIntegerType()) { 704 S.Diag(TheCall->getArg(3)->getBeginLoc(), 705 diag::err_opencl_builtin_expected_type) 706 << TheCall->getDirectCallee() << "integer"; 707 return true; 708 } 709 // check remaining common arguments. 710 Expr *Arg4 = TheCall->getArg(4); 711 Expr *Arg5 = TheCall->getArg(5); 712 713 // Fifth argument is always passed as a pointer to clk_event_t. 714 if (!Arg4->isNullPointerConstant(S.Context, 715 Expr::NPC_ValueDependentIsNotNull) && 716 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 717 S.Diag(TheCall->getArg(4)->getBeginLoc(), 718 diag::err_opencl_builtin_expected_type) 719 << TheCall->getDirectCallee() 720 << S.Context.getPointerType(S.Context.OCLClkEventTy); 721 return true; 722 } 723 724 // Sixth argument is always passed as a pointer to clk_event_t. 725 if (!Arg5->isNullPointerConstant(S.Context, 726 Expr::NPC_ValueDependentIsNotNull) && 727 !(Arg5->getType()->isPointerType() && 728 Arg5->getType()->getPointeeType()->isClkEventT())) { 729 S.Diag(TheCall->getArg(5)->getBeginLoc(), 730 diag::err_opencl_builtin_expected_type) 731 << TheCall->getDirectCallee() 732 << S.Context.getPointerType(S.Context.OCLClkEventTy); 733 return true; 734 } 735 736 if (NumArgs == 7) 737 return false; 738 739 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 740 } 741 742 // None of the specific case has been detected, give generic error 743 S.Diag(TheCall->getBeginLoc(), 744 diag::err_opencl_enqueue_kernel_incorrect_args); 745 return true; 746 } 747 748 /// Returns OpenCL access qual. 749 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 750 return D->getAttr<OpenCLAccessAttr>(); 751 } 752 753 /// Returns true if pipe element type is different from the pointer. 754 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 755 const Expr *Arg0 = Call->getArg(0); 756 // First argument type should always be pipe. 757 if (!Arg0->getType()->isPipeType()) { 758 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 759 << Call->getDirectCallee() << Arg0->getSourceRange(); 760 return true; 761 } 762 OpenCLAccessAttr *AccessQual = 763 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 764 // Validates the access qualifier is compatible with the call. 765 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 766 // read_only and write_only, and assumed to be read_only if no qualifier is 767 // specified. 768 switch (Call->getDirectCallee()->getBuiltinID()) { 769 case Builtin::BIread_pipe: 770 case Builtin::BIreserve_read_pipe: 771 case Builtin::BIcommit_read_pipe: 772 case Builtin::BIwork_group_reserve_read_pipe: 773 case Builtin::BIsub_group_reserve_read_pipe: 774 case Builtin::BIwork_group_commit_read_pipe: 775 case Builtin::BIsub_group_commit_read_pipe: 776 if (!(!AccessQual || AccessQual->isReadOnly())) { 777 S.Diag(Arg0->getBeginLoc(), 778 diag::err_opencl_builtin_pipe_invalid_access_modifier) 779 << "read_only" << Arg0->getSourceRange(); 780 return true; 781 } 782 break; 783 case Builtin::BIwrite_pipe: 784 case Builtin::BIreserve_write_pipe: 785 case Builtin::BIcommit_write_pipe: 786 case Builtin::BIwork_group_reserve_write_pipe: 787 case Builtin::BIsub_group_reserve_write_pipe: 788 case Builtin::BIwork_group_commit_write_pipe: 789 case Builtin::BIsub_group_commit_write_pipe: 790 if (!(AccessQual && AccessQual->isWriteOnly())) { 791 S.Diag(Arg0->getBeginLoc(), 792 diag::err_opencl_builtin_pipe_invalid_access_modifier) 793 << "write_only" << Arg0->getSourceRange(); 794 return true; 795 } 796 break; 797 default: 798 break; 799 } 800 return false; 801 } 802 803 /// Returns true if pipe element type is different from the pointer. 804 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 805 const Expr *Arg0 = Call->getArg(0); 806 const Expr *ArgIdx = Call->getArg(Idx); 807 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 808 const QualType EltTy = PipeTy->getElementType(); 809 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 810 // The Idx argument should be a pointer and the type of the pointer and 811 // the type of pipe element should also be the same. 812 if (!ArgTy || 813 !S.Context.hasSameType( 814 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 815 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 816 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 817 << ArgIdx->getType() << ArgIdx->getSourceRange(); 818 return true; 819 } 820 return false; 821 } 822 823 // Performs semantic analysis for the read/write_pipe call. 824 // \param S Reference to the semantic analyzer. 825 // \param Call A pointer to the builtin call. 826 // \return True if a semantic error has been found, false otherwise. 827 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 828 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 829 // functions have two forms. 830 switch (Call->getNumArgs()) { 831 case 2: 832 if (checkOpenCLPipeArg(S, Call)) 833 return true; 834 // The call with 2 arguments should be 835 // read/write_pipe(pipe T, T*). 836 // Check packet type T. 837 if (checkOpenCLPipePacketType(S, Call, 1)) 838 return true; 839 break; 840 841 case 4: { 842 if (checkOpenCLPipeArg(S, Call)) 843 return true; 844 // The call with 4 arguments should be 845 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 846 // Check reserve_id_t. 847 if (!Call->getArg(1)->getType()->isReserveIDT()) { 848 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 849 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 850 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 851 return true; 852 } 853 854 // Check the index. 855 const Expr *Arg2 = Call->getArg(2); 856 if (!Arg2->getType()->isIntegerType() && 857 !Arg2->getType()->isUnsignedIntegerType()) { 858 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 859 << Call->getDirectCallee() << S.Context.UnsignedIntTy 860 << Arg2->getType() << Arg2->getSourceRange(); 861 return true; 862 } 863 864 // Check packet type T. 865 if (checkOpenCLPipePacketType(S, Call, 3)) 866 return true; 867 } break; 868 default: 869 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 870 << Call->getDirectCallee() << Call->getSourceRange(); 871 return true; 872 } 873 874 return false; 875 } 876 877 // Performs a semantic analysis on the {work_group_/sub_group_ 878 // /_}reserve_{read/write}_pipe 879 // \param S Reference to the semantic analyzer. 880 // \param Call The call to the builtin function to be analyzed. 881 // \return True if a semantic error was found, false otherwise. 882 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 883 if (checkArgCount(S, Call, 2)) 884 return true; 885 886 if (checkOpenCLPipeArg(S, Call)) 887 return true; 888 889 // Check the reserve size. 890 if (!Call->getArg(1)->getType()->isIntegerType() && 891 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 892 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 893 << Call->getDirectCallee() << S.Context.UnsignedIntTy 894 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 895 return true; 896 } 897 898 // Since return type of reserve_read/write_pipe built-in function is 899 // reserve_id_t, which is not defined in the builtin def file , we used int 900 // as return type and need to override the return type of these functions. 901 Call->setType(S.Context.OCLReserveIDTy); 902 903 return false; 904 } 905 906 // Performs a semantic analysis on {work_group_/sub_group_ 907 // /_}commit_{read/write}_pipe 908 // \param S Reference to the semantic analyzer. 909 // \param Call The call to the builtin function to be analyzed. 910 // \return True if a semantic error was found, false otherwise. 911 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 912 if (checkArgCount(S, Call, 2)) 913 return true; 914 915 if (checkOpenCLPipeArg(S, Call)) 916 return true; 917 918 // Check reserve_id_t. 919 if (!Call->getArg(1)->getType()->isReserveIDT()) { 920 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 921 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 922 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 923 return true; 924 } 925 926 return false; 927 } 928 929 // Performs a semantic analysis on the call to built-in Pipe 930 // Query Functions. 931 // \param S Reference to the semantic analyzer. 932 // \param Call The call to the builtin function to be analyzed. 933 // \return True if a semantic error was found, false otherwise. 934 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 935 if (checkArgCount(S, Call, 1)) 936 return true; 937 938 if (!Call->getArg(0)->getType()->isPipeType()) { 939 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 940 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 941 return true; 942 } 943 944 return false; 945 } 946 947 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 948 // Performs semantic analysis for the to_global/local/private call. 949 // \param S Reference to the semantic analyzer. 950 // \param BuiltinID ID of the builtin function. 951 // \param Call A pointer to the builtin call. 952 // \return True if a semantic error has been found, false otherwise. 953 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 954 CallExpr *Call) { 955 if (Call->getNumArgs() != 1) { 956 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 957 << Call->getDirectCallee() << Call->getSourceRange(); 958 return true; 959 } 960 961 auto RT = Call->getArg(0)->getType(); 962 if (!RT->isPointerType() || RT->getPointeeType() 963 .getAddressSpace() == LangAS::opencl_constant) { 964 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 965 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 966 return true; 967 } 968 969 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 970 S.Diag(Call->getArg(0)->getBeginLoc(), 971 diag::warn_opencl_generic_address_space_arg) 972 << Call->getDirectCallee()->getNameInfo().getAsString() 973 << Call->getArg(0)->getSourceRange(); 974 } 975 976 RT = RT->getPointeeType(); 977 auto Qual = RT.getQualifiers(); 978 switch (BuiltinID) { 979 case Builtin::BIto_global: 980 Qual.setAddressSpace(LangAS::opencl_global); 981 break; 982 case Builtin::BIto_local: 983 Qual.setAddressSpace(LangAS::opencl_local); 984 break; 985 case Builtin::BIto_private: 986 Qual.setAddressSpace(LangAS::opencl_private); 987 break; 988 default: 989 llvm_unreachable("Invalid builtin function"); 990 } 991 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 992 RT.getUnqualifiedType(), Qual))); 993 994 return false; 995 } 996 997 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 998 if (checkArgCount(S, TheCall, 1)) 999 return ExprError(); 1000 1001 // Compute __builtin_launder's parameter type from the argument. 1002 // The parameter type is: 1003 // * The type of the argument if it's not an array or function type, 1004 // Otherwise, 1005 // * The decayed argument type. 1006 QualType ParamTy = [&]() { 1007 QualType ArgTy = TheCall->getArg(0)->getType(); 1008 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1009 return S.Context.getPointerType(Ty->getElementType()); 1010 if (ArgTy->isFunctionType()) { 1011 return S.Context.getPointerType(ArgTy); 1012 } 1013 return ArgTy; 1014 }(); 1015 1016 TheCall->setType(ParamTy); 1017 1018 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1019 if (!ParamTy->isPointerType()) 1020 return 0; 1021 if (ParamTy->isFunctionPointerType()) 1022 return 1; 1023 if (ParamTy->isVoidPointerType()) 1024 return 2; 1025 return llvm::Optional<unsigned>{}; 1026 }(); 1027 if (DiagSelect.hasValue()) { 1028 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1029 << DiagSelect.getValue() << TheCall->getSourceRange(); 1030 return ExprError(); 1031 } 1032 1033 // We either have an incomplete class type, or we have a class template 1034 // whose instantiation has not been forced. Example: 1035 // 1036 // template <class T> struct Foo { T value; }; 1037 // Foo<int> *p = nullptr; 1038 // auto *d = __builtin_launder(p); 1039 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1040 diag::err_incomplete_type)) 1041 return ExprError(); 1042 1043 assert(ParamTy->getPointeeType()->isObjectType() && 1044 "Unhandled non-object pointer case"); 1045 1046 InitializedEntity Entity = 1047 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1048 ExprResult Arg = 1049 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1050 if (Arg.isInvalid()) 1051 return ExprError(); 1052 TheCall->setArg(0, Arg.get()); 1053 1054 return TheCall; 1055 } 1056 1057 // Emit an error and return true if the current architecture is not in the list 1058 // of supported architectures. 1059 static bool 1060 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1061 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1062 llvm::Triple::ArchType CurArch = 1063 S.getASTContext().getTargetInfo().getTriple().getArch(); 1064 if (llvm::is_contained(SupportedArchs, CurArch)) 1065 return false; 1066 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1067 << TheCall->getSourceRange(); 1068 return true; 1069 } 1070 1071 ExprResult 1072 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1073 CallExpr *TheCall) { 1074 ExprResult TheCallResult(TheCall); 1075 1076 // Find out if any arguments are required to be integer constant expressions. 1077 unsigned ICEArguments = 0; 1078 ASTContext::GetBuiltinTypeError Error; 1079 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1080 if (Error != ASTContext::GE_None) 1081 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1082 1083 // If any arguments are required to be ICE's, check and diagnose. 1084 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1085 // Skip arguments not required to be ICE's. 1086 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1087 1088 llvm::APSInt Result; 1089 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1090 return true; 1091 ICEArguments &= ~(1 << ArgNo); 1092 } 1093 1094 switch (BuiltinID) { 1095 case Builtin::BI__builtin___CFStringMakeConstantString: 1096 assert(TheCall->getNumArgs() == 1 && 1097 "Wrong # arguments to builtin CFStringMakeConstantString"); 1098 if (CheckObjCString(TheCall->getArg(0))) 1099 return ExprError(); 1100 break; 1101 case Builtin::BI__builtin_ms_va_start: 1102 case Builtin::BI__builtin_stdarg_start: 1103 case Builtin::BI__builtin_va_start: 1104 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1105 return ExprError(); 1106 break; 1107 case Builtin::BI__va_start: { 1108 switch (Context.getTargetInfo().getTriple().getArch()) { 1109 case llvm::Triple::aarch64: 1110 case llvm::Triple::arm: 1111 case llvm::Triple::thumb: 1112 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1113 return ExprError(); 1114 break; 1115 default: 1116 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1117 return ExprError(); 1118 break; 1119 } 1120 break; 1121 } 1122 1123 // The acquire, release, and no fence variants are ARM and AArch64 only. 1124 case Builtin::BI_interlockedbittestandset_acq: 1125 case Builtin::BI_interlockedbittestandset_rel: 1126 case Builtin::BI_interlockedbittestandset_nf: 1127 case Builtin::BI_interlockedbittestandreset_acq: 1128 case Builtin::BI_interlockedbittestandreset_rel: 1129 case Builtin::BI_interlockedbittestandreset_nf: 1130 if (CheckBuiltinTargetSupport( 1131 *this, BuiltinID, TheCall, 1132 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1133 return ExprError(); 1134 break; 1135 1136 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1137 case Builtin::BI_bittest64: 1138 case Builtin::BI_bittestandcomplement64: 1139 case Builtin::BI_bittestandreset64: 1140 case Builtin::BI_bittestandset64: 1141 case Builtin::BI_interlockedbittestandreset64: 1142 case Builtin::BI_interlockedbittestandset64: 1143 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1144 {llvm::Triple::x86_64, llvm::Triple::arm, 1145 llvm::Triple::thumb, llvm::Triple::aarch64})) 1146 return ExprError(); 1147 break; 1148 1149 case Builtin::BI__builtin_isgreater: 1150 case Builtin::BI__builtin_isgreaterequal: 1151 case Builtin::BI__builtin_isless: 1152 case Builtin::BI__builtin_islessequal: 1153 case Builtin::BI__builtin_islessgreater: 1154 case Builtin::BI__builtin_isunordered: 1155 if (SemaBuiltinUnorderedCompare(TheCall)) 1156 return ExprError(); 1157 break; 1158 case Builtin::BI__builtin_fpclassify: 1159 if (SemaBuiltinFPClassification(TheCall, 6)) 1160 return ExprError(); 1161 break; 1162 case Builtin::BI__builtin_isfinite: 1163 case Builtin::BI__builtin_isinf: 1164 case Builtin::BI__builtin_isinf_sign: 1165 case Builtin::BI__builtin_isnan: 1166 case Builtin::BI__builtin_isnormal: 1167 case Builtin::BI__builtin_signbit: 1168 case Builtin::BI__builtin_signbitf: 1169 case Builtin::BI__builtin_signbitl: 1170 if (SemaBuiltinFPClassification(TheCall, 1)) 1171 return ExprError(); 1172 break; 1173 case Builtin::BI__builtin_shufflevector: 1174 return SemaBuiltinShuffleVector(TheCall); 1175 // TheCall will be freed by the smart pointer here, but that's fine, since 1176 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1177 case Builtin::BI__builtin_prefetch: 1178 if (SemaBuiltinPrefetch(TheCall)) 1179 return ExprError(); 1180 break; 1181 case Builtin::BI__builtin_alloca_with_align: 1182 if (SemaBuiltinAllocaWithAlign(TheCall)) 1183 return ExprError(); 1184 LLVM_FALLTHROUGH; 1185 case Builtin::BI__builtin_alloca: 1186 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1187 << TheCall->getDirectCallee(); 1188 break; 1189 case Builtin::BI__assume: 1190 case Builtin::BI__builtin_assume: 1191 if (SemaBuiltinAssume(TheCall)) 1192 return ExprError(); 1193 break; 1194 case Builtin::BI__builtin_assume_aligned: 1195 if (SemaBuiltinAssumeAligned(TheCall)) 1196 return ExprError(); 1197 break; 1198 case Builtin::BI__builtin_dynamic_object_size: 1199 case Builtin::BI__builtin_object_size: 1200 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1201 return ExprError(); 1202 break; 1203 case Builtin::BI__builtin_longjmp: 1204 if (SemaBuiltinLongjmp(TheCall)) 1205 return ExprError(); 1206 break; 1207 case Builtin::BI__builtin_setjmp: 1208 if (SemaBuiltinSetjmp(TheCall)) 1209 return ExprError(); 1210 break; 1211 case Builtin::BI_setjmp: 1212 case Builtin::BI_setjmpex: 1213 if (checkArgCount(*this, TheCall, 1)) 1214 return true; 1215 break; 1216 case Builtin::BI__builtin_classify_type: 1217 if (checkArgCount(*this, TheCall, 1)) return true; 1218 TheCall->setType(Context.IntTy); 1219 break; 1220 case Builtin::BI__builtin_constant_p: { 1221 if (checkArgCount(*this, TheCall, 1)) return true; 1222 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1223 if (Arg.isInvalid()) return true; 1224 TheCall->setArg(0, Arg.get()); 1225 TheCall->setType(Context.IntTy); 1226 break; 1227 } 1228 case Builtin::BI__builtin_launder: 1229 return SemaBuiltinLaunder(*this, TheCall); 1230 case Builtin::BI__sync_fetch_and_add: 1231 case Builtin::BI__sync_fetch_and_add_1: 1232 case Builtin::BI__sync_fetch_and_add_2: 1233 case Builtin::BI__sync_fetch_and_add_4: 1234 case Builtin::BI__sync_fetch_and_add_8: 1235 case Builtin::BI__sync_fetch_and_add_16: 1236 case Builtin::BI__sync_fetch_and_sub: 1237 case Builtin::BI__sync_fetch_and_sub_1: 1238 case Builtin::BI__sync_fetch_and_sub_2: 1239 case Builtin::BI__sync_fetch_and_sub_4: 1240 case Builtin::BI__sync_fetch_and_sub_8: 1241 case Builtin::BI__sync_fetch_and_sub_16: 1242 case Builtin::BI__sync_fetch_and_or: 1243 case Builtin::BI__sync_fetch_and_or_1: 1244 case Builtin::BI__sync_fetch_and_or_2: 1245 case Builtin::BI__sync_fetch_and_or_4: 1246 case Builtin::BI__sync_fetch_and_or_8: 1247 case Builtin::BI__sync_fetch_and_or_16: 1248 case Builtin::BI__sync_fetch_and_and: 1249 case Builtin::BI__sync_fetch_and_and_1: 1250 case Builtin::BI__sync_fetch_and_and_2: 1251 case Builtin::BI__sync_fetch_and_and_4: 1252 case Builtin::BI__sync_fetch_and_and_8: 1253 case Builtin::BI__sync_fetch_and_and_16: 1254 case Builtin::BI__sync_fetch_and_xor: 1255 case Builtin::BI__sync_fetch_and_xor_1: 1256 case Builtin::BI__sync_fetch_and_xor_2: 1257 case Builtin::BI__sync_fetch_and_xor_4: 1258 case Builtin::BI__sync_fetch_and_xor_8: 1259 case Builtin::BI__sync_fetch_and_xor_16: 1260 case Builtin::BI__sync_fetch_and_nand: 1261 case Builtin::BI__sync_fetch_and_nand_1: 1262 case Builtin::BI__sync_fetch_and_nand_2: 1263 case Builtin::BI__sync_fetch_and_nand_4: 1264 case Builtin::BI__sync_fetch_and_nand_8: 1265 case Builtin::BI__sync_fetch_and_nand_16: 1266 case Builtin::BI__sync_add_and_fetch: 1267 case Builtin::BI__sync_add_and_fetch_1: 1268 case Builtin::BI__sync_add_and_fetch_2: 1269 case Builtin::BI__sync_add_and_fetch_4: 1270 case Builtin::BI__sync_add_and_fetch_8: 1271 case Builtin::BI__sync_add_and_fetch_16: 1272 case Builtin::BI__sync_sub_and_fetch: 1273 case Builtin::BI__sync_sub_and_fetch_1: 1274 case Builtin::BI__sync_sub_and_fetch_2: 1275 case Builtin::BI__sync_sub_and_fetch_4: 1276 case Builtin::BI__sync_sub_and_fetch_8: 1277 case Builtin::BI__sync_sub_and_fetch_16: 1278 case Builtin::BI__sync_and_and_fetch: 1279 case Builtin::BI__sync_and_and_fetch_1: 1280 case Builtin::BI__sync_and_and_fetch_2: 1281 case Builtin::BI__sync_and_and_fetch_4: 1282 case Builtin::BI__sync_and_and_fetch_8: 1283 case Builtin::BI__sync_and_and_fetch_16: 1284 case Builtin::BI__sync_or_and_fetch: 1285 case Builtin::BI__sync_or_and_fetch_1: 1286 case Builtin::BI__sync_or_and_fetch_2: 1287 case Builtin::BI__sync_or_and_fetch_4: 1288 case Builtin::BI__sync_or_and_fetch_8: 1289 case Builtin::BI__sync_or_and_fetch_16: 1290 case Builtin::BI__sync_xor_and_fetch: 1291 case Builtin::BI__sync_xor_and_fetch_1: 1292 case Builtin::BI__sync_xor_and_fetch_2: 1293 case Builtin::BI__sync_xor_and_fetch_4: 1294 case Builtin::BI__sync_xor_and_fetch_8: 1295 case Builtin::BI__sync_xor_and_fetch_16: 1296 case Builtin::BI__sync_nand_and_fetch: 1297 case Builtin::BI__sync_nand_and_fetch_1: 1298 case Builtin::BI__sync_nand_and_fetch_2: 1299 case Builtin::BI__sync_nand_and_fetch_4: 1300 case Builtin::BI__sync_nand_and_fetch_8: 1301 case Builtin::BI__sync_nand_and_fetch_16: 1302 case Builtin::BI__sync_val_compare_and_swap: 1303 case Builtin::BI__sync_val_compare_and_swap_1: 1304 case Builtin::BI__sync_val_compare_and_swap_2: 1305 case Builtin::BI__sync_val_compare_and_swap_4: 1306 case Builtin::BI__sync_val_compare_and_swap_8: 1307 case Builtin::BI__sync_val_compare_and_swap_16: 1308 case Builtin::BI__sync_bool_compare_and_swap: 1309 case Builtin::BI__sync_bool_compare_and_swap_1: 1310 case Builtin::BI__sync_bool_compare_and_swap_2: 1311 case Builtin::BI__sync_bool_compare_and_swap_4: 1312 case Builtin::BI__sync_bool_compare_and_swap_8: 1313 case Builtin::BI__sync_bool_compare_and_swap_16: 1314 case Builtin::BI__sync_lock_test_and_set: 1315 case Builtin::BI__sync_lock_test_and_set_1: 1316 case Builtin::BI__sync_lock_test_and_set_2: 1317 case Builtin::BI__sync_lock_test_and_set_4: 1318 case Builtin::BI__sync_lock_test_and_set_8: 1319 case Builtin::BI__sync_lock_test_and_set_16: 1320 case Builtin::BI__sync_lock_release: 1321 case Builtin::BI__sync_lock_release_1: 1322 case Builtin::BI__sync_lock_release_2: 1323 case Builtin::BI__sync_lock_release_4: 1324 case Builtin::BI__sync_lock_release_8: 1325 case Builtin::BI__sync_lock_release_16: 1326 case Builtin::BI__sync_swap: 1327 case Builtin::BI__sync_swap_1: 1328 case Builtin::BI__sync_swap_2: 1329 case Builtin::BI__sync_swap_4: 1330 case Builtin::BI__sync_swap_8: 1331 case Builtin::BI__sync_swap_16: 1332 return SemaBuiltinAtomicOverloaded(TheCallResult); 1333 case Builtin::BI__sync_synchronize: 1334 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1335 << TheCall->getCallee()->getSourceRange(); 1336 break; 1337 case Builtin::BI__builtin_nontemporal_load: 1338 case Builtin::BI__builtin_nontemporal_store: 1339 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1340 #define BUILTIN(ID, TYPE, ATTRS) 1341 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1342 case Builtin::BI##ID: \ 1343 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1344 #include "clang/Basic/Builtins.def" 1345 case Builtin::BI__annotation: 1346 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1347 return ExprError(); 1348 break; 1349 case Builtin::BI__builtin_annotation: 1350 if (SemaBuiltinAnnotation(*this, TheCall)) 1351 return ExprError(); 1352 break; 1353 case Builtin::BI__builtin_addressof: 1354 if (SemaBuiltinAddressof(*this, TheCall)) 1355 return ExprError(); 1356 break; 1357 case Builtin::BI__builtin_add_overflow: 1358 case Builtin::BI__builtin_sub_overflow: 1359 case Builtin::BI__builtin_mul_overflow: 1360 if (SemaBuiltinOverflow(*this, TheCall)) 1361 return ExprError(); 1362 break; 1363 case Builtin::BI__builtin_operator_new: 1364 case Builtin::BI__builtin_operator_delete: { 1365 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1366 ExprResult Res = 1367 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1368 if (Res.isInvalid()) 1369 CorrectDelayedTyposInExpr(TheCallResult.get()); 1370 return Res; 1371 } 1372 case Builtin::BI__builtin_dump_struct: { 1373 // We first want to ensure we are called with 2 arguments 1374 if (checkArgCount(*this, TheCall, 2)) 1375 return ExprError(); 1376 // Ensure that the first argument is of type 'struct XX *' 1377 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1378 const QualType PtrArgType = PtrArg->getType(); 1379 if (!PtrArgType->isPointerType() || 1380 !PtrArgType->getPointeeType()->isRecordType()) { 1381 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1382 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1383 << "structure pointer"; 1384 return ExprError(); 1385 } 1386 1387 // Ensure that the second argument is of type 'FunctionType' 1388 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1389 const QualType FnPtrArgType = FnPtrArg->getType(); 1390 if (!FnPtrArgType->isPointerType()) { 1391 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1392 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1393 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1394 return ExprError(); 1395 } 1396 1397 const auto *FuncType = 1398 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1399 1400 if (!FuncType) { 1401 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1402 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1403 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1404 return ExprError(); 1405 } 1406 1407 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1408 if (!FT->getNumParams()) { 1409 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1410 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1411 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1412 return ExprError(); 1413 } 1414 QualType PT = FT->getParamType(0); 1415 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1416 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1417 !PT->getPointeeType().isConstQualified()) { 1418 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1419 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1420 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1421 return ExprError(); 1422 } 1423 } 1424 1425 TheCall->setType(Context.IntTy); 1426 break; 1427 } 1428 case Builtin::BI__builtin_preserve_access_index: 1429 if (SemaBuiltinPreserveAI(*this, TheCall)) 1430 return ExprError(); 1431 break; 1432 case Builtin::BI__builtin_call_with_static_chain: 1433 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1434 return ExprError(); 1435 break; 1436 case Builtin::BI__exception_code: 1437 case Builtin::BI_exception_code: 1438 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1439 diag::err_seh___except_block)) 1440 return ExprError(); 1441 break; 1442 case Builtin::BI__exception_info: 1443 case Builtin::BI_exception_info: 1444 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1445 diag::err_seh___except_filter)) 1446 return ExprError(); 1447 break; 1448 case Builtin::BI__GetExceptionInfo: 1449 if (checkArgCount(*this, TheCall, 1)) 1450 return ExprError(); 1451 1452 if (CheckCXXThrowOperand( 1453 TheCall->getBeginLoc(), 1454 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1455 TheCall)) 1456 return ExprError(); 1457 1458 TheCall->setType(Context.VoidPtrTy); 1459 break; 1460 // OpenCL v2.0, s6.13.16 - Pipe functions 1461 case Builtin::BIread_pipe: 1462 case Builtin::BIwrite_pipe: 1463 // Since those two functions are declared with var args, we need a semantic 1464 // check for the argument. 1465 if (SemaBuiltinRWPipe(*this, TheCall)) 1466 return ExprError(); 1467 break; 1468 case Builtin::BIreserve_read_pipe: 1469 case Builtin::BIreserve_write_pipe: 1470 case Builtin::BIwork_group_reserve_read_pipe: 1471 case Builtin::BIwork_group_reserve_write_pipe: 1472 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BIsub_group_reserve_read_pipe: 1476 case Builtin::BIsub_group_reserve_write_pipe: 1477 if (checkOpenCLSubgroupExt(*this, TheCall) || 1478 SemaBuiltinReserveRWPipe(*this, TheCall)) 1479 return ExprError(); 1480 break; 1481 case Builtin::BIcommit_read_pipe: 1482 case Builtin::BIcommit_write_pipe: 1483 case Builtin::BIwork_group_commit_read_pipe: 1484 case Builtin::BIwork_group_commit_write_pipe: 1485 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1486 return ExprError(); 1487 break; 1488 case Builtin::BIsub_group_commit_read_pipe: 1489 case Builtin::BIsub_group_commit_write_pipe: 1490 if (checkOpenCLSubgroupExt(*this, TheCall) || 1491 SemaBuiltinCommitRWPipe(*this, TheCall)) 1492 return ExprError(); 1493 break; 1494 case Builtin::BIget_pipe_num_packets: 1495 case Builtin::BIget_pipe_max_packets: 1496 if (SemaBuiltinPipePackets(*this, TheCall)) 1497 return ExprError(); 1498 break; 1499 case Builtin::BIto_global: 1500 case Builtin::BIto_local: 1501 case Builtin::BIto_private: 1502 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1503 return ExprError(); 1504 break; 1505 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1506 case Builtin::BIenqueue_kernel: 1507 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1508 return ExprError(); 1509 break; 1510 case Builtin::BIget_kernel_work_group_size: 1511 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1512 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1513 return ExprError(); 1514 break; 1515 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1516 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1517 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1518 return ExprError(); 1519 break; 1520 case Builtin::BI__builtin_os_log_format: 1521 case Builtin::BI__builtin_os_log_format_buffer_size: 1522 if (SemaBuiltinOSLogFormat(TheCall)) 1523 return ExprError(); 1524 break; 1525 } 1526 1527 // Since the target specific builtins for each arch overlap, only check those 1528 // of the arch we are compiling for. 1529 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1530 switch (Context.getTargetInfo().getTriple().getArch()) { 1531 case llvm::Triple::arm: 1532 case llvm::Triple::armeb: 1533 case llvm::Triple::thumb: 1534 case llvm::Triple::thumbeb: 1535 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1536 return ExprError(); 1537 break; 1538 case llvm::Triple::aarch64: 1539 case llvm::Triple::aarch64_32: 1540 case llvm::Triple::aarch64_be: 1541 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1542 return ExprError(); 1543 break; 1544 case llvm::Triple::bpfeb: 1545 case llvm::Triple::bpfel: 1546 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall)) 1547 return ExprError(); 1548 break; 1549 case llvm::Triple::hexagon: 1550 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1551 return ExprError(); 1552 break; 1553 case llvm::Triple::mips: 1554 case llvm::Triple::mipsel: 1555 case llvm::Triple::mips64: 1556 case llvm::Triple::mips64el: 1557 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1558 return ExprError(); 1559 break; 1560 case llvm::Triple::systemz: 1561 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1562 return ExprError(); 1563 break; 1564 case llvm::Triple::x86: 1565 case llvm::Triple::x86_64: 1566 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1567 return ExprError(); 1568 break; 1569 case llvm::Triple::ppc: 1570 case llvm::Triple::ppc64: 1571 case llvm::Triple::ppc64le: 1572 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1573 return ExprError(); 1574 break; 1575 default: 1576 break; 1577 } 1578 } 1579 1580 return TheCallResult; 1581 } 1582 1583 // Get the valid immediate range for the specified NEON type code. 1584 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1585 NeonTypeFlags Type(t); 1586 int IsQuad = ForceQuad ? true : Type.isQuad(); 1587 switch (Type.getEltType()) { 1588 case NeonTypeFlags::Int8: 1589 case NeonTypeFlags::Poly8: 1590 return shift ? 7 : (8 << IsQuad) - 1; 1591 case NeonTypeFlags::Int16: 1592 case NeonTypeFlags::Poly16: 1593 return shift ? 15 : (4 << IsQuad) - 1; 1594 case NeonTypeFlags::Int32: 1595 return shift ? 31 : (2 << IsQuad) - 1; 1596 case NeonTypeFlags::Int64: 1597 case NeonTypeFlags::Poly64: 1598 return shift ? 63 : (1 << IsQuad) - 1; 1599 case NeonTypeFlags::Poly128: 1600 return shift ? 127 : (1 << IsQuad) - 1; 1601 case NeonTypeFlags::Float16: 1602 assert(!shift && "cannot shift float types!"); 1603 return (4 << IsQuad) - 1; 1604 case NeonTypeFlags::Float32: 1605 assert(!shift && "cannot shift float types!"); 1606 return (2 << IsQuad) - 1; 1607 case NeonTypeFlags::Float64: 1608 assert(!shift && "cannot shift float types!"); 1609 return (1 << IsQuad) - 1; 1610 } 1611 llvm_unreachable("Invalid NeonTypeFlag!"); 1612 } 1613 1614 /// getNeonEltType - Return the QualType corresponding to the elements of 1615 /// the vector type specified by the NeonTypeFlags. This is used to check 1616 /// the pointer arguments for Neon load/store intrinsics. 1617 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1618 bool IsPolyUnsigned, bool IsInt64Long) { 1619 switch (Flags.getEltType()) { 1620 case NeonTypeFlags::Int8: 1621 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1622 case NeonTypeFlags::Int16: 1623 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1624 case NeonTypeFlags::Int32: 1625 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1626 case NeonTypeFlags::Int64: 1627 if (IsInt64Long) 1628 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1629 else 1630 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1631 : Context.LongLongTy; 1632 case NeonTypeFlags::Poly8: 1633 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1634 case NeonTypeFlags::Poly16: 1635 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1636 case NeonTypeFlags::Poly64: 1637 if (IsInt64Long) 1638 return Context.UnsignedLongTy; 1639 else 1640 return Context.UnsignedLongLongTy; 1641 case NeonTypeFlags::Poly128: 1642 break; 1643 case NeonTypeFlags::Float16: 1644 return Context.HalfTy; 1645 case NeonTypeFlags::Float32: 1646 return Context.FloatTy; 1647 case NeonTypeFlags::Float64: 1648 return Context.DoubleTy; 1649 } 1650 llvm_unreachable("Invalid NeonTypeFlag!"); 1651 } 1652 1653 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1654 llvm::APSInt Result; 1655 uint64_t mask = 0; 1656 unsigned TV = 0; 1657 int PtrArgNum = -1; 1658 bool HasConstPtr = false; 1659 switch (BuiltinID) { 1660 #define GET_NEON_OVERLOAD_CHECK 1661 #include "clang/Basic/arm_neon.inc" 1662 #include "clang/Basic/arm_fp16.inc" 1663 #undef GET_NEON_OVERLOAD_CHECK 1664 } 1665 1666 // For NEON intrinsics which are overloaded on vector element type, validate 1667 // the immediate which specifies which variant to emit. 1668 unsigned ImmArg = TheCall->getNumArgs()-1; 1669 if (mask) { 1670 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1671 return true; 1672 1673 TV = Result.getLimitedValue(64); 1674 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1675 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1676 << TheCall->getArg(ImmArg)->getSourceRange(); 1677 } 1678 1679 if (PtrArgNum >= 0) { 1680 // Check that pointer arguments have the specified type. 1681 Expr *Arg = TheCall->getArg(PtrArgNum); 1682 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1683 Arg = ICE->getSubExpr(); 1684 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1685 QualType RHSTy = RHS.get()->getType(); 1686 1687 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1688 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1689 Arch == llvm::Triple::aarch64_32 || 1690 Arch == llvm::Triple::aarch64_be; 1691 bool IsInt64Long = 1692 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1693 QualType EltTy = 1694 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1695 if (HasConstPtr) 1696 EltTy = EltTy.withConst(); 1697 QualType LHSTy = Context.getPointerType(EltTy); 1698 AssignConvertType ConvTy; 1699 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1700 if (RHS.isInvalid()) 1701 return true; 1702 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1703 RHS.get(), AA_Assigning)) 1704 return true; 1705 } 1706 1707 // For NEON intrinsics which take an immediate value as part of the 1708 // instruction, range check them here. 1709 unsigned i = 0, l = 0, u = 0; 1710 switch (BuiltinID) { 1711 default: 1712 return false; 1713 #define GET_NEON_IMMEDIATE_CHECK 1714 #include "clang/Basic/arm_neon.inc" 1715 #include "clang/Basic/arm_fp16.inc" 1716 #undef GET_NEON_IMMEDIATE_CHECK 1717 } 1718 1719 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1720 } 1721 1722 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1723 switch (BuiltinID) { 1724 default: 1725 return false; 1726 #include "clang/Basic/arm_mve_builtin_sema.inc" 1727 } 1728 } 1729 1730 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1731 unsigned MaxWidth) { 1732 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1733 BuiltinID == ARM::BI__builtin_arm_ldaex || 1734 BuiltinID == ARM::BI__builtin_arm_strex || 1735 BuiltinID == ARM::BI__builtin_arm_stlex || 1736 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1737 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1738 BuiltinID == AArch64::BI__builtin_arm_strex || 1739 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1740 "unexpected ARM builtin"); 1741 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1742 BuiltinID == ARM::BI__builtin_arm_ldaex || 1743 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1744 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1745 1746 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1747 1748 // Ensure that we have the proper number of arguments. 1749 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1750 return true; 1751 1752 // Inspect the pointer argument of the atomic builtin. This should always be 1753 // a pointer type, whose element is an integral scalar or pointer type. 1754 // Because it is a pointer type, we don't have to worry about any implicit 1755 // casts here. 1756 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1757 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1758 if (PointerArgRes.isInvalid()) 1759 return true; 1760 PointerArg = PointerArgRes.get(); 1761 1762 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1763 if (!pointerType) { 1764 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1765 << PointerArg->getType() << PointerArg->getSourceRange(); 1766 return true; 1767 } 1768 1769 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1770 // task is to insert the appropriate casts into the AST. First work out just 1771 // what the appropriate type is. 1772 QualType ValType = pointerType->getPointeeType(); 1773 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1774 if (IsLdrex) 1775 AddrType.addConst(); 1776 1777 // Issue a warning if the cast is dodgy. 1778 CastKind CastNeeded = CK_NoOp; 1779 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1780 CastNeeded = CK_BitCast; 1781 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1782 << PointerArg->getType() << Context.getPointerType(AddrType) 1783 << AA_Passing << PointerArg->getSourceRange(); 1784 } 1785 1786 // Finally, do the cast and replace the argument with the corrected version. 1787 AddrType = Context.getPointerType(AddrType); 1788 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1789 if (PointerArgRes.isInvalid()) 1790 return true; 1791 PointerArg = PointerArgRes.get(); 1792 1793 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1794 1795 // In general, we allow ints, floats and pointers to be loaded and stored. 1796 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1797 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1798 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1799 << PointerArg->getType() << PointerArg->getSourceRange(); 1800 return true; 1801 } 1802 1803 // But ARM doesn't have instructions to deal with 128-bit versions. 1804 if (Context.getTypeSize(ValType) > MaxWidth) { 1805 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1806 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1807 << PointerArg->getType() << PointerArg->getSourceRange(); 1808 return true; 1809 } 1810 1811 switch (ValType.getObjCLifetime()) { 1812 case Qualifiers::OCL_None: 1813 case Qualifiers::OCL_ExplicitNone: 1814 // okay 1815 break; 1816 1817 case Qualifiers::OCL_Weak: 1818 case Qualifiers::OCL_Strong: 1819 case Qualifiers::OCL_Autoreleasing: 1820 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1821 << ValType << PointerArg->getSourceRange(); 1822 return true; 1823 } 1824 1825 if (IsLdrex) { 1826 TheCall->setType(ValType); 1827 return false; 1828 } 1829 1830 // Initialize the argument to be stored. 1831 ExprResult ValArg = TheCall->getArg(0); 1832 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1833 Context, ValType, /*consume*/ false); 1834 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1835 if (ValArg.isInvalid()) 1836 return true; 1837 TheCall->setArg(0, ValArg.get()); 1838 1839 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1840 // but the custom checker bypasses all default analysis. 1841 TheCall->setType(Context.IntTy); 1842 return false; 1843 } 1844 1845 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1846 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1847 BuiltinID == ARM::BI__builtin_arm_ldaex || 1848 BuiltinID == ARM::BI__builtin_arm_strex || 1849 BuiltinID == ARM::BI__builtin_arm_stlex) { 1850 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1851 } 1852 1853 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1854 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1855 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1856 } 1857 1858 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1859 BuiltinID == ARM::BI__builtin_arm_wsr64) 1860 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1861 1862 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1863 BuiltinID == ARM::BI__builtin_arm_rsrp || 1864 BuiltinID == ARM::BI__builtin_arm_wsr || 1865 BuiltinID == ARM::BI__builtin_arm_wsrp) 1866 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1867 1868 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1869 return true; 1870 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 1871 return true; 1872 1873 // For intrinsics which take an immediate value as part of the instruction, 1874 // range check them here. 1875 // FIXME: VFP Intrinsics should error if VFP not present. 1876 switch (BuiltinID) { 1877 default: return false; 1878 case ARM::BI__builtin_arm_ssat: 1879 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1880 case ARM::BI__builtin_arm_usat: 1881 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1882 case ARM::BI__builtin_arm_ssat16: 1883 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1884 case ARM::BI__builtin_arm_usat16: 1885 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1886 case ARM::BI__builtin_arm_vcvtr_f: 1887 case ARM::BI__builtin_arm_vcvtr_d: 1888 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1889 case ARM::BI__builtin_arm_dmb: 1890 case ARM::BI__builtin_arm_dsb: 1891 case ARM::BI__builtin_arm_isb: 1892 case ARM::BI__builtin_arm_dbg: 1893 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1894 } 1895 } 1896 1897 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1898 CallExpr *TheCall) { 1899 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1900 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1901 BuiltinID == AArch64::BI__builtin_arm_strex || 1902 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1903 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1904 } 1905 1906 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1907 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1908 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1909 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1910 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1911 } 1912 1913 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1914 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1915 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1916 1917 // Memory Tagging Extensions (MTE) Intrinsics 1918 if (BuiltinID == AArch64::BI__builtin_arm_irg || 1919 BuiltinID == AArch64::BI__builtin_arm_addg || 1920 BuiltinID == AArch64::BI__builtin_arm_gmi || 1921 BuiltinID == AArch64::BI__builtin_arm_ldg || 1922 BuiltinID == AArch64::BI__builtin_arm_stg || 1923 BuiltinID == AArch64::BI__builtin_arm_subp) { 1924 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 1925 } 1926 1927 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1928 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1929 BuiltinID == AArch64::BI__builtin_arm_wsr || 1930 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1931 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1932 1933 // Only check the valid encoding range. Any constant in this range would be 1934 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1935 // an exception for incorrect registers. This matches MSVC behavior. 1936 if (BuiltinID == AArch64::BI_ReadStatusReg || 1937 BuiltinID == AArch64::BI_WriteStatusReg) 1938 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1939 1940 if (BuiltinID == AArch64::BI__getReg) 1941 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1942 1943 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1944 return true; 1945 1946 // For intrinsics which take an immediate value as part of the instruction, 1947 // range check them here. 1948 unsigned i = 0, l = 0, u = 0; 1949 switch (BuiltinID) { 1950 default: return false; 1951 case AArch64::BI__builtin_arm_dmb: 1952 case AArch64::BI__builtin_arm_dsb: 1953 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1954 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 1955 } 1956 1957 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1958 } 1959 1960 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 1961 CallExpr *TheCall) { 1962 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 1963 "unexpected ARM builtin"); 1964 1965 if (checkArgCount(*this, TheCall, 2)) 1966 return true; 1967 1968 // The first argument needs to be a record field access. 1969 // If it is an array element access, we delay decision 1970 // to BPF backend to check whether the access is a 1971 // field access or not. 1972 Expr *Arg = TheCall->getArg(0); 1973 if (Arg->getType()->getAsPlaceholderType() || 1974 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 1975 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 1976 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 1977 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 1978 << 1 << Arg->getSourceRange(); 1979 return true; 1980 } 1981 1982 // The second argument needs to be a constant int 1983 llvm::APSInt Value; 1984 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 1985 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 1986 << 2 << Arg->getSourceRange(); 1987 return true; 1988 } 1989 1990 TheCall->setType(Context.UnsignedIntTy); 1991 return false; 1992 } 1993 1994 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1995 struct BuiltinAndString { 1996 unsigned BuiltinID; 1997 const char *Str; 1998 }; 1999 2000 static BuiltinAndString ValidCPU[] = { 2001 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 2024 }; 2025 2026 static BuiltinAndString ValidHVX[] = { 2027 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2605 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2606 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2607 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2608 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2609 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2610 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2611 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2612 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2613 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2614 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2615 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2616 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2617 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2618 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2619 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2620 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2621 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2622 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2623 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2624 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2625 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2626 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2627 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2628 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2629 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2630 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2631 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2632 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2633 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2634 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2635 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2636 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2637 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2638 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2639 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2640 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2641 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2642 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2643 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2644 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2645 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2646 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2647 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2648 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2649 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2650 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2651 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2652 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2653 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2654 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2655 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2656 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2657 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2658 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2659 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2660 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2661 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2662 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2663 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2664 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2665 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2666 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2667 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2668 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2669 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2670 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2671 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2672 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2673 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2674 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2675 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2676 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2677 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2678 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2679 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2680 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2681 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2682 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2683 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2684 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2685 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2686 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2687 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2688 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2689 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2690 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2691 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2692 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2693 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2694 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2695 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2696 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2697 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2698 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2699 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2700 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2701 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2702 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2703 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2704 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2705 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2706 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2707 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2708 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2709 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2710 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2711 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2712 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2713 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2714 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2715 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2716 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2717 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2718 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2719 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2720 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2721 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2722 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2723 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2724 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2725 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2726 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2727 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2728 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2729 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2730 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2731 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2732 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2733 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2734 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2735 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2736 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2737 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2738 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2739 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2740 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2741 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2742 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2743 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2744 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2745 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2746 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2747 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2748 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2749 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2750 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2751 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2752 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2753 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2754 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2755 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2756 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2757 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2758 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2759 }; 2760 2761 // Sort the tables on first execution so we can binary search them. 2762 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2763 return LHS.BuiltinID < RHS.BuiltinID; 2764 }; 2765 static const bool SortOnce = 2766 (llvm::sort(ValidCPU, SortCmp), 2767 llvm::sort(ValidHVX, SortCmp), true); 2768 (void)SortOnce; 2769 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2770 return BI.BuiltinID < BuiltinID; 2771 }; 2772 2773 const TargetInfo &TI = Context.getTargetInfo(); 2774 2775 const BuiltinAndString *FC = 2776 llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp); 2777 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2778 const TargetOptions &Opts = TI.getTargetOpts(); 2779 StringRef CPU = Opts.CPU; 2780 if (!CPU.empty()) { 2781 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2782 CPU.consume_front("hexagon"); 2783 SmallVector<StringRef, 3> CPUs; 2784 StringRef(FC->Str).split(CPUs, ','); 2785 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2786 return Diag(TheCall->getBeginLoc(), 2787 diag::err_hexagon_builtin_unsupported_cpu); 2788 } 2789 } 2790 2791 const BuiltinAndString *FH = 2792 llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp); 2793 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2794 if (!TI.hasFeature("hvx")) 2795 return Diag(TheCall->getBeginLoc(), 2796 diag::err_hexagon_builtin_requires_hvx); 2797 2798 SmallVector<StringRef, 3> HVXs; 2799 StringRef(FH->Str).split(HVXs, ','); 2800 bool IsValid = llvm::any_of(HVXs, 2801 [&TI] (StringRef V) { 2802 std::string F = "hvx" + V.str(); 2803 return TI.hasFeature(F); 2804 }); 2805 if (!IsValid) 2806 return Diag(TheCall->getBeginLoc(), 2807 diag::err_hexagon_builtin_unsupported_hvx); 2808 } 2809 2810 return false; 2811 } 2812 2813 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2814 struct ArgInfo { 2815 uint8_t OpNum; 2816 bool IsSigned; 2817 uint8_t BitWidth; 2818 uint8_t Align; 2819 }; 2820 struct BuiltinInfo { 2821 unsigned BuiltinID; 2822 ArgInfo Infos[2]; 2823 }; 2824 2825 static BuiltinInfo Infos[] = { 2826 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2827 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2828 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2829 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2830 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2831 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2832 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2833 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2834 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2835 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2836 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2837 2838 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2849 2850 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2891 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2902 {{ 1, false, 6, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2910 {{ 1, false, 5, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2917 { 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2919 { 2, false, 6, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2921 { 3, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2923 { 3, false, 6, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2940 {{ 2, false, 4, 0 }, 2941 { 3, false, 5, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2943 {{ 2, false, 4, 0 }, 2944 { 3, false, 5, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2946 {{ 2, false, 4, 0 }, 2947 { 3, false, 5, 0 }} }, 2948 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2949 {{ 2, false, 4, 0 }, 2950 { 3, false, 5, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2953 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2958 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2959 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2960 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2961 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2962 { 2, false, 5, 0 }} }, 2963 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2964 { 2, false, 6, 0 }} }, 2965 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2966 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2967 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2968 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2969 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2970 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2971 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2972 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2973 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2974 {{ 1, false, 4, 0 }} }, 2975 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2976 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2977 {{ 1, false, 4, 0 }} }, 2978 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2979 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2980 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2981 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2982 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2983 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2984 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2985 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2986 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2987 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2988 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2989 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2990 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2991 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2992 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2993 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2994 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2995 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2996 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2997 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2998 {{ 3, false, 1, 0 }} }, 2999 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3000 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3001 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3002 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3003 {{ 3, false, 1, 0 }} }, 3004 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3005 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3006 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3007 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3008 {{ 3, false, 1, 0 }} }, 3009 }; 3010 3011 // Use a dynamically initialized static to sort the table exactly once on 3012 // first run. 3013 static const bool SortOnce = 3014 (llvm::sort(Infos, 3015 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3016 return LHS.BuiltinID < RHS.BuiltinID; 3017 }), 3018 true); 3019 (void)SortOnce; 3020 3021 const BuiltinInfo *F = llvm::partition_point( 3022 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3023 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3024 return false; 3025 3026 bool Error = false; 3027 3028 for (const ArgInfo &A : F->Infos) { 3029 // Ignore empty ArgInfo elements. 3030 if (A.BitWidth == 0) 3031 continue; 3032 3033 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3034 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3035 if (!A.Align) { 3036 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3037 } else { 3038 unsigned M = 1 << A.Align; 3039 Min *= M; 3040 Max *= M; 3041 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 3042 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3043 } 3044 } 3045 return Error; 3046 } 3047 3048 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3049 CallExpr *TheCall) { 3050 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 3051 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3052 } 3053 3054 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3055 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 3056 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3057 } 3058 3059 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 3060 const TargetInfo &TI = Context.getTargetInfo(); 3061 3062 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3063 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3064 if (!TI.hasFeature("dsp")) 3065 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3066 } 3067 3068 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3069 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3070 if (!TI.hasFeature("dspr2")) 3071 return Diag(TheCall->getBeginLoc(), 3072 diag::err_mips_builtin_requires_dspr2); 3073 } 3074 3075 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3076 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3077 if (!TI.hasFeature("msa")) 3078 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3079 } 3080 3081 return false; 3082 } 3083 3084 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3085 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3086 // ordering for DSP is unspecified. MSA is ordered by the data format used 3087 // by the underlying instruction i.e., df/m, df/n and then by size. 3088 // 3089 // FIXME: The size tests here should instead be tablegen'd along with the 3090 // definitions from include/clang/Basic/BuiltinsMips.def. 3091 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3092 // be too. 3093 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3094 unsigned i = 0, l = 0, u = 0, m = 0; 3095 switch (BuiltinID) { 3096 default: return false; 3097 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3098 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3099 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3100 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3101 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3102 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3103 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3104 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3105 // df/m field. 3106 // These intrinsics take an unsigned 3 bit immediate. 3107 case Mips::BI__builtin_msa_bclri_b: 3108 case Mips::BI__builtin_msa_bnegi_b: 3109 case Mips::BI__builtin_msa_bseti_b: 3110 case Mips::BI__builtin_msa_sat_s_b: 3111 case Mips::BI__builtin_msa_sat_u_b: 3112 case Mips::BI__builtin_msa_slli_b: 3113 case Mips::BI__builtin_msa_srai_b: 3114 case Mips::BI__builtin_msa_srari_b: 3115 case Mips::BI__builtin_msa_srli_b: 3116 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3117 case Mips::BI__builtin_msa_binsli_b: 3118 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3119 // These intrinsics take an unsigned 4 bit immediate. 3120 case Mips::BI__builtin_msa_bclri_h: 3121 case Mips::BI__builtin_msa_bnegi_h: 3122 case Mips::BI__builtin_msa_bseti_h: 3123 case Mips::BI__builtin_msa_sat_s_h: 3124 case Mips::BI__builtin_msa_sat_u_h: 3125 case Mips::BI__builtin_msa_slli_h: 3126 case Mips::BI__builtin_msa_srai_h: 3127 case Mips::BI__builtin_msa_srari_h: 3128 case Mips::BI__builtin_msa_srli_h: 3129 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3130 case Mips::BI__builtin_msa_binsli_h: 3131 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3132 // These intrinsics take an unsigned 5 bit immediate. 3133 // The first block of intrinsics actually have an unsigned 5 bit field, 3134 // not a df/n field. 3135 case Mips::BI__builtin_msa_cfcmsa: 3136 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3137 case Mips::BI__builtin_msa_clei_u_b: 3138 case Mips::BI__builtin_msa_clei_u_h: 3139 case Mips::BI__builtin_msa_clei_u_w: 3140 case Mips::BI__builtin_msa_clei_u_d: 3141 case Mips::BI__builtin_msa_clti_u_b: 3142 case Mips::BI__builtin_msa_clti_u_h: 3143 case Mips::BI__builtin_msa_clti_u_w: 3144 case Mips::BI__builtin_msa_clti_u_d: 3145 case Mips::BI__builtin_msa_maxi_u_b: 3146 case Mips::BI__builtin_msa_maxi_u_h: 3147 case Mips::BI__builtin_msa_maxi_u_w: 3148 case Mips::BI__builtin_msa_maxi_u_d: 3149 case Mips::BI__builtin_msa_mini_u_b: 3150 case Mips::BI__builtin_msa_mini_u_h: 3151 case Mips::BI__builtin_msa_mini_u_w: 3152 case Mips::BI__builtin_msa_mini_u_d: 3153 case Mips::BI__builtin_msa_addvi_b: 3154 case Mips::BI__builtin_msa_addvi_h: 3155 case Mips::BI__builtin_msa_addvi_w: 3156 case Mips::BI__builtin_msa_addvi_d: 3157 case Mips::BI__builtin_msa_bclri_w: 3158 case Mips::BI__builtin_msa_bnegi_w: 3159 case Mips::BI__builtin_msa_bseti_w: 3160 case Mips::BI__builtin_msa_sat_s_w: 3161 case Mips::BI__builtin_msa_sat_u_w: 3162 case Mips::BI__builtin_msa_slli_w: 3163 case Mips::BI__builtin_msa_srai_w: 3164 case Mips::BI__builtin_msa_srari_w: 3165 case Mips::BI__builtin_msa_srli_w: 3166 case Mips::BI__builtin_msa_srlri_w: 3167 case Mips::BI__builtin_msa_subvi_b: 3168 case Mips::BI__builtin_msa_subvi_h: 3169 case Mips::BI__builtin_msa_subvi_w: 3170 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3171 case Mips::BI__builtin_msa_binsli_w: 3172 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3173 // These intrinsics take an unsigned 6 bit immediate. 3174 case Mips::BI__builtin_msa_bclri_d: 3175 case Mips::BI__builtin_msa_bnegi_d: 3176 case Mips::BI__builtin_msa_bseti_d: 3177 case Mips::BI__builtin_msa_sat_s_d: 3178 case Mips::BI__builtin_msa_sat_u_d: 3179 case Mips::BI__builtin_msa_slli_d: 3180 case Mips::BI__builtin_msa_srai_d: 3181 case Mips::BI__builtin_msa_srari_d: 3182 case Mips::BI__builtin_msa_srli_d: 3183 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3184 case Mips::BI__builtin_msa_binsli_d: 3185 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3186 // These intrinsics take a signed 5 bit immediate. 3187 case Mips::BI__builtin_msa_ceqi_b: 3188 case Mips::BI__builtin_msa_ceqi_h: 3189 case Mips::BI__builtin_msa_ceqi_w: 3190 case Mips::BI__builtin_msa_ceqi_d: 3191 case Mips::BI__builtin_msa_clti_s_b: 3192 case Mips::BI__builtin_msa_clti_s_h: 3193 case Mips::BI__builtin_msa_clti_s_w: 3194 case Mips::BI__builtin_msa_clti_s_d: 3195 case Mips::BI__builtin_msa_clei_s_b: 3196 case Mips::BI__builtin_msa_clei_s_h: 3197 case Mips::BI__builtin_msa_clei_s_w: 3198 case Mips::BI__builtin_msa_clei_s_d: 3199 case Mips::BI__builtin_msa_maxi_s_b: 3200 case Mips::BI__builtin_msa_maxi_s_h: 3201 case Mips::BI__builtin_msa_maxi_s_w: 3202 case Mips::BI__builtin_msa_maxi_s_d: 3203 case Mips::BI__builtin_msa_mini_s_b: 3204 case Mips::BI__builtin_msa_mini_s_h: 3205 case Mips::BI__builtin_msa_mini_s_w: 3206 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3207 // These intrinsics take an unsigned 8 bit immediate. 3208 case Mips::BI__builtin_msa_andi_b: 3209 case Mips::BI__builtin_msa_nori_b: 3210 case Mips::BI__builtin_msa_ori_b: 3211 case Mips::BI__builtin_msa_shf_b: 3212 case Mips::BI__builtin_msa_shf_h: 3213 case Mips::BI__builtin_msa_shf_w: 3214 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3215 case Mips::BI__builtin_msa_bseli_b: 3216 case Mips::BI__builtin_msa_bmnzi_b: 3217 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3218 // df/n format 3219 // These intrinsics take an unsigned 4 bit immediate. 3220 case Mips::BI__builtin_msa_copy_s_b: 3221 case Mips::BI__builtin_msa_copy_u_b: 3222 case Mips::BI__builtin_msa_insve_b: 3223 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3224 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3225 // These intrinsics take an unsigned 3 bit immediate. 3226 case Mips::BI__builtin_msa_copy_s_h: 3227 case Mips::BI__builtin_msa_copy_u_h: 3228 case Mips::BI__builtin_msa_insve_h: 3229 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3230 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3231 // These intrinsics take an unsigned 2 bit immediate. 3232 case Mips::BI__builtin_msa_copy_s_w: 3233 case Mips::BI__builtin_msa_copy_u_w: 3234 case Mips::BI__builtin_msa_insve_w: 3235 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3236 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3237 // These intrinsics take an unsigned 1 bit immediate. 3238 case Mips::BI__builtin_msa_copy_s_d: 3239 case Mips::BI__builtin_msa_copy_u_d: 3240 case Mips::BI__builtin_msa_insve_d: 3241 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3242 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3243 // Memory offsets and immediate loads. 3244 // These intrinsics take a signed 10 bit immediate. 3245 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3246 case Mips::BI__builtin_msa_ldi_h: 3247 case Mips::BI__builtin_msa_ldi_w: 3248 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3249 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3250 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3251 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3252 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3253 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3254 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3255 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3256 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3257 } 3258 3259 if (!m) 3260 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3261 3262 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3263 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3264 } 3265 3266 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3267 unsigned i = 0, l = 0, u = 0; 3268 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3269 BuiltinID == PPC::BI__builtin_divdeu || 3270 BuiltinID == PPC::BI__builtin_bpermd; 3271 bool IsTarget64Bit = Context.getTargetInfo() 3272 .getTypeWidth(Context 3273 .getTargetInfo() 3274 .getIntPtrType()) == 64; 3275 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3276 BuiltinID == PPC::BI__builtin_divweu || 3277 BuiltinID == PPC::BI__builtin_divde || 3278 BuiltinID == PPC::BI__builtin_divdeu; 3279 3280 if (Is64BitBltin && !IsTarget64Bit) 3281 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3282 << TheCall->getSourceRange(); 3283 3284 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3285 (BuiltinID == PPC::BI__builtin_bpermd && 3286 !Context.getTargetInfo().hasFeature("bpermd"))) 3287 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3288 << TheCall->getSourceRange(); 3289 3290 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3291 if (!Context.getTargetInfo().hasFeature("vsx")) 3292 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3293 << TheCall->getSourceRange(); 3294 return false; 3295 }; 3296 3297 switch (BuiltinID) { 3298 default: return false; 3299 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3300 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3301 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3302 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3303 case PPC::BI__builtin_altivec_dss: 3304 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3305 case PPC::BI__builtin_tbegin: 3306 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3307 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3308 case PPC::BI__builtin_tabortwc: 3309 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3310 case PPC::BI__builtin_tabortwci: 3311 case PPC::BI__builtin_tabortdci: 3312 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3313 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3314 case PPC::BI__builtin_altivec_dst: 3315 case PPC::BI__builtin_altivec_dstt: 3316 case PPC::BI__builtin_altivec_dstst: 3317 case PPC::BI__builtin_altivec_dststt: 3318 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3319 case PPC::BI__builtin_vsx_xxpermdi: 3320 case PPC::BI__builtin_vsx_xxsldwi: 3321 return SemaBuiltinVSX(TheCall); 3322 case PPC::BI__builtin_unpack_vector_int128: 3323 return SemaVSXCheck(TheCall) || 3324 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3325 case PPC::BI__builtin_pack_vector_int128: 3326 return SemaVSXCheck(TheCall); 3327 } 3328 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3329 } 3330 3331 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3332 CallExpr *TheCall) { 3333 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3334 Expr *Arg = TheCall->getArg(0); 3335 llvm::APSInt AbortCode(32); 3336 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3337 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3338 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3339 << Arg->getSourceRange(); 3340 } 3341 3342 // For intrinsics which take an immediate value as part of the instruction, 3343 // range check them here. 3344 unsigned i = 0, l = 0, u = 0; 3345 switch (BuiltinID) { 3346 default: return false; 3347 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3348 case SystemZ::BI__builtin_s390_verimb: 3349 case SystemZ::BI__builtin_s390_verimh: 3350 case SystemZ::BI__builtin_s390_verimf: 3351 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3352 case SystemZ::BI__builtin_s390_vfaeb: 3353 case SystemZ::BI__builtin_s390_vfaeh: 3354 case SystemZ::BI__builtin_s390_vfaef: 3355 case SystemZ::BI__builtin_s390_vfaebs: 3356 case SystemZ::BI__builtin_s390_vfaehs: 3357 case SystemZ::BI__builtin_s390_vfaefs: 3358 case SystemZ::BI__builtin_s390_vfaezb: 3359 case SystemZ::BI__builtin_s390_vfaezh: 3360 case SystemZ::BI__builtin_s390_vfaezf: 3361 case SystemZ::BI__builtin_s390_vfaezbs: 3362 case SystemZ::BI__builtin_s390_vfaezhs: 3363 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3364 case SystemZ::BI__builtin_s390_vfisb: 3365 case SystemZ::BI__builtin_s390_vfidb: 3366 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3367 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3368 case SystemZ::BI__builtin_s390_vftcisb: 3369 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3370 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3371 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3372 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3373 case SystemZ::BI__builtin_s390_vstrcb: 3374 case SystemZ::BI__builtin_s390_vstrch: 3375 case SystemZ::BI__builtin_s390_vstrcf: 3376 case SystemZ::BI__builtin_s390_vstrczb: 3377 case SystemZ::BI__builtin_s390_vstrczh: 3378 case SystemZ::BI__builtin_s390_vstrczf: 3379 case SystemZ::BI__builtin_s390_vstrcbs: 3380 case SystemZ::BI__builtin_s390_vstrchs: 3381 case SystemZ::BI__builtin_s390_vstrcfs: 3382 case SystemZ::BI__builtin_s390_vstrczbs: 3383 case SystemZ::BI__builtin_s390_vstrczhs: 3384 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3385 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3386 case SystemZ::BI__builtin_s390_vfminsb: 3387 case SystemZ::BI__builtin_s390_vfmaxsb: 3388 case SystemZ::BI__builtin_s390_vfmindb: 3389 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3390 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3391 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3392 } 3393 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3394 } 3395 3396 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3397 /// This checks that the target supports __builtin_cpu_supports and 3398 /// that the string argument is constant and valid. 3399 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3400 Expr *Arg = TheCall->getArg(0); 3401 3402 // Check if the argument is a string literal. 3403 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3404 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3405 << Arg->getSourceRange(); 3406 3407 // Check the contents of the string. 3408 StringRef Feature = 3409 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3410 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3411 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3412 << Arg->getSourceRange(); 3413 return false; 3414 } 3415 3416 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3417 /// This checks that the target supports __builtin_cpu_is and 3418 /// that the string argument is constant and valid. 3419 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3420 Expr *Arg = TheCall->getArg(0); 3421 3422 // Check if the argument is a string literal. 3423 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3424 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3425 << Arg->getSourceRange(); 3426 3427 // Check the contents of the string. 3428 StringRef Feature = 3429 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3430 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3431 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3432 << Arg->getSourceRange(); 3433 return false; 3434 } 3435 3436 // Check if the rounding mode is legal. 3437 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3438 // Indicates if this instruction has rounding control or just SAE. 3439 bool HasRC = false; 3440 3441 unsigned ArgNum = 0; 3442 switch (BuiltinID) { 3443 default: 3444 return false; 3445 case X86::BI__builtin_ia32_vcvttsd2si32: 3446 case X86::BI__builtin_ia32_vcvttsd2si64: 3447 case X86::BI__builtin_ia32_vcvttsd2usi32: 3448 case X86::BI__builtin_ia32_vcvttsd2usi64: 3449 case X86::BI__builtin_ia32_vcvttss2si32: 3450 case X86::BI__builtin_ia32_vcvttss2si64: 3451 case X86::BI__builtin_ia32_vcvttss2usi32: 3452 case X86::BI__builtin_ia32_vcvttss2usi64: 3453 ArgNum = 1; 3454 break; 3455 case X86::BI__builtin_ia32_maxpd512: 3456 case X86::BI__builtin_ia32_maxps512: 3457 case X86::BI__builtin_ia32_minpd512: 3458 case X86::BI__builtin_ia32_minps512: 3459 ArgNum = 2; 3460 break; 3461 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3462 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3463 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3464 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3465 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3466 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3467 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3468 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3469 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3470 case X86::BI__builtin_ia32_exp2pd_mask: 3471 case X86::BI__builtin_ia32_exp2ps_mask: 3472 case X86::BI__builtin_ia32_getexppd512_mask: 3473 case X86::BI__builtin_ia32_getexpps512_mask: 3474 case X86::BI__builtin_ia32_rcp28pd_mask: 3475 case X86::BI__builtin_ia32_rcp28ps_mask: 3476 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3477 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3478 case X86::BI__builtin_ia32_vcomisd: 3479 case X86::BI__builtin_ia32_vcomiss: 3480 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3481 ArgNum = 3; 3482 break; 3483 case X86::BI__builtin_ia32_cmppd512_mask: 3484 case X86::BI__builtin_ia32_cmpps512_mask: 3485 case X86::BI__builtin_ia32_cmpsd_mask: 3486 case X86::BI__builtin_ia32_cmpss_mask: 3487 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3488 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3489 case X86::BI__builtin_ia32_getexpss128_round_mask: 3490 case X86::BI__builtin_ia32_getmantpd512_mask: 3491 case X86::BI__builtin_ia32_getmantps512_mask: 3492 case X86::BI__builtin_ia32_maxsd_round_mask: 3493 case X86::BI__builtin_ia32_maxss_round_mask: 3494 case X86::BI__builtin_ia32_minsd_round_mask: 3495 case X86::BI__builtin_ia32_minss_round_mask: 3496 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3497 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3498 case X86::BI__builtin_ia32_reducepd512_mask: 3499 case X86::BI__builtin_ia32_reduceps512_mask: 3500 case X86::BI__builtin_ia32_rndscalepd_mask: 3501 case X86::BI__builtin_ia32_rndscaleps_mask: 3502 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3503 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3504 ArgNum = 4; 3505 break; 3506 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3507 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3508 case X86::BI__builtin_ia32_fixupimmps512_mask: 3509 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3510 case X86::BI__builtin_ia32_fixupimmsd_mask: 3511 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3512 case X86::BI__builtin_ia32_fixupimmss_mask: 3513 case X86::BI__builtin_ia32_fixupimmss_maskz: 3514 case X86::BI__builtin_ia32_getmantsd_round_mask: 3515 case X86::BI__builtin_ia32_getmantss_round_mask: 3516 case X86::BI__builtin_ia32_rangepd512_mask: 3517 case X86::BI__builtin_ia32_rangeps512_mask: 3518 case X86::BI__builtin_ia32_rangesd128_round_mask: 3519 case X86::BI__builtin_ia32_rangess128_round_mask: 3520 case X86::BI__builtin_ia32_reducesd_mask: 3521 case X86::BI__builtin_ia32_reducess_mask: 3522 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3523 case X86::BI__builtin_ia32_rndscaless_round_mask: 3524 ArgNum = 5; 3525 break; 3526 case X86::BI__builtin_ia32_vcvtsd2si64: 3527 case X86::BI__builtin_ia32_vcvtsd2si32: 3528 case X86::BI__builtin_ia32_vcvtsd2usi32: 3529 case X86::BI__builtin_ia32_vcvtsd2usi64: 3530 case X86::BI__builtin_ia32_vcvtss2si32: 3531 case X86::BI__builtin_ia32_vcvtss2si64: 3532 case X86::BI__builtin_ia32_vcvtss2usi32: 3533 case X86::BI__builtin_ia32_vcvtss2usi64: 3534 case X86::BI__builtin_ia32_sqrtpd512: 3535 case X86::BI__builtin_ia32_sqrtps512: 3536 ArgNum = 1; 3537 HasRC = true; 3538 break; 3539 case X86::BI__builtin_ia32_addpd512: 3540 case X86::BI__builtin_ia32_addps512: 3541 case X86::BI__builtin_ia32_divpd512: 3542 case X86::BI__builtin_ia32_divps512: 3543 case X86::BI__builtin_ia32_mulpd512: 3544 case X86::BI__builtin_ia32_mulps512: 3545 case X86::BI__builtin_ia32_subpd512: 3546 case X86::BI__builtin_ia32_subps512: 3547 case X86::BI__builtin_ia32_cvtsi2sd64: 3548 case X86::BI__builtin_ia32_cvtsi2ss32: 3549 case X86::BI__builtin_ia32_cvtsi2ss64: 3550 case X86::BI__builtin_ia32_cvtusi2sd64: 3551 case X86::BI__builtin_ia32_cvtusi2ss32: 3552 case X86::BI__builtin_ia32_cvtusi2ss64: 3553 ArgNum = 2; 3554 HasRC = true; 3555 break; 3556 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3557 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3558 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3559 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3560 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3561 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3562 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3563 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3564 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3565 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3566 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3567 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3568 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3569 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3570 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3571 ArgNum = 3; 3572 HasRC = true; 3573 break; 3574 case X86::BI__builtin_ia32_addss_round_mask: 3575 case X86::BI__builtin_ia32_addsd_round_mask: 3576 case X86::BI__builtin_ia32_divss_round_mask: 3577 case X86::BI__builtin_ia32_divsd_round_mask: 3578 case X86::BI__builtin_ia32_mulss_round_mask: 3579 case X86::BI__builtin_ia32_mulsd_round_mask: 3580 case X86::BI__builtin_ia32_subss_round_mask: 3581 case X86::BI__builtin_ia32_subsd_round_mask: 3582 case X86::BI__builtin_ia32_scalefpd512_mask: 3583 case X86::BI__builtin_ia32_scalefps512_mask: 3584 case X86::BI__builtin_ia32_scalefsd_round_mask: 3585 case X86::BI__builtin_ia32_scalefss_round_mask: 3586 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3587 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3588 case X86::BI__builtin_ia32_sqrtss_round_mask: 3589 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3590 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3591 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3592 case X86::BI__builtin_ia32_vfmaddss3_mask: 3593 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3594 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3595 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3596 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3597 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3598 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3599 case X86::BI__builtin_ia32_vfmaddps512_mask: 3600 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3601 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3602 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3603 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3604 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3605 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3606 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3607 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3608 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3609 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3610 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3611 ArgNum = 4; 3612 HasRC = true; 3613 break; 3614 } 3615 3616 llvm::APSInt Result; 3617 3618 // We can't check the value of a dependent argument. 3619 Expr *Arg = TheCall->getArg(ArgNum); 3620 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3621 return false; 3622 3623 // Check constant-ness first. 3624 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3625 return true; 3626 3627 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3628 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3629 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3630 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3631 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3632 Result == 8/*ROUND_NO_EXC*/ || 3633 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3634 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3635 return false; 3636 3637 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3638 << Arg->getSourceRange(); 3639 } 3640 3641 // Check if the gather/scatter scale is legal. 3642 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3643 CallExpr *TheCall) { 3644 unsigned ArgNum = 0; 3645 switch (BuiltinID) { 3646 default: 3647 return false; 3648 case X86::BI__builtin_ia32_gatherpfdpd: 3649 case X86::BI__builtin_ia32_gatherpfdps: 3650 case X86::BI__builtin_ia32_gatherpfqpd: 3651 case X86::BI__builtin_ia32_gatherpfqps: 3652 case X86::BI__builtin_ia32_scatterpfdpd: 3653 case X86::BI__builtin_ia32_scatterpfdps: 3654 case X86::BI__builtin_ia32_scatterpfqpd: 3655 case X86::BI__builtin_ia32_scatterpfqps: 3656 ArgNum = 3; 3657 break; 3658 case X86::BI__builtin_ia32_gatherd_pd: 3659 case X86::BI__builtin_ia32_gatherd_pd256: 3660 case X86::BI__builtin_ia32_gatherq_pd: 3661 case X86::BI__builtin_ia32_gatherq_pd256: 3662 case X86::BI__builtin_ia32_gatherd_ps: 3663 case X86::BI__builtin_ia32_gatherd_ps256: 3664 case X86::BI__builtin_ia32_gatherq_ps: 3665 case X86::BI__builtin_ia32_gatherq_ps256: 3666 case X86::BI__builtin_ia32_gatherd_q: 3667 case X86::BI__builtin_ia32_gatherd_q256: 3668 case X86::BI__builtin_ia32_gatherq_q: 3669 case X86::BI__builtin_ia32_gatherq_q256: 3670 case X86::BI__builtin_ia32_gatherd_d: 3671 case X86::BI__builtin_ia32_gatherd_d256: 3672 case X86::BI__builtin_ia32_gatherq_d: 3673 case X86::BI__builtin_ia32_gatherq_d256: 3674 case X86::BI__builtin_ia32_gather3div2df: 3675 case X86::BI__builtin_ia32_gather3div2di: 3676 case X86::BI__builtin_ia32_gather3div4df: 3677 case X86::BI__builtin_ia32_gather3div4di: 3678 case X86::BI__builtin_ia32_gather3div4sf: 3679 case X86::BI__builtin_ia32_gather3div4si: 3680 case X86::BI__builtin_ia32_gather3div8sf: 3681 case X86::BI__builtin_ia32_gather3div8si: 3682 case X86::BI__builtin_ia32_gather3siv2df: 3683 case X86::BI__builtin_ia32_gather3siv2di: 3684 case X86::BI__builtin_ia32_gather3siv4df: 3685 case X86::BI__builtin_ia32_gather3siv4di: 3686 case X86::BI__builtin_ia32_gather3siv4sf: 3687 case X86::BI__builtin_ia32_gather3siv4si: 3688 case X86::BI__builtin_ia32_gather3siv8sf: 3689 case X86::BI__builtin_ia32_gather3siv8si: 3690 case X86::BI__builtin_ia32_gathersiv8df: 3691 case X86::BI__builtin_ia32_gathersiv16sf: 3692 case X86::BI__builtin_ia32_gatherdiv8df: 3693 case X86::BI__builtin_ia32_gatherdiv16sf: 3694 case X86::BI__builtin_ia32_gathersiv8di: 3695 case X86::BI__builtin_ia32_gathersiv16si: 3696 case X86::BI__builtin_ia32_gatherdiv8di: 3697 case X86::BI__builtin_ia32_gatherdiv16si: 3698 case X86::BI__builtin_ia32_scatterdiv2df: 3699 case X86::BI__builtin_ia32_scatterdiv2di: 3700 case X86::BI__builtin_ia32_scatterdiv4df: 3701 case X86::BI__builtin_ia32_scatterdiv4di: 3702 case X86::BI__builtin_ia32_scatterdiv4sf: 3703 case X86::BI__builtin_ia32_scatterdiv4si: 3704 case X86::BI__builtin_ia32_scatterdiv8sf: 3705 case X86::BI__builtin_ia32_scatterdiv8si: 3706 case X86::BI__builtin_ia32_scattersiv2df: 3707 case X86::BI__builtin_ia32_scattersiv2di: 3708 case X86::BI__builtin_ia32_scattersiv4df: 3709 case X86::BI__builtin_ia32_scattersiv4di: 3710 case X86::BI__builtin_ia32_scattersiv4sf: 3711 case X86::BI__builtin_ia32_scattersiv4si: 3712 case X86::BI__builtin_ia32_scattersiv8sf: 3713 case X86::BI__builtin_ia32_scattersiv8si: 3714 case X86::BI__builtin_ia32_scattersiv8df: 3715 case X86::BI__builtin_ia32_scattersiv16sf: 3716 case X86::BI__builtin_ia32_scatterdiv8df: 3717 case X86::BI__builtin_ia32_scatterdiv16sf: 3718 case X86::BI__builtin_ia32_scattersiv8di: 3719 case X86::BI__builtin_ia32_scattersiv16si: 3720 case X86::BI__builtin_ia32_scatterdiv8di: 3721 case X86::BI__builtin_ia32_scatterdiv16si: 3722 ArgNum = 4; 3723 break; 3724 } 3725 3726 llvm::APSInt Result; 3727 3728 // We can't check the value of a dependent argument. 3729 Expr *Arg = TheCall->getArg(ArgNum); 3730 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3731 return false; 3732 3733 // Check constant-ness first. 3734 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3735 return true; 3736 3737 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3738 return false; 3739 3740 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3741 << Arg->getSourceRange(); 3742 } 3743 3744 static bool isX86_32Builtin(unsigned BuiltinID) { 3745 // These builtins only work on x86-32 targets. 3746 switch (BuiltinID) { 3747 case X86::BI__builtin_ia32_readeflags_u32: 3748 case X86::BI__builtin_ia32_writeeflags_u32: 3749 return true; 3750 } 3751 3752 return false; 3753 } 3754 3755 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3756 if (BuiltinID == X86::BI__builtin_cpu_supports) 3757 return SemaBuiltinCpuSupports(*this, TheCall); 3758 3759 if (BuiltinID == X86::BI__builtin_cpu_is) 3760 return SemaBuiltinCpuIs(*this, TheCall); 3761 3762 // Check for 32-bit only builtins on a 64-bit target. 3763 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3764 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3765 return Diag(TheCall->getCallee()->getBeginLoc(), 3766 diag::err_32_bit_builtin_64_bit_tgt); 3767 3768 // If the intrinsic has rounding or SAE make sure its valid. 3769 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3770 return true; 3771 3772 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3773 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3774 return true; 3775 3776 // For intrinsics which take an immediate value as part of the instruction, 3777 // range check them here. 3778 int i = 0, l = 0, u = 0; 3779 switch (BuiltinID) { 3780 default: 3781 return false; 3782 case X86::BI__builtin_ia32_vec_ext_v2si: 3783 case X86::BI__builtin_ia32_vec_ext_v2di: 3784 case X86::BI__builtin_ia32_vextractf128_pd256: 3785 case X86::BI__builtin_ia32_vextractf128_ps256: 3786 case X86::BI__builtin_ia32_vextractf128_si256: 3787 case X86::BI__builtin_ia32_extract128i256: 3788 case X86::BI__builtin_ia32_extractf64x4_mask: 3789 case X86::BI__builtin_ia32_extracti64x4_mask: 3790 case X86::BI__builtin_ia32_extractf32x8_mask: 3791 case X86::BI__builtin_ia32_extracti32x8_mask: 3792 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3793 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3794 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3795 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3796 i = 1; l = 0; u = 1; 3797 break; 3798 case X86::BI__builtin_ia32_vec_set_v2di: 3799 case X86::BI__builtin_ia32_vinsertf128_pd256: 3800 case X86::BI__builtin_ia32_vinsertf128_ps256: 3801 case X86::BI__builtin_ia32_vinsertf128_si256: 3802 case X86::BI__builtin_ia32_insert128i256: 3803 case X86::BI__builtin_ia32_insertf32x8: 3804 case X86::BI__builtin_ia32_inserti32x8: 3805 case X86::BI__builtin_ia32_insertf64x4: 3806 case X86::BI__builtin_ia32_inserti64x4: 3807 case X86::BI__builtin_ia32_insertf64x2_256: 3808 case X86::BI__builtin_ia32_inserti64x2_256: 3809 case X86::BI__builtin_ia32_insertf32x4_256: 3810 case X86::BI__builtin_ia32_inserti32x4_256: 3811 i = 2; l = 0; u = 1; 3812 break; 3813 case X86::BI__builtin_ia32_vpermilpd: 3814 case X86::BI__builtin_ia32_vec_ext_v4hi: 3815 case X86::BI__builtin_ia32_vec_ext_v4si: 3816 case X86::BI__builtin_ia32_vec_ext_v4sf: 3817 case X86::BI__builtin_ia32_vec_ext_v4di: 3818 case X86::BI__builtin_ia32_extractf32x4_mask: 3819 case X86::BI__builtin_ia32_extracti32x4_mask: 3820 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3821 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3822 i = 1; l = 0; u = 3; 3823 break; 3824 case X86::BI_mm_prefetch: 3825 case X86::BI__builtin_ia32_vec_ext_v8hi: 3826 case X86::BI__builtin_ia32_vec_ext_v8si: 3827 i = 1; l = 0; u = 7; 3828 break; 3829 case X86::BI__builtin_ia32_sha1rnds4: 3830 case X86::BI__builtin_ia32_blendpd: 3831 case X86::BI__builtin_ia32_shufpd: 3832 case X86::BI__builtin_ia32_vec_set_v4hi: 3833 case X86::BI__builtin_ia32_vec_set_v4si: 3834 case X86::BI__builtin_ia32_vec_set_v4di: 3835 case X86::BI__builtin_ia32_shuf_f32x4_256: 3836 case X86::BI__builtin_ia32_shuf_f64x2_256: 3837 case X86::BI__builtin_ia32_shuf_i32x4_256: 3838 case X86::BI__builtin_ia32_shuf_i64x2_256: 3839 case X86::BI__builtin_ia32_insertf64x2_512: 3840 case X86::BI__builtin_ia32_inserti64x2_512: 3841 case X86::BI__builtin_ia32_insertf32x4: 3842 case X86::BI__builtin_ia32_inserti32x4: 3843 i = 2; l = 0; u = 3; 3844 break; 3845 case X86::BI__builtin_ia32_vpermil2pd: 3846 case X86::BI__builtin_ia32_vpermil2pd256: 3847 case X86::BI__builtin_ia32_vpermil2ps: 3848 case X86::BI__builtin_ia32_vpermil2ps256: 3849 i = 3; l = 0; u = 3; 3850 break; 3851 case X86::BI__builtin_ia32_cmpb128_mask: 3852 case X86::BI__builtin_ia32_cmpw128_mask: 3853 case X86::BI__builtin_ia32_cmpd128_mask: 3854 case X86::BI__builtin_ia32_cmpq128_mask: 3855 case X86::BI__builtin_ia32_cmpb256_mask: 3856 case X86::BI__builtin_ia32_cmpw256_mask: 3857 case X86::BI__builtin_ia32_cmpd256_mask: 3858 case X86::BI__builtin_ia32_cmpq256_mask: 3859 case X86::BI__builtin_ia32_cmpb512_mask: 3860 case X86::BI__builtin_ia32_cmpw512_mask: 3861 case X86::BI__builtin_ia32_cmpd512_mask: 3862 case X86::BI__builtin_ia32_cmpq512_mask: 3863 case X86::BI__builtin_ia32_ucmpb128_mask: 3864 case X86::BI__builtin_ia32_ucmpw128_mask: 3865 case X86::BI__builtin_ia32_ucmpd128_mask: 3866 case X86::BI__builtin_ia32_ucmpq128_mask: 3867 case X86::BI__builtin_ia32_ucmpb256_mask: 3868 case X86::BI__builtin_ia32_ucmpw256_mask: 3869 case X86::BI__builtin_ia32_ucmpd256_mask: 3870 case X86::BI__builtin_ia32_ucmpq256_mask: 3871 case X86::BI__builtin_ia32_ucmpb512_mask: 3872 case X86::BI__builtin_ia32_ucmpw512_mask: 3873 case X86::BI__builtin_ia32_ucmpd512_mask: 3874 case X86::BI__builtin_ia32_ucmpq512_mask: 3875 case X86::BI__builtin_ia32_vpcomub: 3876 case X86::BI__builtin_ia32_vpcomuw: 3877 case X86::BI__builtin_ia32_vpcomud: 3878 case X86::BI__builtin_ia32_vpcomuq: 3879 case X86::BI__builtin_ia32_vpcomb: 3880 case X86::BI__builtin_ia32_vpcomw: 3881 case X86::BI__builtin_ia32_vpcomd: 3882 case X86::BI__builtin_ia32_vpcomq: 3883 case X86::BI__builtin_ia32_vec_set_v8hi: 3884 case X86::BI__builtin_ia32_vec_set_v8si: 3885 i = 2; l = 0; u = 7; 3886 break; 3887 case X86::BI__builtin_ia32_vpermilpd256: 3888 case X86::BI__builtin_ia32_roundps: 3889 case X86::BI__builtin_ia32_roundpd: 3890 case X86::BI__builtin_ia32_roundps256: 3891 case X86::BI__builtin_ia32_roundpd256: 3892 case X86::BI__builtin_ia32_getmantpd128_mask: 3893 case X86::BI__builtin_ia32_getmantpd256_mask: 3894 case X86::BI__builtin_ia32_getmantps128_mask: 3895 case X86::BI__builtin_ia32_getmantps256_mask: 3896 case X86::BI__builtin_ia32_getmantpd512_mask: 3897 case X86::BI__builtin_ia32_getmantps512_mask: 3898 case X86::BI__builtin_ia32_vec_ext_v16qi: 3899 case X86::BI__builtin_ia32_vec_ext_v16hi: 3900 i = 1; l = 0; u = 15; 3901 break; 3902 case X86::BI__builtin_ia32_pblendd128: 3903 case X86::BI__builtin_ia32_blendps: 3904 case X86::BI__builtin_ia32_blendpd256: 3905 case X86::BI__builtin_ia32_shufpd256: 3906 case X86::BI__builtin_ia32_roundss: 3907 case X86::BI__builtin_ia32_roundsd: 3908 case X86::BI__builtin_ia32_rangepd128_mask: 3909 case X86::BI__builtin_ia32_rangepd256_mask: 3910 case X86::BI__builtin_ia32_rangepd512_mask: 3911 case X86::BI__builtin_ia32_rangeps128_mask: 3912 case X86::BI__builtin_ia32_rangeps256_mask: 3913 case X86::BI__builtin_ia32_rangeps512_mask: 3914 case X86::BI__builtin_ia32_getmantsd_round_mask: 3915 case X86::BI__builtin_ia32_getmantss_round_mask: 3916 case X86::BI__builtin_ia32_vec_set_v16qi: 3917 case X86::BI__builtin_ia32_vec_set_v16hi: 3918 i = 2; l = 0; u = 15; 3919 break; 3920 case X86::BI__builtin_ia32_vec_ext_v32qi: 3921 i = 1; l = 0; u = 31; 3922 break; 3923 case X86::BI__builtin_ia32_cmpps: 3924 case X86::BI__builtin_ia32_cmpss: 3925 case X86::BI__builtin_ia32_cmppd: 3926 case X86::BI__builtin_ia32_cmpsd: 3927 case X86::BI__builtin_ia32_cmpps256: 3928 case X86::BI__builtin_ia32_cmppd256: 3929 case X86::BI__builtin_ia32_cmpps128_mask: 3930 case X86::BI__builtin_ia32_cmppd128_mask: 3931 case X86::BI__builtin_ia32_cmpps256_mask: 3932 case X86::BI__builtin_ia32_cmppd256_mask: 3933 case X86::BI__builtin_ia32_cmpps512_mask: 3934 case X86::BI__builtin_ia32_cmppd512_mask: 3935 case X86::BI__builtin_ia32_cmpsd_mask: 3936 case X86::BI__builtin_ia32_cmpss_mask: 3937 case X86::BI__builtin_ia32_vec_set_v32qi: 3938 i = 2; l = 0; u = 31; 3939 break; 3940 case X86::BI__builtin_ia32_permdf256: 3941 case X86::BI__builtin_ia32_permdi256: 3942 case X86::BI__builtin_ia32_permdf512: 3943 case X86::BI__builtin_ia32_permdi512: 3944 case X86::BI__builtin_ia32_vpermilps: 3945 case X86::BI__builtin_ia32_vpermilps256: 3946 case X86::BI__builtin_ia32_vpermilpd512: 3947 case X86::BI__builtin_ia32_vpermilps512: 3948 case X86::BI__builtin_ia32_pshufd: 3949 case X86::BI__builtin_ia32_pshufd256: 3950 case X86::BI__builtin_ia32_pshufd512: 3951 case X86::BI__builtin_ia32_pshufhw: 3952 case X86::BI__builtin_ia32_pshufhw256: 3953 case X86::BI__builtin_ia32_pshufhw512: 3954 case X86::BI__builtin_ia32_pshuflw: 3955 case X86::BI__builtin_ia32_pshuflw256: 3956 case X86::BI__builtin_ia32_pshuflw512: 3957 case X86::BI__builtin_ia32_vcvtps2ph: 3958 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3959 case X86::BI__builtin_ia32_vcvtps2ph256: 3960 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3961 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3962 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3963 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3964 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3965 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3966 case X86::BI__builtin_ia32_rndscaleps_mask: 3967 case X86::BI__builtin_ia32_rndscalepd_mask: 3968 case X86::BI__builtin_ia32_reducepd128_mask: 3969 case X86::BI__builtin_ia32_reducepd256_mask: 3970 case X86::BI__builtin_ia32_reducepd512_mask: 3971 case X86::BI__builtin_ia32_reduceps128_mask: 3972 case X86::BI__builtin_ia32_reduceps256_mask: 3973 case X86::BI__builtin_ia32_reduceps512_mask: 3974 case X86::BI__builtin_ia32_prold512: 3975 case X86::BI__builtin_ia32_prolq512: 3976 case X86::BI__builtin_ia32_prold128: 3977 case X86::BI__builtin_ia32_prold256: 3978 case X86::BI__builtin_ia32_prolq128: 3979 case X86::BI__builtin_ia32_prolq256: 3980 case X86::BI__builtin_ia32_prord512: 3981 case X86::BI__builtin_ia32_prorq512: 3982 case X86::BI__builtin_ia32_prord128: 3983 case X86::BI__builtin_ia32_prord256: 3984 case X86::BI__builtin_ia32_prorq128: 3985 case X86::BI__builtin_ia32_prorq256: 3986 case X86::BI__builtin_ia32_fpclasspd128_mask: 3987 case X86::BI__builtin_ia32_fpclasspd256_mask: 3988 case X86::BI__builtin_ia32_fpclassps128_mask: 3989 case X86::BI__builtin_ia32_fpclassps256_mask: 3990 case X86::BI__builtin_ia32_fpclassps512_mask: 3991 case X86::BI__builtin_ia32_fpclasspd512_mask: 3992 case X86::BI__builtin_ia32_fpclasssd_mask: 3993 case X86::BI__builtin_ia32_fpclassss_mask: 3994 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3995 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3996 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3997 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3998 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3999 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4000 case X86::BI__builtin_ia32_kshiftliqi: 4001 case X86::BI__builtin_ia32_kshiftlihi: 4002 case X86::BI__builtin_ia32_kshiftlisi: 4003 case X86::BI__builtin_ia32_kshiftlidi: 4004 case X86::BI__builtin_ia32_kshiftriqi: 4005 case X86::BI__builtin_ia32_kshiftrihi: 4006 case X86::BI__builtin_ia32_kshiftrisi: 4007 case X86::BI__builtin_ia32_kshiftridi: 4008 i = 1; l = 0; u = 255; 4009 break; 4010 case X86::BI__builtin_ia32_vperm2f128_pd256: 4011 case X86::BI__builtin_ia32_vperm2f128_ps256: 4012 case X86::BI__builtin_ia32_vperm2f128_si256: 4013 case X86::BI__builtin_ia32_permti256: 4014 case X86::BI__builtin_ia32_pblendw128: 4015 case X86::BI__builtin_ia32_pblendw256: 4016 case X86::BI__builtin_ia32_blendps256: 4017 case X86::BI__builtin_ia32_pblendd256: 4018 case X86::BI__builtin_ia32_palignr128: 4019 case X86::BI__builtin_ia32_palignr256: 4020 case X86::BI__builtin_ia32_palignr512: 4021 case X86::BI__builtin_ia32_alignq512: 4022 case X86::BI__builtin_ia32_alignd512: 4023 case X86::BI__builtin_ia32_alignd128: 4024 case X86::BI__builtin_ia32_alignd256: 4025 case X86::BI__builtin_ia32_alignq128: 4026 case X86::BI__builtin_ia32_alignq256: 4027 case X86::BI__builtin_ia32_vcomisd: 4028 case X86::BI__builtin_ia32_vcomiss: 4029 case X86::BI__builtin_ia32_shuf_f32x4: 4030 case X86::BI__builtin_ia32_shuf_f64x2: 4031 case X86::BI__builtin_ia32_shuf_i32x4: 4032 case X86::BI__builtin_ia32_shuf_i64x2: 4033 case X86::BI__builtin_ia32_shufpd512: 4034 case X86::BI__builtin_ia32_shufps: 4035 case X86::BI__builtin_ia32_shufps256: 4036 case X86::BI__builtin_ia32_shufps512: 4037 case X86::BI__builtin_ia32_dbpsadbw128: 4038 case X86::BI__builtin_ia32_dbpsadbw256: 4039 case X86::BI__builtin_ia32_dbpsadbw512: 4040 case X86::BI__builtin_ia32_vpshldd128: 4041 case X86::BI__builtin_ia32_vpshldd256: 4042 case X86::BI__builtin_ia32_vpshldd512: 4043 case X86::BI__builtin_ia32_vpshldq128: 4044 case X86::BI__builtin_ia32_vpshldq256: 4045 case X86::BI__builtin_ia32_vpshldq512: 4046 case X86::BI__builtin_ia32_vpshldw128: 4047 case X86::BI__builtin_ia32_vpshldw256: 4048 case X86::BI__builtin_ia32_vpshldw512: 4049 case X86::BI__builtin_ia32_vpshrdd128: 4050 case X86::BI__builtin_ia32_vpshrdd256: 4051 case X86::BI__builtin_ia32_vpshrdd512: 4052 case X86::BI__builtin_ia32_vpshrdq128: 4053 case X86::BI__builtin_ia32_vpshrdq256: 4054 case X86::BI__builtin_ia32_vpshrdq512: 4055 case X86::BI__builtin_ia32_vpshrdw128: 4056 case X86::BI__builtin_ia32_vpshrdw256: 4057 case X86::BI__builtin_ia32_vpshrdw512: 4058 i = 2; l = 0; u = 255; 4059 break; 4060 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4061 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4062 case X86::BI__builtin_ia32_fixupimmps512_mask: 4063 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4064 case X86::BI__builtin_ia32_fixupimmsd_mask: 4065 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4066 case X86::BI__builtin_ia32_fixupimmss_mask: 4067 case X86::BI__builtin_ia32_fixupimmss_maskz: 4068 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4069 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4070 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4071 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4072 case X86::BI__builtin_ia32_fixupimmps128_mask: 4073 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4074 case X86::BI__builtin_ia32_fixupimmps256_mask: 4075 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4076 case X86::BI__builtin_ia32_pternlogd512_mask: 4077 case X86::BI__builtin_ia32_pternlogd512_maskz: 4078 case X86::BI__builtin_ia32_pternlogq512_mask: 4079 case X86::BI__builtin_ia32_pternlogq512_maskz: 4080 case X86::BI__builtin_ia32_pternlogd128_mask: 4081 case X86::BI__builtin_ia32_pternlogd128_maskz: 4082 case X86::BI__builtin_ia32_pternlogd256_mask: 4083 case X86::BI__builtin_ia32_pternlogd256_maskz: 4084 case X86::BI__builtin_ia32_pternlogq128_mask: 4085 case X86::BI__builtin_ia32_pternlogq128_maskz: 4086 case X86::BI__builtin_ia32_pternlogq256_mask: 4087 case X86::BI__builtin_ia32_pternlogq256_maskz: 4088 i = 3; l = 0; u = 255; 4089 break; 4090 case X86::BI__builtin_ia32_gatherpfdpd: 4091 case X86::BI__builtin_ia32_gatherpfdps: 4092 case X86::BI__builtin_ia32_gatherpfqpd: 4093 case X86::BI__builtin_ia32_gatherpfqps: 4094 case X86::BI__builtin_ia32_scatterpfdpd: 4095 case X86::BI__builtin_ia32_scatterpfdps: 4096 case X86::BI__builtin_ia32_scatterpfqpd: 4097 case X86::BI__builtin_ia32_scatterpfqps: 4098 i = 4; l = 2; u = 3; 4099 break; 4100 case X86::BI__builtin_ia32_reducesd_mask: 4101 case X86::BI__builtin_ia32_reducess_mask: 4102 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4103 case X86::BI__builtin_ia32_rndscaless_round_mask: 4104 i = 4; l = 0; u = 255; 4105 break; 4106 } 4107 4108 // Note that we don't force a hard error on the range check here, allowing 4109 // template-generated or macro-generated dead code to potentially have out-of- 4110 // range values. These need to code generate, but don't need to necessarily 4111 // make any sense. We use a warning that defaults to an error. 4112 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4113 } 4114 4115 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4116 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4117 /// Returns true when the format fits the function and the FormatStringInfo has 4118 /// been populated. 4119 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4120 FormatStringInfo *FSI) { 4121 FSI->HasVAListArg = Format->getFirstArg() == 0; 4122 FSI->FormatIdx = Format->getFormatIdx() - 1; 4123 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4124 4125 // The way the format attribute works in GCC, the implicit this argument 4126 // of member functions is counted. However, it doesn't appear in our own 4127 // lists, so decrement format_idx in that case. 4128 if (IsCXXMember) { 4129 if(FSI->FormatIdx == 0) 4130 return false; 4131 --FSI->FormatIdx; 4132 if (FSI->FirstDataArg != 0) 4133 --FSI->FirstDataArg; 4134 } 4135 return true; 4136 } 4137 4138 /// Checks if a the given expression evaluates to null. 4139 /// 4140 /// Returns true if the value evaluates to null. 4141 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4142 // If the expression has non-null type, it doesn't evaluate to null. 4143 if (auto nullability 4144 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4145 if (*nullability == NullabilityKind::NonNull) 4146 return false; 4147 } 4148 4149 // As a special case, transparent unions initialized with zero are 4150 // considered null for the purposes of the nonnull attribute. 4151 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4152 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4153 if (const CompoundLiteralExpr *CLE = 4154 dyn_cast<CompoundLiteralExpr>(Expr)) 4155 if (const InitListExpr *ILE = 4156 dyn_cast<InitListExpr>(CLE->getInitializer())) 4157 Expr = ILE->getInit(0); 4158 } 4159 4160 bool Result; 4161 return (!Expr->isValueDependent() && 4162 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4163 !Result); 4164 } 4165 4166 static void CheckNonNullArgument(Sema &S, 4167 const Expr *ArgExpr, 4168 SourceLocation CallSiteLoc) { 4169 if (CheckNonNullExpr(S, ArgExpr)) 4170 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4171 S.PDiag(diag::warn_null_arg) 4172 << ArgExpr->getSourceRange()); 4173 } 4174 4175 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4176 FormatStringInfo FSI; 4177 if ((GetFormatStringType(Format) == FST_NSString) && 4178 getFormatStringInfo(Format, false, &FSI)) { 4179 Idx = FSI.FormatIdx; 4180 return true; 4181 } 4182 return false; 4183 } 4184 4185 /// Diagnose use of %s directive in an NSString which is being passed 4186 /// as formatting string to formatting method. 4187 static void 4188 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4189 const NamedDecl *FDecl, 4190 Expr **Args, 4191 unsigned NumArgs) { 4192 unsigned Idx = 0; 4193 bool Format = false; 4194 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4195 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4196 Idx = 2; 4197 Format = true; 4198 } 4199 else 4200 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4201 if (S.GetFormatNSStringIdx(I, Idx)) { 4202 Format = true; 4203 break; 4204 } 4205 } 4206 if (!Format || NumArgs <= Idx) 4207 return; 4208 const Expr *FormatExpr = Args[Idx]; 4209 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4210 FormatExpr = CSCE->getSubExpr(); 4211 const StringLiteral *FormatString; 4212 if (const ObjCStringLiteral *OSL = 4213 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4214 FormatString = OSL->getString(); 4215 else 4216 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4217 if (!FormatString) 4218 return; 4219 if (S.FormatStringHasSArg(FormatString)) { 4220 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4221 << "%s" << 1 << 1; 4222 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4223 << FDecl->getDeclName(); 4224 } 4225 } 4226 4227 /// Determine whether the given type has a non-null nullability annotation. 4228 static bool isNonNullType(ASTContext &ctx, QualType type) { 4229 if (auto nullability = type->getNullability(ctx)) 4230 return *nullability == NullabilityKind::NonNull; 4231 4232 return false; 4233 } 4234 4235 static void CheckNonNullArguments(Sema &S, 4236 const NamedDecl *FDecl, 4237 const FunctionProtoType *Proto, 4238 ArrayRef<const Expr *> Args, 4239 SourceLocation CallSiteLoc) { 4240 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4241 4242 // Already checked by by constant evaluator. 4243 if (S.isConstantEvaluated()) 4244 return; 4245 // Check the attributes attached to the method/function itself. 4246 llvm::SmallBitVector NonNullArgs; 4247 if (FDecl) { 4248 // Handle the nonnull attribute on the function/method declaration itself. 4249 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4250 if (!NonNull->args_size()) { 4251 // Easy case: all pointer arguments are nonnull. 4252 for (const auto *Arg : Args) 4253 if (S.isValidPointerAttrType(Arg->getType())) 4254 CheckNonNullArgument(S, Arg, CallSiteLoc); 4255 return; 4256 } 4257 4258 for (const ParamIdx &Idx : NonNull->args()) { 4259 unsigned IdxAST = Idx.getASTIndex(); 4260 if (IdxAST >= Args.size()) 4261 continue; 4262 if (NonNullArgs.empty()) 4263 NonNullArgs.resize(Args.size()); 4264 NonNullArgs.set(IdxAST); 4265 } 4266 } 4267 } 4268 4269 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4270 // Handle the nonnull attribute on the parameters of the 4271 // function/method. 4272 ArrayRef<ParmVarDecl*> parms; 4273 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4274 parms = FD->parameters(); 4275 else 4276 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4277 4278 unsigned ParamIndex = 0; 4279 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4280 I != E; ++I, ++ParamIndex) { 4281 const ParmVarDecl *PVD = *I; 4282 if (PVD->hasAttr<NonNullAttr>() || 4283 isNonNullType(S.Context, PVD->getType())) { 4284 if (NonNullArgs.empty()) 4285 NonNullArgs.resize(Args.size()); 4286 4287 NonNullArgs.set(ParamIndex); 4288 } 4289 } 4290 } else { 4291 // If we have a non-function, non-method declaration but no 4292 // function prototype, try to dig out the function prototype. 4293 if (!Proto) { 4294 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4295 QualType type = VD->getType().getNonReferenceType(); 4296 if (auto pointerType = type->getAs<PointerType>()) 4297 type = pointerType->getPointeeType(); 4298 else if (auto blockType = type->getAs<BlockPointerType>()) 4299 type = blockType->getPointeeType(); 4300 // FIXME: data member pointers? 4301 4302 // Dig out the function prototype, if there is one. 4303 Proto = type->getAs<FunctionProtoType>(); 4304 } 4305 } 4306 4307 // Fill in non-null argument information from the nullability 4308 // information on the parameter types (if we have them). 4309 if (Proto) { 4310 unsigned Index = 0; 4311 for (auto paramType : Proto->getParamTypes()) { 4312 if (isNonNullType(S.Context, paramType)) { 4313 if (NonNullArgs.empty()) 4314 NonNullArgs.resize(Args.size()); 4315 4316 NonNullArgs.set(Index); 4317 } 4318 4319 ++Index; 4320 } 4321 } 4322 } 4323 4324 // Check for non-null arguments. 4325 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4326 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4327 if (NonNullArgs[ArgIndex]) 4328 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4329 } 4330 } 4331 4332 /// Handles the checks for format strings, non-POD arguments to vararg 4333 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4334 /// attributes. 4335 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4336 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4337 bool IsMemberFunction, SourceLocation Loc, 4338 SourceRange Range, VariadicCallType CallType) { 4339 // FIXME: We should check as much as we can in the template definition. 4340 if (CurContext->isDependentContext()) 4341 return; 4342 4343 // Printf and scanf checking. 4344 llvm::SmallBitVector CheckedVarArgs; 4345 if (FDecl) { 4346 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4347 // Only create vector if there are format attributes. 4348 CheckedVarArgs.resize(Args.size()); 4349 4350 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4351 CheckedVarArgs); 4352 } 4353 } 4354 4355 // Refuse POD arguments that weren't caught by the format string 4356 // checks above. 4357 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4358 if (CallType != VariadicDoesNotApply && 4359 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4360 unsigned NumParams = Proto ? Proto->getNumParams() 4361 : FDecl && isa<FunctionDecl>(FDecl) 4362 ? cast<FunctionDecl>(FDecl)->getNumParams() 4363 : FDecl && isa<ObjCMethodDecl>(FDecl) 4364 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4365 : 0; 4366 4367 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4368 // Args[ArgIdx] can be null in malformed code. 4369 if (const Expr *Arg = Args[ArgIdx]) { 4370 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4371 checkVariadicArgument(Arg, CallType); 4372 } 4373 } 4374 } 4375 4376 if (FDecl || Proto) { 4377 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4378 4379 // Type safety checking. 4380 if (FDecl) { 4381 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4382 CheckArgumentWithTypeTag(I, Args, Loc); 4383 } 4384 } 4385 4386 if (FD) 4387 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4388 } 4389 4390 /// CheckConstructorCall - Check a constructor call for correctness and safety 4391 /// properties not enforced by the C type system. 4392 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4393 ArrayRef<const Expr *> Args, 4394 const FunctionProtoType *Proto, 4395 SourceLocation Loc) { 4396 VariadicCallType CallType = 4397 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4398 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4399 Loc, SourceRange(), CallType); 4400 } 4401 4402 /// CheckFunctionCall - Check a direct function call for various correctness 4403 /// and safety properties not strictly enforced by the C type system. 4404 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4405 const FunctionProtoType *Proto) { 4406 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4407 isa<CXXMethodDecl>(FDecl); 4408 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4409 IsMemberOperatorCall; 4410 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4411 TheCall->getCallee()); 4412 Expr** Args = TheCall->getArgs(); 4413 unsigned NumArgs = TheCall->getNumArgs(); 4414 4415 Expr *ImplicitThis = nullptr; 4416 if (IsMemberOperatorCall) { 4417 // If this is a call to a member operator, hide the first argument 4418 // from checkCall. 4419 // FIXME: Our choice of AST representation here is less than ideal. 4420 ImplicitThis = Args[0]; 4421 ++Args; 4422 --NumArgs; 4423 } else if (IsMemberFunction) 4424 ImplicitThis = 4425 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4426 4427 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4428 IsMemberFunction, TheCall->getRParenLoc(), 4429 TheCall->getCallee()->getSourceRange(), CallType); 4430 4431 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4432 // None of the checks below are needed for functions that don't have 4433 // simple names (e.g., C++ conversion functions). 4434 if (!FnInfo) 4435 return false; 4436 4437 CheckAbsoluteValueFunction(TheCall, FDecl); 4438 CheckMaxUnsignedZero(TheCall, FDecl); 4439 4440 if (getLangOpts().ObjC) 4441 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4442 4443 unsigned CMId = FDecl->getMemoryFunctionKind(); 4444 if (CMId == 0) 4445 return false; 4446 4447 // Handle memory setting and copying functions. 4448 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4449 CheckStrlcpycatArguments(TheCall, FnInfo); 4450 else if (CMId == Builtin::BIstrncat) 4451 CheckStrncatArguments(TheCall, FnInfo); 4452 else 4453 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4454 4455 return false; 4456 } 4457 4458 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4459 ArrayRef<const Expr *> Args) { 4460 VariadicCallType CallType = 4461 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4462 4463 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4464 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4465 CallType); 4466 4467 return false; 4468 } 4469 4470 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4471 const FunctionProtoType *Proto) { 4472 QualType Ty; 4473 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4474 Ty = V->getType().getNonReferenceType(); 4475 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4476 Ty = F->getType().getNonReferenceType(); 4477 else 4478 return false; 4479 4480 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4481 !Ty->isFunctionProtoType()) 4482 return false; 4483 4484 VariadicCallType CallType; 4485 if (!Proto || !Proto->isVariadic()) { 4486 CallType = VariadicDoesNotApply; 4487 } else if (Ty->isBlockPointerType()) { 4488 CallType = VariadicBlock; 4489 } else { // Ty->isFunctionPointerType() 4490 CallType = VariadicFunction; 4491 } 4492 4493 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4494 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4495 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4496 TheCall->getCallee()->getSourceRange(), CallType); 4497 4498 return false; 4499 } 4500 4501 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4502 /// such as function pointers returned from functions. 4503 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4504 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4505 TheCall->getCallee()); 4506 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4507 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4508 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4509 TheCall->getCallee()->getSourceRange(), CallType); 4510 4511 return false; 4512 } 4513 4514 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4515 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4516 return false; 4517 4518 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4519 switch (Op) { 4520 case AtomicExpr::AO__c11_atomic_init: 4521 case AtomicExpr::AO__opencl_atomic_init: 4522 llvm_unreachable("There is no ordering argument for an init"); 4523 4524 case AtomicExpr::AO__c11_atomic_load: 4525 case AtomicExpr::AO__opencl_atomic_load: 4526 case AtomicExpr::AO__atomic_load_n: 4527 case AtomicExpr::AO__atomic_load: 4528 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4529 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4530 4531 case AtomicExpr::AO__c11_atomic_store: 4532 case AtomicExpr::AO__opencl_atomic_store: 4533 case AtomicExpr::AO__atomic_store: 4534 case AtomicExpr::AO__atomic_store_n: 4535 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4536 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4537 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4538 4539 default: 4540 return true; 4541 } 4542 } 4543 4544 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4545 AtomicExpr::AtomicOp Op) { 4546 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4547 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4548 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4549 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4550 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4551 Op); 4552 } 4553 4554 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4555 SourceLocation RParenLoc, MultiExprArg Args, 4556 AtomicExpr::AtomicOp Op, 4557 AtomicArgumentOrder ArgOrder) { 4558 // All the non-OpenCL operations take one of the following forms. 4559 // The OpenCL operations take the __c11 forms with one extra argument for 4560 // synchronization scope. 4561 enum { 4562 // C __c11_atomic_init(A *, C) 4563 Init, 4564 4565 // C __c11_atomic_load(A *, int) 4566 Load, 4567 4568 // void __atomic_load(A *, CP, int) 4569 LoadCopy, 4570 4571 // void __atomic_store(A *, CP, int) 4572 Copy, 4573 4574 // C __c11_atomic_add(A *, M, int) 4575 Arithmetic, 4576 4577 // C __atomic_exchange_n(A *, CP, int) 4578 Xchg, 4579 4580 // void __atomic_exchange(A *, C *, CP, int) 4581 GNUXchg, 4582 4583 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4584 C11CmpXchg, 4585 4586 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4587 GNUCmpXchg 4588 } Form = Init; 4589 4590 const unsigned NumForm = GNUCmpXchg + 1; 4591 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4592 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4593 // where: 4594 // C is an appropriate type, 4595 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4596 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4597 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4598 // the int parameters are for orderings. 4599 4600 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4601 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4602 "need to update code for modified forms"); 4603 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4604 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4605 AtomicExpr::AO__atomic_load, 4606 "need to update code for modified C11 atomics"); 4607 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4608 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4609 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4610 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4611 IsOpenCL; 4612 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4613 Op == AtomicExpr::AO__atomic_store_n || 4614 Op == AtomicExpr::AO__atomic_exchange_n || 4615 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4616 bool IsAddSub = false; 4617 4618 switch (Op) { 4619 case AtomicExpr::AO__c11_atomic_init: 4620 case AtomicExpr::AO__opencl_atomic_init: 4621 Form = Init; 4622 break; 4623 4624 case AtomicExpr::AO__c11_atomic_load: 4625 case AtomicExpr::AO__opencl_atomic_load: 4626 case AtomicExpr::AO__atomic_load_n: 4627 Form = Load; 4628 break; 4629 4630 case AtomicExpr::AO__atomic_load: 4631 Form = LoadCopy; 4632 break; 4633 4634 case AtomicExpr::AO__c11_atomic_store: 4635 case AtomicExpr::AO__opencl_atomic_store: 4636 case AtomicExpr::AO__atomic_store: 4637 case AtomicExpr::AO__atomic_store_n: 4638 Form = Copy; 4639 break; 4640 4641 case AtomicExpr::AO__c11_atomic_fetch_add: 4642 case AtomicExpr::AO__c11_atomic_fetch_sub: 4643 case AtomicExpr::AO__opencl_atomic_fetch_add: 4644 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4645 case AtomicExpr::AO__atomic_fetch_add: 4646 case AtomicExpr::AO__atomic_fetch_sub: 4647 case AtomicExpr::AO__atomic_add_fetch: 4648 case AtomicExpr::AO__atomic_sub_fetch: 4649 IsAddSub = true; 4650 LLVM_FALLTHROUGH; 4651 case AtomicExpr::AO__c11_atomic_fetch_and: 4652 case AtomicExpr::AO__c11_atomic_fetch_or: 4653 case AtomicExpr::AO__c11_atomic_fetch_xor: 4654 case AtomicExpr::AO__opencl_atomic_fetch_and: 4655 case AtomicExpr::AO__opencl_atomic_fetch_or: 4656 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4657 case AtomicExpr::AO__atomic_fetch_and: 4658 case AtomicExpr::AO__atomic_fetch_or: 4659 case AtomicExpr::AO__atomic_fetch_xor: 4660 case AtomicExpr::AO__atomic_fetch_nand: 4661 case AtomicExpr::AO__atomic_and_fetch: 4662 case AtomicExpr::AO__atomic_or_fetch: 4663 case AtomicExpr::AO__atomic_xor_fetch: 4664 case AtomicExpr::AO__atomic_nand_fetch: 4665 case AtomicExpr::AO__c11_atomic_fetch_min: 4666 case AtomicExpr::AO__c11_atomic_fetch_max: 4667 case AtomicExpr::AO__opencl_atomic_fetch_min: 4668 case AtomicExpr::AO__opencl_atomic_fetch_max: 4669 case AtomicExpr::AO__atomic_min_fetch: 4670 case AtomicExpr::AO__atomic_max_fetch: 4671 case AtomicExpr::AO__atomic_fetch_min: 4672 case AtomicExpr::AO__atomic_fetch_max: 4673 Form = Arithmetic; 4674 break; 4675 4676 case AtomicExpr::AO__c11_atomic_exchange: 4677 case AtomicExpr::AO__opencl_atomic_exchange: 4678 case AtomicExpr::AO__atomic_exchange_n: 4679 Form = Xchg; 4680 break; 4681 4682 case AtomicExpr::AO__atomic_exchange: 4683 Form = GNUXchg; 4684 break; 4685 4686 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4687 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4688 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4689 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4690 Form = C11CmpXchg; 4691 break; 4692 4693 case AtomicExpr::AO__atomic_compare_exchange: 4694 case AtomicExpr::AO__atomic_compare_exchange_n: 4695 Form = GNUCmpXchg; 4696 break; 4697 } 4698 4699 unsigned AdjustedNumArgs = NumArgs[Form]; 4700 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4701 ++AdjustedNumArgs; 4702 // Check we have the right number of arguments. 4703 if (Args.size() < AdjustedNumArgs) { 4704 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4705 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4706 << ExprRange; 4707 return ExprError(); 4708 } else if (Args.size() > AdjustedNumArgs) { 4709 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4710 diag::err_typecheck_call_too_many_args) 4711 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4712 << ExprRange; 4713 return ExprError(); 4714 } 4715 4716 // Inspect the first argument of the atomic operation. 4717 Expr *Ptr = Args[0]; 4718 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4719 if (ConvertedPtr.isInvalid()) 4720 return ExprError(); 4721 4722 Ptr = ConvertedPtr.get(); 4723 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4724 if (!pointerType) { 4725 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4726 << Ptr->getType() << Ptr->getSourceRange(); 4727 return ExprError(); 4728 } 4729 4730 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4731 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4732 QualType ValType = AtomTy; // 'C' 4733 if (IsC11) { 4734 if (!AtomTy->isAtomicType()) { 4735 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4736 << Ptr->getType() << Ptr->getSourceRange(); 4737 return ExprError(); 4738 } 4739 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4740 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4741 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4742 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4743 << Ptr->getSourceRange(); 4744 return ExprError(); 4745 } 4746 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4747 } else if (Form != Load && Form != LoadCopy) { 4748 if (ValType.isConstQualified()) { 4749 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4750 << Ptr->getType() << Ptr->getSourceRange(); 4751 return ExprError(); 4752 } 4753 } 4754 4755 // For an arithmetic operation, the implied arithmetic must be well-formed. 4756 if (Form == Arithmetic) { 4757 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4758 if (IsAddSub && !ValType->isIntegerType() 4759 && !ValType->isPointerType()) { 4760 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4761 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4762 return ExprError(); 4763 } 4764 if (!IsAddSub && !ValType->isIntegerType()) { 4765 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4766 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4767 return ExprError(); 4768 } 4769 if (IsC11 && ValType->isPointerType() && 4770 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4771 diag::err_incomplete_type)) { 4772 return ExprError(); 4773 } 4774 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4775 // For __atomic_*_n operations, the value type must be a scalar integral or 4776 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4777 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4778 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4779 return ExprError(); 4780 } 4781 4782 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4783 !AtomTy->isScalarType()) { 4784 // For GNU atomics, require a trivially-copyable type. This is not part of 4785 // the GNU atomics specification, but we enforce it for sanity. 4786 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4787 << Ptr->getType() << Ptr->getSourceRange(); 4788 return ExprError(); 4789 } 4790 4791 switch (ValType.getObjCLifetime()) { 4792 case Qualifiers::OCL_None: 4793 case Qualifiers::OCL_ExplicitNone: 4794 // okay 4795 break; 4796 4797 case Qualifiers::OCL_Weak: 4798 case Qualifiers::OCL_Strong: 4799 case Qualifiers::OCL_Autoreleasing: 4800 // FIXME: Can this happen? By this point, ValType should be known 4801 // to be trivially copyable. 4802 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4803 << ValType << Ptr->getSourceRange(); 4804 return ExprError(); 4805 } 4806 4807 // All atomic operations have an overload which takes a pointer to a volatile 4808 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4809 // into the result or the other operands. Similarly atomic_load takes a 4810 // pointer to a const 'A'. 4811 ValType.removeLocalVolatile(); 4812 ValType.removeLocalConst(); 4813 QualType ResultType = ValType; 4814 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4815 Form == Init) 4816 ResultType = Context.VoidTy; 4817 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4818 ResultType = Context.BoolTy; 4819 4820 // The type of a parameter passed 'by value'. In the GNU atomics, such 4821 // arguments are actually passed as pointers. 4822 QualType ByValType = ValType; // 'CP' 4823 bool IsPassedByAddress = false; 4824 if (!IsC11 && !IsN) { 4825 ByValType = Ptr->getType(); 4826 IsPassedByAddress = true; 4827 } 4828 4829 SmallVector<Expr *, 5> APIOrderedArgs; 4830 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4831 APIOrderedArgs.push_back(Args[0]); 4832 switch (Form) { 4833 case Init: 4834 case Load: 4835 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4836 break; 4837 case LoadCopy: 4838 case Copy: 4839 case Arithmetic: 4840 case Xchg: 4841 APIOrderedArgs.push_back(Args[2]); // Val1 4842 APIOrderedArgs.push_back(Args[1]); // Order 4843 break; 4844 case GNUXchg: 4845 APIOrderedArgs.push_back(Args[2]); // Val1 4846 APIOrderedArgs.push_back(Args[3]); // Val2 4847 APIOrderedArgs.push_back(Args[1]); // Order 4848 break; 4849 case C11CmpXchg: 4850 APIOrderedArgs.push_back(Args[2]); // Val1 4851 APIOrderedArgs.push_back(Args[4]); // Val2 4852 APIOrderedArgs.push_back(Args[1]); // Order 4853 APIOrderedArgs.push_back(Args[3]); // OrderFail 4854 break; 4855 case GNUCmpXchg: 4856 APIOrderedArgs.push_back(Args[2]); // Val1 4857 APIOrderedArgs.push_back(Args[4]); // Val2 4858 APIOrderedArgs.push_back(Args[5]); // Weak 4859 APIOrderedArgs.push_back(Args[1]); // Order 4860 APIOrderedArgs.push_back(Args[3]); // OrderFail 4861 break; 4862 } 4863 } else 4864 APIOrderedArgs.append(Args.begin(), Args.end()); 4865 4866 // The first argument's non-CV pointer type is used to deduce the type of 4867 // subsequent arguments, except for: 4868 // - weak flag (always converted to bool) 4869 // - memory order (always converted to int) 4870 // - scope (always converted to int) 4871 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4872 QualType Ty; 4873 if (i < NumVals[Form] + 1) { 4874 switch (i) { 4875 case 0: 4876 // The first argument is always a pointer. It has a fixed type. 4877 // It is always dereferenced, a nullptr is undefined. 4878 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4879 // Nothing else to do: we already know all we want about this pointer. 4880 continue; 4881 case 1: 4882 // The second argument is the non-atomic operand. For arithmetic, this 4883 // is always passed by value, and for a compare_exchange it is always 4884 // passed by address. For the rest, GNU uses by-address and C11 uses 4885 // by-value. 4886 assert(Form != Load); 4887 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4888 Ty = ValType; 4889 else if (Form == Copy || Form == Xchg) { 4890 if (IsPassedByAddress) { 4891 // The value pointer is always dereferenced, a nullptr is undefined. 4892 CheckNonNullArgument(*this, APIOrderedArgs[i], 4893 ExprRange.getBegin()); 4894 } 4895 Ty = ByValType; 4896 } else if (Form == Arithmetic) 4897 Ty = Context.getPointerDiffType(); 4898 else { 4899 Expr *ValArg = APIOrderedArgs[i]; 4900 // The value pointer is always dereferenced, a nullptr is undefined. 4901 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4902 LangAS AS = LangAS::Default; 4903 // Keep address space of non-atomic pointer type. 4904 if (const PointerType *PtrTy = 4905 ValArg->getType()->getAs<PointerType>()) { 4906 AS = PtrTy->getPointeeType().getAddressSpace(); 4907 } 4908 Ty = Context.getPointerType( 4909 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4910 } 4911 break; 4912 case 2: 4913 // The third argument to compare_exchange / GNU exchange is the desired 4914 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4915 if (IsPassedByAddress) 4916 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4917 Ty = ByValType; 4918 break; 4919 case 3: 4920 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4921 Ty = Context.BoolTy; 4922 break; 4923 } 4924 } else { 4925 // The order(s) and scope are always converted to int. 4926 Ty = Context.IntTy; 4927 } 4928 4929 InitializedEntity Entity = 4930 InitializedEntity::InitializeParameter(Context, Ty, false); 4931 ExprResult Arg = APIOrderedArgs[i]; 4932 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4933 if (Arg.isInvalid()) 4934 return true; 4935 APIOrderedArgs[i] = Arg.get(); 4936 } 4937 4938 // Permute the arguments into a 'consistent' order. 4939 SmallVector<Expr*, 5> SubExprs; 4940 SubExprs.push_back(Ptr); 4941 switch (Form) { 4942 case Init: 4943 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4944 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4945 break; 4946 case Load: 4947 SubExprs.push_back(APIOrderedArgs[1]); // Order 4948 break; 4949 case LoadCopy: 4950 case Copy: 4951 case Arithmetic: 4952 case Xchg: 4953 SubExprs.push_back(APIOrderedArgs[2]); // Order 4954 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4955 break; 4956 case GNUXchg: 4957 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4958 SubExprs.push_back(APIOrderedArgs[3]); // Order 4959 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4960 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4961 break; 4962 case C11CmpXchg: 4963 SubExprs.push_back(APIOrderedArgs[3]); // Order 4964 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4965 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4966 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4967 break; 4968 case GNUCmpXchg: 4969 SubExprs.push_back(APIOrderedArgs[4]); // Order 4970 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4971 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4972 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4973 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4974 break; 4975 } 4976 4977 if (SubExprs.size() >= 2 && Form != Init) { 4978 llvm::APSInt Result(32); 4979 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4980 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4981 Diag(SubExprs[1]->getBeginLoc(), 4982 diag::warn_atomic_op_has_invalid_memory_order) 4983 << SubExprs[1]->getSourceRange(); 4984 } 4985 4986 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4987 auto *Scope = Args[Args.size() - 1]; 4988 llvm::APSInt Result(32); 4989 if (Scope->isIntegerConstantExpr(Result, Context) && 4990 !ScopeModel->isValid(Result.getZExtValue())) { 4991 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4992 << Scope->getSourceRange(); 4993 } 4994 SubExprs.push_back(Scope); 4995 } 4996 4997 AtomicExpr *AE = new (Context) 4998 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4999 5000 if ((Op == AtomicExpr::AO__c11_atomic_load || 5001 Op == AtomicExpr::AO__c11_atomic_store || 5002 Op == AtomicExpr::AO__opencl_atomic_load || 5003 Op == AtomicExpr::AO__opencl_atomic_store ) && 5004 Context.AtomicUsesUnsupportedLibcall(AE)) 5005 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5006 << ((Op == AtomicExpr::AO__c11_atomic_load || 5007 Op == AtomicExpr::AO__opencl_atomic_load) 5008 ? 0 5009 : 1); 5010 5011 return AE; 5012 } 5013 5014 /// checkBuiltinArgument - Given a call to a builtin function, perform 5015 /// normal type-checking on the given argument, updating the call in 5016 /// place. This is useful when a builtin function requires custom 5017 /// type-checking for some of its arguments but not necessarily all of 5018 /// them. 5019 /// 5020 /// Returns true on error. 5021 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5022 FunctionDecl *Fn = E->getDirectCallee(); 5023 assert(Fn && "builtin call without direct callee!"); 5024 5025 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5026 InitializedEntity Entity = 5027 InitializedEntity::InitializeParameter(S.Context, Param); 5028 5029 ExprResult Arg = E->getArg(0); 5030 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5031 if (Arg.isInvalid()) 5032 return true; 5033 5034 E->setArg(ArgIndex, Arg.get()); 5035 return false; 5036 } 5037 5038 /// We have a call to a function like __sync_fetch_and_add, which is an 5039 /// overloaded function based on the pointer type of its first argument. 5040 /// The main BuildCallExpr routines have already promoted the types of 5041 /// arguments because all of these calls are prototyped as void(...). 5042 /// 5043 /// This function goes through and does final semantic checking for these 5044 /// builtins, as well as generating any warnings. 5045 ExprResult 5046 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5047 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5048 Expr *Callee = TheCall->getCallee(); 5049 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5050 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5051 5052 // Ensure that we have at least one argument to do type inference from. 5053 if (TheCall->getNumArgs() < 1) { 5054 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5055 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5056 return ExprError(); 5057 } 5058 5059 // Inspect the first argument of the atomic builtin. This should always be 5060 // a pointer type, whose element is an integral scalar or pointer type. 5061 // Because it is a pointer type, we don't have to worry about any implicit 5062 // casts here. 5063 // FIXME: We don't allow floating point scalars as input. 5064 Expr *FirstArg = TheCall->getArg(0); 5065 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5066 if (FirstArgResult.isInvalid()) 5067 return ExprError(); 5068 FirstArg = FirstArgResult.get(); 5069 TheCall->setArg(0, FirstArg); 5070 5071 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5072 if (!pointerType) { 5073 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5074 << FirstArg->getType() << FirstArg->getSourceRange(); 5075 return ExprError(); 5076 } 5077 5078 QualType ValType = pointerType->getPointeeType(); 5079 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5080 !ValType->isBlockPointerType()) { 5081 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5082 << FirstArg->getType() << FirstArg->getSourceRange(); 5083 return ExprError(); 5084 } 5085 5086 if (ValType.isConstQualified()) { 5087 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5088 << FirstArg->getType() << FirstArg->getSourceRange(); 5089 return ExprError(); 5090 } 5091 5092 switch (ValType.getObjCLifetime()) { 5093 case Qualifiers::OCL_None: 5094 case Qualifiers::OCL_ExplicitNone: 5095 // okay 5096 break; 5097 5098 case Qualifiers::OCL_Weak: 5099 case Qualifiers::OCL_Strong: 5100 case Qualifiers::OCL_Autoreleasing: 5101 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5102 << ValType << FirstArg->getSourceRange(); 5103 return ExprError(); 5104 } 5105 5106 // Strip any qualifiers off ValType. 5107 ValType = ValType.getUnqualifiedType(); 5108 5109 // The majority of builtins return a value, but a few have special return 5110 // types, so allow them to override appropriately below. 5111 QualType ResultType = ValType; 5112 5113 // We need to figure out which concrete builtin this maps onto. For example, 5114 // __sync_fetch_and_add with a 2 byte object turns into 5115 // __sync_fetch_and_add_2. 5116 #define BUILTIN_ROW(x) \ 5117 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5118 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5119 5120 static const unsigned BuiltinIndices[][5] = { 5121 BUILTIN_ROW(__sync_fetch_and_add), 5122 BUILTIN_ROW(__sync_fetch_and_sub), 5123 BUILTIN_ROW(__sync_fetch_and_or), 5124 BUILTIN_ROW(__sync_fetch_and_and), 5125 BUILTIN_ROW(__sync_fetch_and_xor), 5126 BUILTIN_ROW(__sync_fetch_and_nand), 5127 5128 BUILTIN_ROW(__sync_add_and_fetch), 5129 BUILTIN_ROW(__sync_sub_and_fetch), 5130 BUILTIN_ROW(__sync_and_and_fetch), 5131 BUILTIN_ROW(__sync_or_and_fetch), 5132 BUILTIN_ROW(__sync_xor_and_fetch), 5133 BUILTIN_ROW(__sync_nand_and_fetch), 5134 5135 BUILTIN_ROW(__sync_val_compare_and_swap), 5136 BUILTIN_ROW(__sync_bool_compare_and_swap), 5137 BUILTIN_ROW(__sync_lock_test_and_set), 5138 BUILTIN_ROW(__sync_lock_release), 5139 BUILTIN_ROW(__sync_swap) 5140 }; 5141 #undef BUILTIN_ROW 5142 5143 // Determine the index of the size. 5144 unsigned SizeIndex; 5145 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5146 case 1: SizeIndex = 0; break; 5147 case 2: SizeIndex = 1; break; 5148 case 4: SizeIndex = 2; break; 5149 case 8: SizeIndex = 3; break; 5150 case 16: SizeIndex = 4; break; 5151 default: 5152 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5153 << FirstArg->getType() << FirstArg->getSourceRange(); 5154 return ExprError(); 5155 } 5156 5157 // Each of these builtins has one pointer argument, followed by some number of 5158 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5159 // that we ignore. Find out which row of BuiltinIndices to read from as well 5160 // as the number of fixed args. 5161 unsigned BuiltinID = FDecl->getBuiltinID(); 5162 unsigned BuiltinIndex, NumFixed = 1; 5163 bool WarnAboutSemanticsChange = false; 5164 switch (BuiltinID) { 5165 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5166 case Builtin::BI__sync_fetch_and_add: 5167 case Builtin::BI__sync_fetch_and_add_1: 5168 case Builtin::BI__sync_fetch_and_add_2: 5169 case Builtin::BI__sync_fetch_and_add_4: 5170 case Builtin::BI__sync_fetch_and_add_8: 5171 case Builtin::BI__sync_fetch_and_add_16: 5172 BuiltinIndex = 0; 5173 break; 5174 5175 case Builtin::BI__sync_fetch_and_sub: 5176 case Builtin::BI__sync_fetch_and_sub_1: 5177 case Builtin::BI__sync_fetch_and_sub_2: 5178 case Builtin::BI__sync_fetch_and_sub_4: 5179 case Builtin::BI__sync_fetch_and_sub_8: 5180 case Builtin::BI__sync_fetch_and_sub_16: 5181 BuiltinIndex = 1; 5182 break; 5183 5184 case Builtin::BI__sync_fetch_and_or: 5185 case Builtin::BI__sync_fetch_and_or_1: 5186 case Builtin::BI__sync_fetch_and_or_2: 5187 case Builtin::BI__sync_fetch_and_or_4: 5188 case Builtin::BI__sync_fetch_and_or_8: 5189 case Builtin::BI__sync_fetch_and_or_16: 5190 BuiltinIndex = 2; 5191 break; 5192 5193 case Builtin::BI__sync_fetch_and_and: 5194 case Builtin::BI__sync_fetch_and_and_1: 5195 case Builtin::BI__sync_fetch_and_and_2: 5196 case Builtin::BI__sync_fetch_and_and_4: 5197 case Builtin::BI__sync_fetch_and_and_8: 5198 case Builtin::BI__sync_fetch_and_and_16: 5199 BuiltinIndex = 3; 5200 break; 5201 5202 case Builtin::BI__sync_fetch_and_xor: 5203 case Builtin::BI__sync_fetch_and_xor_1: 5204 case Builtin::BI__sync_fetch_and_xor_2: 5205 case Builtin::BI__sync_fetch_and_xor_4: 5206 case Builtin::BI__sync_fetch_and_xor_8: 5207 case Builtin::BI__sync_fetch_and_xor_16: 5208 BuiltinIndex = 4; 5209 break; 5210 5211 case Builtin::BI__sync_fetch_and_nand: 5212 case Builtin::BI__sync_fetch_and_nand_1: 5213 case Builtin::BI__sync_fetch_and_nand_2: 5214 case Builtin::BI__sync_fetch_and_nand_4: 5215 case Builtin::BI__sync_fetch_and_nand_8: 5216 case Builtin::BI__sync_fetch_and_nand_16: 5217 BuiltinIndex = 5; 5218 WarnAboutSemanticsChange = true; 5219 break; 5220 5221 case Builtin::BI__sync_add_and_fetch: 5222 case Builtin::BI__sync_add_and_fetch_1: 5223 case Builtin::BI__sync_add_and_fetch_2: 5224 case Builtin::BI__sync_add_and_fetch_4: 5225 case Builtin::BI__sync_add_and_fetch_8: 5226 case Builtin::BI__sync_add_and_fetch_16: 5227 BuiltinIndex = 6; 5228 break; 5229 5230 case Builtin::BI__sync_sub_and_fetch: 5231 case Builtin::BI__sync_sub_and_fetch_1: 5232 case Builtin::BI__sync_sub_and_fetch_2: 5233 case Builtin::BI__sync_sub_and_fetch_4: 5234 case Builtin::BI__sync_sub_and_fetch_8: 5235 case Builtin::BI__sync_sub_and_fetch_16: 5236 BuiltinIndex = 7; 5237 break; 5238 5239 case Builtin::BI__sync_and_and_fetch: 5240 case Builtin::BI__sync_and_and_fetch_1: 5241 case Builtin::BI__sync_and_and_fetch_2: 5242 case Builtin::BI__sync_and_and_fetch_4: 5243 case Builtin::BI__sync_and_and_fetch_8: 5244 case Builtin::BI__sync_and_and_fetch_16: 5245 BuiltinIndex = 8; 5246 break; 5247 5248 case Builtin::BI__sync_or_and_fetch: 5249 case Builtin::BI__sync_or_and_fetch_1: 5250 case Builtin::BI__sync_or_and_fetch_2: 5251 case Builtin::BI__sync_or_and_fetch_4: 5252 case Builtin::BI__sync_or_and_fetch_8: 5253 case Builtin::BI__sync_or_and_fetch_16: 5254 BuiltinIndex = 9; 5255 break; 5256 5257 case Builtin::BI__sync_xor_and_fetch: 5258 case Builtin::BI__sync_xor_and_fetch_1: 5259 case Builtin::BI__sync_xor_and_fetch_2: 5260 case Builtin::BI__sync_xor_and_fetch_4: 5261 case Builtin::BI__sync_xor_and_fetch_8: 5262 case Builtin::BI__sync_xor_and_fetch_16: 5263 BuiltinIndex = 10; 5264 break; 5265 5266 case Builtin::BI__sync_nand_and_fetch: 5267 case Builtin::BI__sync_nand_and_fetch_1: 5268 case Builtin::BI__sync_nand_and_fetch_2: 5269 case Builtin::BI__sync_nand_and_fetch_4: 5270 case Builtin::BI__sync_nand_and_fetch_8: 5271 case Builtin::BI__sync_nand_and_fetch_16: 5272 BuiltinIndex = 11; 5273 WarnAboutSemanticsChange = true; 5274 break; 5275 5276 case Builtin::BI__sync_val_compare_and_swap: 5277 case Builtin::BI__sync_val_compare_and_swap_1: 5278 case Builtin::BI__sync_val_compare_and_swap_2: 5279 case Builtin::BI__sync_val_compare_and_swap_4: 5280 case Builtin::BI__sync_val_compare_and_swap_8: 5281 case Builtin::BI__sync_val_compare_and_swap_16: 5282 BuiltinIndex = 12; 5283 NumFixed = 2; 5284 break; 5285 5286 case Builtin::BI__sync_bool_compare_and_swap: 5287 case Builtin::BI__sync_bool_compare_and_swap_1: 5288 case Builtin::BI__sync_bool_compare_and_swap_2: 5289 case Builtin::BI__sync_bool_compare_and_swap_4: 5290 case Builtin::BI__sync_bool_compare_and_swap_8: 5291 case Builtin::BI__sync_bool_compare_and_swap_16: 5292 BuiltinIndex = 13; 5293 NumFixed = 2; 5294 ResultType = Context.BoolTy; 5295 break; 5296 5297 case Builtin::BI__sync_lock_test_and_set: 5298 case Builtin::BI__sync_lock_test_and_set_1: 5299 case Builtin::BI__sync_lock_test_and_set_2: 5300 case Builtin::BI__sync_lock_test_and_set_4: 5301 case Builtin::BI__sync_lock_test_and_set_8: 5302 case Builtin::BI__sync_lock_test_and_set_16: 5303 BuiltinIndex = 14; 5304 break; 5305 5306 case Builtin::BI__sync_lock_release: 5307 case Builtin::BI__sync_lock_release_1: 5308 case Builtin::BI__sync_lock_release_2: 5309 case Builtin::BI__sync_lock_release_4: 5310 case Builtin::BI__sync_lock_release_8: 5311 case Builtin::BI__sync_lock_release_16: 5312 BuiltinIndex = 15; 5313 NumFixed = 0; 5314 ResultType = Context.VoidTy; 5315 break; 5316 5317 case Builtin::BI__sync_swap: 5318 case Builtin::BI__sync_swap_1: 5319 case Builtin::BI__sync_swap_2: 5320 case Builtin::BI__sync_swap_4: 5321 case Builtin::BI__sync_swap_8: 5322 case Builtin::BI__sync_swap_16: 5323 BuiltinIndex = 16; 5324 break; 5325 } 5326 5327 // Now that we know how many fixed arguments we expect, first check that we 5328 // have at least that many. 5329 if (TheCall->getNumArgs() < 1+NumFixed) { 5330 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5331 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5332 << Callee->getSourceRange(); 5333 return ExprError(); 5334 } 5335 5336 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5337 << Callee->getSourceRange(); 5338 5339 if (WarnAboutSemanticsChange) { 5340 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5341 << Callee->getSourceRange(); 5342 } 5343 5344 // Get the decl for the concrete builtin from this, we can tell what the 5345 // concrete integer type we should convert to is. 5346 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5347 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5348 FunctionDecl *NewBuiltinDecl; 5349 if (NewBuiltinID == BuiltinID) 5350 NewBuiltinDecl = FDecl; 5351 else { 5352 // Perform builtin lookup to avoid redeclaring it. 5353 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5354 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5355 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5356 assert(Res.getFoundDecl()); 5357 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5358 if (!NewBuiltinDecl) 5359 return ExprError(); 5360 } 5361 5362 // The first argument --- the pointer --- has a fixed type; we 5363 // deduce the types of the rest of the arguments accordingly. Walk 5364 // the remaining arguments, converting them to the deduced value type. 5365 for (unsigned i = 0; i != NumFixed; ++i) { 5366 ExprResult Arg = TheCall->getArg(i+1); 5367 5368 // GCC does an implicit conversion to the pointer or integer ValType. This 5369 // can fail in some cases (1i -> int**), check for this error case now. 5370 // Initialize the argument. 5371 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5372 ValType, /*consume*/ false); 5373 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5374 if (Arg.isInvalid()) 5375 return ExprError(); 5376 5377 // Okay, we have something that *can* be converted to the right type. Check 5378 // to see if there is a potentially weird extension going on here. This can 5379 // happen when you do an atomic operation on something like an char* and 5380 // pass in 42. The 42 gets converted to char. This is even more strange 5381 // for things like 45.123 -> char, etc. 5382 // FIXME: Do this check. 5383 TheCall->setArg(i+1, Arg.get()); 5384 } 5385 5386 // Create a new DeclRefExpr to refer to the new decl. 5387 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5388 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5389 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5390 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5391 5392 // Set the callee in the CallExpr. 5393 // FIXME: This loses syntactic information. 5394 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5395 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5396 CK_BuiltinFnToFnPtr); 5397 TheCall->setCallee(PromotedCall.get()); 5398 5399 // Change the result type of the call to match the original value type. This 5400 // is arbitrary, but the codegen for these builtins ins design to handle it 5401 // gracefully. 5402 TheCall->setType(ResultType); 5403 5404 return TheCallResult; 5405 } 5406 5407 /// SemaBuiltinNontemporalOverloaded - We have a call to 5408 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5409 /// overloaded function based on the pointer type of its last argument. 5410 /// 5411 /// This function goes through and does final semantic checking for these 5412 /// builtins. 5413 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5414 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5415 DeclRefExpr *DRE = 5416 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5417 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5418 unsigned BuiltinID = FDecl->getBuiltinID(); 5419 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5420 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5421 "Unexpected nontemporal load/store builtin!"); 5422 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5423 unsigned numArgs = isStore ? 2 : 1; 5424 5425 // Ensure that we have the proper number of arguments. 5426 if (checkArgCount(*this, TheCall, numArgs)) 5427 return ExprError(); 5428 5429 // Inspect the last argument of the nontemporal builtin. This should always 5430 // be a pointer type, from which we imply the type of the memory access. 5431 // Because it is a pointer type, we don't have to worry about any implicit 5432 // casts here. 5433 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5434 ExprResult PointerArgResult = 5435 DefaultFunctionArrayLvalueConversion(PointerArg); 5436 5437 if (PointerArgResult.isInvalid()) 5438 return ExprError(); 5439 PointerArg = PointerArgResult.get(); 5440 TheCall->setArg(numArgs - 1, PointerArg); 5441 5442 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5443 if (!pointerType) { 5444 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5445 << PointerArg->getType() << PointerArg->getSourceRange(); 5446 return ExprError(); 5447 } 5448 5449 QualType ValType = pointerType->getPointeeType(); 5450 5451 // Strip any qualifiers off ValType. 5452 ValType = ValType.getUnqualifiedType(); 5453 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5454 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5455 !ValType->isVectorType()) { 5456 Diag(DRE->getBeginLoc(), 5457 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5458 << PointerArg->getType() << PointerArg->getSourceRange(); 5459 return ExprError(); 5460 } 5461 5462 if (!isStore) { 5463 TheCall->setType(ValType); 5464 return TheCallResult; 5465 } 5466 5467 ExprResult ValArg = TheCall->getArg(0); 5468 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5469 Context, ValType, /*consume*/ false); 5470 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5471 if (ValArg.isInvalid()) 5472 return ExprError(); 5473 5474 TheCall->setArg(0, ValArg.get()); 5475 TheCall->setType(Context.VoidTy); 5476 return TheCallResult; 5477 } 5478 5479 /// CheckObjCString - Checks that the argument to the builtin 5480 /// CFString constructor is correct 5481 /// Note: It might also make sense to do the UTF-16 conversion here (would 5482 /// simplify the backend). 5483 bool Sema::CheckObjCString(Expr *Arg) { 5484 Arg = Arg->IgnoreParenCasts(); 5485 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5486 5487 if (!Literal || !Literal->isAscii()) { 5488 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5489 << Arg->getSourceRange(); 5490 return true; 5491 } 5492 5493 if (Literal->containsNonAsciiOrNull()) { 5494 StringRef String = Literal->getString(); 5495 unsigned NumBytes = String.size(); 5496 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5497 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5498 llvm::UTF16 *ToPtr = &ToBuf[0]; 5499 5500 llvm::ConversionResult Result = 5501 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5502 ToPtr + NumBytes, llvm::strictConversion); 5503 // Check for conversion failure. 5504 if (Result != llvm::conversionOK) 5505 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5506 << Arg->getSourceRange(); 5507 } 5508 return false; 5509 } 5510 5511 /// CheckObjCString - Checks that the format string argument to the os_log() 5512 /// and os_trace() functions is correct, and converts it to const char *. 5513 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5514 Arg = Arg->IgnoreParenCasts(); 5515 auto *Literal = dyn_cast<StringLiteral>(Arg); 5516 if (!Literal) { 5517 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5518 Literal = ObjcLiteral->getString(); 5519 } 5520 } 5521 5522 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5523 return ExprError( 5524 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5525 << Arg->getSourceRange()); 5526 } 5527 5528 ExprResult Result(Literal); 5529 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5530 InitializedEntity Entity = 5531 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5532 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5533 return Result; 5534 } 5535 5536 /// Check that the user is calling the appropriate va_start builtin for the 5537 /// target and calling convention. 5538 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5539 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5540 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5541 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5542 TT.getArch() == llvm::Triple::aarch64_32); 5543 bool IsWindows = TT.isOSWindows(); 5544 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5545 if (IsX64 || IsAArch64) { 5546 CallingConv CC = CC_C; 5547 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5548 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5549 if (IsMSVAStart) { 5550 // Don't allow this in System V ABI functions. 5551 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5552 return S.Diag(Fn->getBeginLoc(), 5553 diag::err_ms_va_start_used_in_sysv_function); 5554 } else { 5555 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5556 // On x64 Windows, don't allow this in System V ABI functions. 5557 // (Yes, that means there's no corresponding way to support variadic 5558 // System V ABI functions on Windows.) 5559 if ((IsWindows && CC == CC_X86_64SysV) || 5560 (!IsWindows && CC == CC_Win64)) 5561 return S.Diag(Fn->getBeginLoc(), 5562 diag::err_va_start_used_in_wrong_abi_function) 5563 << !IsWindows; 5564 } 5565 return false; 5566 } 5567 5568 if (IsMSVAStart) 5569 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5570 return false; 5571 } 5572 5573 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5574 ParmVarDecl **LastParam = nullptr) { 5575 // Determine whether the current function, block, or obj-c method is variadic 5576 // and get its parameter list. 5577 bool IsVariadic = false; 5578 ArrayRef<ParmVarDecl *> Params; 5579 DeclContext *Caller = S.CurContext; 5580 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5581 IsVariadic = Block->isVariadic(); 5582 Params = Block->parameters(); 5583 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5584 IsVariadic = FD->isVariadic(); 5585 Params = FD->parameters(); 5586 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5587 IsVariadic = MD->isVariadic(); 5588 // FIXME: This isn't correct for methods (results in bogus warning). 5589 Params = MD->parameters(); 5590 } else if (isa<CapturedDecl>(Caller)) { 5591 // We don't support va_start in a CapturedDecl. 5592 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5593 return true; 5594 } else { 5595 // This must be some other declcontext that parses exprs. 5596 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5597 return true; 5598 } 5599 5600 if (!IsVariadic) { 5601 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5602 return true; 5603 } 5604 5605 if (LastParam) 5606 *LastParam = Params.empty() ? nullptr : Params.back(); 5607 5608 return false; 5609 } 5610 5611 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5612 /// for validity. Emit an error and return true on failure; return false 5613 /// on success. 5614 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5615 Expr *Fn = TheCall->getCallee(); 5616 5617 if (checkVAStartABI(*this, BuiltinID, Fn)) 5618 return true; 5619 5620 if (TheCall->getNumArgs() > 2) { 5621 Diag(TheCall->getArg(2)->getBeginLoc(), 5622 diag::err_typecheck_call_too_many_args) 5623 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5624 << Fn->getSourceRange() 5625 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5626 (*(TheCall->arg_end() - 1))->getEndLoc()); 5627 return true; 5628 } 5629 5630 if (TheCall->getNumArgs() < 2) { 5631 return Diag(TheCall->getEndLoc(), 5632 diag::err_typecheck_call_too_few_args_at_least) 5633 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5634 } 5635 5636 // Type-check the first argument normally. 5637 if (checkBuiltinArgument(*this, TheCall, 0)) 5638 return true; 5639 5640 // Check that the current function is variadic, and get its last parameter. 5641 ParmVarDecl *LastParam; 5642 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5643 return true; 5644 5645 // Verify that the second argument to the builtin is the last argument of the 5646 // current function or method. 5647 bool SecondArgIsLastNamedArgument = false; 5648 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5649 5650 // These are valid if SecondArgIsLastNamedArgument is false after the next 5651 // block. 5652 QualType Type; 5653 SourceLocation ParamLoc; 5654 bool IsCRegister = false; 5655 5656 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5657 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5658 SecondArgIsLastNamedArgument = PV == LastParam; 5659 5660 Type = PV->getType(); 5661 ParamLoc = PV->getLocation(); 5662 IsCRegister = 5663 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5664 } 5665 } 5666 5667 if (!SecondArgIsLastNamedArgument) 5668 Diag(TheCall->getArg(1)->getBeginLoc(), 5669 diag::warn_second_arg_of_va_start_not_last_named_param); 5670 else if (IsCRegister || Type->isReferenceType() || 5671 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5672 // Promotable integers are UB, but enumerations need a bit of 5673 // extra checking to see what their promotable type actually is. 5674 if (!Type->isPromotableIntegerType()) 5675 return false; 5676 if (!Type->isEnumeralType()) 5677 return true; 5678 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5679 return !(ED && 5680 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5681 }()) { 5682 unsigned Reason = 0; 5683 if (Type->isReferenceType()) Reason = 1; 5684 else if (IsCRegister) Reason = 2; 5685 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5686 Diag(ParamLoc, diag::note_parameter_type) << Type; 5687 } 5688 5689 TheCall->setType(Context.VoidTy); 5690 return false; 5691 } 5692 5693 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5694 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5695 // const char *named_addr); 5696 5697 Expr *Func = Call->getCallee(); 5698 5699 if (Call->getNumArgs() < 3) 5700 return Diag(Call->getEndLoc(), 5701 diag::err_typecheck_call_too_few_args_at_least) 5702 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5703 5704 // Type-check the first argument normally. 5705 if (checkBuiltinArgument(*this, Call, 0)) 5706 return true; 5707 5708 // Check that the current function is variadic. 5709 if (checkVAStartIsInVariadicFunction(*this, Func)) 5710 return true; 5711 5712 // __va_start on Windows does not validate the parameter qualifiers 5713 5714 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5715 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5716 5717 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5718 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5719 5720 const QualType &ConstCharPtrTy = 5721 Context.getPointerType(Context.CharTy.withConst()); 5722 if (!Arg1Ty->isPointerType() || 5723 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5724 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5725 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5726 << 0 /* qualifier difference */ 5727 << 3 /* parameter mismatch */ 5728 << 2 << Arg1->getType() << ConstCharPtrTy; 5729 5730 const QualType SizeTy = Context.getSizeType(); 5731 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5732 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5733 << Arg2->getType() << SizeTy << 1 /* different class */ 5734 << 0 /* qualifier difference */ 5735 << 3 /* parameter mismatch */ 5736 << 3 << Arg2->getType() << SizeTy; 5737 5738 return false; 5739 } 5740 5741 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5742 /// friends. This is declared to take (...), so we have to check everything. 5743 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5744 if (TheCall->getNumArgs() < 2) 5745 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5746 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5747 if (TheCall->getNumArgs() > 2) 5748 return Diag(TheCall->getArg(2)->getBeginLoc(), 5749 diag::err_typecheck_call_too_many_args) 5750 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5751 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5752 (*(TheCall->arg_end() - 1))->getEndLoc()); 5753 5754 ExprResult OrigArg0 = TheCall->getArg(0); 5755 ExprResult OrigArg1 = TheCall->getArg(1); 5756 5757 // Do standard promotions between the two arguments, returning their common 5758 // type. 5759 QualType Res = UsualArithmeticConversions( 5760 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5761 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5762 return true; 5763 5764 // Make sure any conversions are pushed back into the call; this is 5765 // type safe since unordered compare builtins are declared as "_Bool 5766 // foo(...)". 5767 TheCall->setArg(0, OrigArg0.get()); 5768 TheCall->setArg(1, OrigArg1.get()); 5769 5770 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5771 return false; 5772 5773 // If the common type isn't a real floating type, then the arguments were 5774 // invalid for this operation. 5775 if (Res.isNull() || !Res->isRealFloatingType()) 5776 return Diag(OrigArg0.get()->getBeginLoc(), 5777 diag::err_typecheck_call_invalid_ordered_compare) 5778 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5779 << SourceRange(OrigArg0.get()->getBeginLoc(), 5780 OrigArg1.get()->getEndLoc()); 5781 5782 return false; 5783 } 5784 5785 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5786 /// __builtin_isnan and friends. This is declared to take (...), so we have 5787 /// to check everything. We expect the last argument to be a floating point 5788 /// value. 5789 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5790 if (TheCall->getNumArgs() < NumArgs) 5791 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5792 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5793 if (TheCall->getNumArgs() > NumArgs) 5794 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5795 diag::err_typecheck_call_too_many_args) 5796 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5797 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5798 (*(TheCall->arg_end() - 1))->getEndLoc()); 5799 5800 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5801 // on all preceding parameters just being int. Try all of those. 5802 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5803 Expr *Arg = TheCall->getArg(i); 5804 5805 if (Arg->isTypeDependent()) 5806 return false; 5807 5808 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5809 5810 if (Res.isInvalid()) 5811 return true; 5812 TheCall->setArg(i, Res.get()); 5813 } 5814 5815 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5816 5817 if (OrigArg->isTypeDependent()) 5818 return false; 5819 5820 // Usual Unary Conversions will convert half to float, which we want for 5821 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5822 // type how it is, but do normal L->Rvalue conversions. 5823 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5824 OrigArg = UsualUnaryConversions(OrigArg).get(); 5825 else 5826 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5827 TheCall->setArg(NumArgs - 1, OrigArg); 5828 5829 // This operation requires a non-_Complex floating-point number. 5830 if (!OrigArg->getType()->isRealFloatingType()) 5831 return Diag(OrigArg->getBeginLoc(), 5832 diag::err_typecheck_call_invalid_unary_fp) 5833 << OrigArg->getType() << OrigArg->getSourceRange(); 5834 5835 return false; 5836 } 5837 5838 // Customized Sema Checking for VSX builtins that have the following signature: 5839 // vector [...] builtinName(vector [...], vector [...], const int); 5840 // Which takes the same type of vectors (any legal vector type) for the first 5841 // two arguments and takes compile time constant for the third argument. 5842 // Example builtins are : 5843 // vector double vec_xxpermdi(vector double, vector double, int); 5844 // vector short vec_xxsldwi(vector short, vector short, int); 5845 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5846 unsigned ExpectedNumArgs = 3; 5847 if (TheCall->getNumArgs() < ExpectedNumArgs) 5848 return Diag(TheCall->getEndLoc(), 5849 diag::err_typecheck_call_too_few_args_at_least) 5850 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5851 << TheCall->getSourceRange(); 5852 5853 if (TheCall->getNumArgs() > ExpectedNumArgs) 5854 return Diag(TheCall->getEndLoc(), 5855 diag::err_typecheck_call_too_many_args_at_most) 5856 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5857 << TheCall->getSourceRange(); 5858 5859 // Check the third argument is a compile time constant 5860 llvm::APSInt Value; 5861 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5862 return Diag(TheCall->getBeginLoc(), 5863 diag::err_vsx_builtin_nonconstant_argument) 5864 << 3 /* argument index */ << TheCall->getDirectCallee() 5865 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5866 TheCall->getArg(2)->getEndLoc()); 5867 5868 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5869 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5870 5871 // Check the type of argument 1 and argument 2 are vectors. 5872 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5873 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5874 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5875 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5876 << TheCall->getDirectCallee() 5877 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5878 TheCall->getArg(1)->getEndLoc()); 5879 } 5880 5881 // Check the first two arguments are the same type. 5882 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5883 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5884 << TheCall->getDirectCallee() 5885 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5886 TheCall->getArg(1)->getEndLoc()); 5887 } 5888 5889 // When default clang type checking is turned off and the customized type 5890 // checking is used, the returning type of the function must be explicitly 5891 // set. Otherwise it is _Bool by default. 5892 TheCall->setType(Arg1Ty); 5893 5894 return false; 5895 } 5896 5897 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5898 // This is declared to take (...), so we have to check everything. 5899 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5900 if (TheCall->getNumArgs() < 2) 5901 return ExprError(Diag(TheCall->getEndLoc(), 5902 diag::err_typecheck_call_too_few_args_at_least) 5903 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5904 << TheCall->getSourceRange()); 5905 5906 // Determine which of the following types of shufflevector we're checking: 5907 // 1) unary, vector mask: (lhs, mask) 5908 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5909 QualType resType = TheCall->getArg(0)->getType(); 5910 unsigned numElements = 0; 5911 5912 if (!TheCall->getArg(0)->isTypeDependent() && 5913 !TheCall->getArg(1)->isTypeDependent()) { 5914 QualType LHSType = TheCall->getArg(0)->getType(); 5915 QualType RHSType = TheCall->getArg(1)->getType(); 5916 5917 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5918 return ExprError( 5919 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5920 << TheCall->getDirectCallee() 5921 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5922 TheCall->getArg(1)->getEndLoc())); 5923 5924 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5925 unsigned numResElements = TheCall->getNumArgs() - 2; 5926 5927 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5928 // with mask. If so, verify that RHS is an integer vector type with the 5929 // same number of elts as lhs. 5930 if (TheCall->getNumArgs() == 2) { 5931 if (!RHSType->hasIntegerRepresentation() || 5932 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5933 return ExprError(Diag(TheCall->getBeginLoc(), 5934 diag::err_vec_builtin_incompatible_vector) 5935 << TheCall->getDirectCallee() 5936 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5937 TheCall->getArg(1)->getEndLoc())); 5938 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5939 return ExprError(Diag(TheCall->getBeginLoc(), 5940 diag::err_vec_builtin_incompatible_vector) 5941 << TheCall->getDirectCallee() 5942 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5943 TheCall->getArg(1)->getEndLoc())); 5944 } else if (numElements != numResElements) { 5945 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5946 resType = Context.getVectorType(eltType, numResElements, 5947 VectorType::GenericVector); 5948 } 5949 } 5950 5951 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5952 if (TheCall->getArg(i)->isTypeDependent() || 5953 TheCall->getArg(i)->isValueDependent()) 5954 continue; 5955 5956 llvm::APSInt Result(32); 5957 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5958 return ExprError(Diag(TheCall->getBeginLoc(), 5959 diag::err_shufflevector_nonconstant_argument) 5960 << TheCall->getArg(i)->getSourceRange()); 5961 5962 // Allow -1 which will be translated to undef in the IR. 5963 if (Result.isSigned() && Result.isAllOnesValue()) 5964 continue; 5965 5966 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5967 return ExprError(Diag(TheCall->getBeginLoc(), 5968 diag::err_shufflevector_argument_too_large) 5969 << TheCall->getArg(i)->getSourceRange()); 5970 } 5971 5972 SmallVector<Expr*, 32> exprs; 5973 5974 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5975 exprs.push_back(TheCall->getArg(i)); 5976 TheCall->setArg(i, nullptr); 5977 } 5978 5979 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5980 TheCall->getCallee()->getBeginLoc(), 5981 TheCall->getRParenLoc()); 5982 } 5983 5984 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5985 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5986 SourceLocation BuiltinLoc, 5987 SourceLocation RParenLoc) { 5988 ExprValueKind VK = VK_RValue; 5989 ExprObjectKind OK = OK_Ordinary; 5990 QualType DstTy = TInfo->getType(); 5991 QualType SrcTy = E->getType(); 5992 5993 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5994 return ExprError(Diag(BuiltinLoc, 5995 diag::err_convertvector_non_vector) 5996 << E->getSourceRange()); 5997 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5998 return ExprError(Diag(BuiltinLoc, 5999 diag::err_convertvector_non_vector_type)); 6000 6001 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6002 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6003 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6004 if (SrcElts != DstElts) 6005 return ExprError(Diag(BuiltinLoc, 6006 diag::err_convertvector_incompatible_vector) 6007 << E->getSourceRange()); 6008 } 6009 6010 return new (Context) 6011 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6012 } 6013 6014 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6015 // This is declared to take (const void*, ...) and can take two 6016 // optional constant int args. 6017 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6018 unsigned NumArgs = TheCall->getNumArgs(); 6019 6020 if (NumArgs > 3) 6021 return Diag(TheCall->getEndLoc(), 6022 diag::err_typecheck_call_too_many_args_at_most) 6023 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6024 6025 // Argument 0 is checked for us and the remaining arguments must be 6026 // constant integers. 6027 for (unsigned i = 1; i != NumArgs; ++i) 6028 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6029 return true; 6030 6031 return false; 6032 } 6033 6034 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6035 // __assume does not evaluate its arguments, and should warn if its argument 6036 // has side effects. 6037 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6038 Expr *Arg = TheCall->getArg(0); 6039 if (Arg->isInstantiationDependent()) return false; 6040 6041 if (Arg->HasSideEffects(Context)) 6042 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6043 << Arg->getSourceRange() 6044 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6045 6046 return false; 6047 } 6048 6049 /// Handle __builtin_alloca_with_align. This is declared 6050 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6051 /// than 8. 6052 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6053 // The alignment must be a constant integer. 6054 Expr *Arg = TheCall->getArg(1); 6055 6056 // We can't check the value of a dependent argument. 6057 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6058 if (const auto *UE = 6059 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6060 if (UE->getKind() == UETT_AlignOf || 6061 UE->getKind() == UETT_PreferredAlignOf) 6062 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6063 << Arg->getSourceRange(); 6064 6065 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6066 6067 if (!Result.isPowerOf2()) 6068 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6069 << Arg->getSourceRange(); 6070 6071 if (Result < Context.getCharWidth()) 6072 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6073 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6074 6075 if (Result > std::numeric_limits<int32_t>::max()) 6076 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6077 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6078 } 6079 6080 return false; 6081 } 6082 6083 /// Handle __builtin_assume_aligned. This is declared 6084 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6085 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6086 unsigned NumArgs = TheCall->getNumArgs(); 6087 6088 if (NumArgs > 3) 6089 return Diag(TheCall->getEndLoc(), 6090 diag::err_typecheck_call_too_many_args_at_most) 6091 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6092 6093 // The alignment must be a constant integer. 6094 Expr *Arg = TheCall->getArg(1); 6095 6096 // We can't check the value of a dependent argument. 6097 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6098 llvm::APSInt Result; 6099 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6100 return true; 6101 6102 if (!Result.isPowerOf2()) 6103 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6104 << Arg->getSourceRange(); 6105 6106 // Alignment calculations can wrap around if it's greater than 2**29. 6107 unsigned MaximumAlignment = 536870912; 6108 if (Result > MaximumAlignment) 6109 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6110 << Arg->getSourceRange() << MaximumAlignment; 6111 } 6112 6113 if (NumArgs > 2) { 6114 ExprResult Arg(TheCall->getArg(2)); 6115 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6116 Context.getSizeType(), false); 6117 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6118 if (Arg.isInvalid()) return true; 6119 TheCall->setArg(2, Arg.get()); 6120 } 6121 6122 return false; 6123 } 6124 6125 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6126 unsigned BuiltinID = 6127 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6128 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6129 6130 unsigned NumArgs = TheCall->getNumArgs(); 6131 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6132 if (NumArgs < NumRequiredArgs) { 6133 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6134 << 0 /* function call */ << NumRequiredArgs << NumArgs 6135 << TheCall->getSourceRange(); 6136 } 6137 if (NumArgs >= NumRequiredArgs + 0x100) { 6138 return Diag(TheCall->getEndLoc(), 6139 diag::err_typecheck_call_too_many_args_at_most) 6140 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6141 << TheCall->getSourceRange(); 6142 } 6143 unsigned i = 0; 6144 6145 // For formatting call, check buffer arg. 6146 if (!IsSizeCall) { 6147 ExprResult Arg(TheCall->getArg(i)); 6148 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6149 Context, Context.VoidPtrTy, false); 6150 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6151 if (Arg.isInvalid()) 6152 return true; 6153 TheCall->setArg(i, Arg.get()); 6154 i++; 6155 } 6156 6157 // Check string literal arg. 6158 unsigned FormatIdx = i; 6159 { 6160 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6161 if (Arg.isInvalid()) 6162 return true; 6163 TheCall->setArg(i, Arg.get()); 6164 i++; 6165 } 6166 6167 // Make sure variadic args are scalar. 6168 unsigned FirstDataArg = i; 6169 while (i < NumArgs) { 6170 ExprResult Arg = DefaultVariadicArgumentPromotion( 6171 TheCall->getArg(i), VariadicFunction, nullptr); 6172 if (Arg.isInvalid()) 6173 return true; 6174 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6175 if (ArgSize.getQuantity() >= 0x100) { 6176 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6177 << i << (int)ArgSize.getQuantity() << 0xff 6178 << TheCall->getSourceRange(); 6179 } 6180 TheCall->setArg(i, Arg.get()); 6181 i++; 6182 } 6183 6184 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6185 // call to avoid duplicate diagnostics. 6186 if (!IsSizeCall) { 6187 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6188 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6189 bool Success = CheckFormatArguments( 6190 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6191 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6192 CheckedVarArgs); 6193 if (!Success) 6194 return true; 6195 } 6196 6197 if (IsSizeCall) { 6198 TheCall->setType(Context.getSizeType()); 6199 } else { 6200 TheCall->setType(Context.VoidPtrTy); 6201 } 6202 return false; 6203 } 6204 6205 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6206 /// TheCall is a constant expression. 6207 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6208 llvm::APSInt &Result) { 6209 Expr *Arg = TheCall->getArg(ArgNum); 6210 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6211 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6212 6213 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6214 6215 if (!Arg->isIntegerConstantExpr(Result, Context)) 6216 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6217 << FDecl->getDeclName() << Arg->getSourceRange(); 6218 6219 return false; 6220 } 6221 6222 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6223 /// TheCall is a constant expression in the range [Low, High]. 6224 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6225 int Low, int High, bool RangeIsError) { 6226 if (isConstantEvaluated()) 6227 return false; 6228 llvm::APSInt Result; 6229 6230 // We can't check the value of a dependent argument. 6231 Expr *Arg = TheCall->getArg(ArgNum); 6232 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6233 return false; 6234 6235 // Check constant-ness first. 6236 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6237 return true; 6238 6239 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6240 if (RangeIsError) 6241 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6242 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6243 else 6244 // Defer the warning until we know if the code will be emitted so that 6245 // dead code can ignore this. 6246 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6247 PDiag(diag::warn_argument_invalid_range) 6248 << Result.toString(10) << Low << High 6249 << Arg->getSourceRange()); 6250 } 6251 6252 return false; 6253 } 6254 6255 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6256 /// TheCall is a constant expression is a multiple of Num.. 6257 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6258 unsigned Num) { 6259 llvm::APSInt Result; 6260 6261 // We can't check the value of a dependent argument. 6262 Expr *Arg = TheCall->getArg(ArgNum); 6263 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6264 return false; 6265 6266 // Check constant-ness first. 6267 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6268 return true; 6269 6270 if (Result.getSExtValue() % Num != 0) 6271 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6272 << Num << Arg->getSourceRange(); 6273 6274 return false; 6275 } 6276 6277 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6278 /// constant expression representing a power of 2. 6279 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6280 llvm::APSInt Result; 6281 6282 // We can't check the value of a dependent argument. 6283 Expr *Arg = TheCall->getArg(ArgNum); 6284 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6285 return false; 6286 6287 // Check constant-ness first. 6288 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6289 return true; 6290 6291 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6292 // and only if x is a power of 2. 6293 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6294 return false; 6295 6296 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6297 << Arg->getSourceRange(); 6298 } 6299 6300 static bool IsShiftedByte(llvm::APSInt Value) { 6301 if (Value.isNegative()) 6302 return false; 6303 6304 // Check if it's a shifted byte, by shifting it down 6305 while (true) { 6306 // If the value fits in the bottom byte, the check passes. 6307 if (Value < 0x100) 6308 return true; 6309 6310 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6311 // fails. 6312 if ((Value & 0xFF) != 0) 6313 return false; 6314 6315 // If the bottom 8 bits are all 0, but something above that is nonzero, 6316 // then shifting the value right by 8 bits won't affect whether it's a 6317 // shifted byte or not. So do that, and go round again. 6318 Value >>= 8; 6319 } 6320 } 6321 6322 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6323 /// a constant expression representing an arbitrary byte value shifted left by 6324 /// a multiple of 8 bits. 6325 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) { 6326 llvm::APSInt Result; 6327 6328 // We can't check the value of a dependent argument. 6329 Expr *Arg = TheCall->getArg(ArgNum); 6330 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6331 return false; 6332 6333 // Check constant-ness first. 6334 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6335 return true; 6336 6337 if (IsShiftedByte(Result)) 6338 return false; 6339 6340 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6341 << Arg->getSourceRange(); 6342 } 6343 6344 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6345 /// TheCall is a constant expression representing either a shifted byte value, 6346 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6347 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6348 /// Arm MVE intrinsics. 6349 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6350 int ArgNum) { 6351 llvm::APSInt Result; 6352 6353 // We can't check the value of a dependent argument. 6354 Expr *Arg = TheCall->getArg(ArgNum); 6355 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6356 return false; 6357 6358 // Check constant-ness first. 6359 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6360 return true; 6361 6362 // Check to see if it's in either of the required forms. 6363 if (IsShiftedByte(Result) || 6364 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6365 return false; 6366 6367 return Diag(TheCall->getBeginLoc(), 6368 diag::err_argument_not_shifted_byte_or_xxff) 6369 << Arg->getSourceRange(); 6370 } 6371 6372 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6373 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6374 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6375 if (checkArgCount(*this, TheCall, 2)) 6376 return true; 6377 Expr *Arg0 = TheCall->getArg(0); 6378 Expr *Arg1 = TheCall->getArg(1); 6379 6380 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6381 if (FirstArg.isInvalid()) 6382 return true; 6383 QualType FirstArgType = FirstArg.get()->getType(); 6384 if (!FirstArgType->isAnyPointerType()) 6385 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6386 << "first" << FirstArgType << Arg0->getSourceRange(); 6387 TheCall->setArg(0, FirstArg.get()); 6388 6389 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6390 if (SecArg.isInvalid()) 6391 return true; 6392 QualType SecArgType = SecArg.get()->getType(); 6393 if (!SecArgType->isIntegerType()) 6394 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6395 << "second" << SecArgType << Arg1->getSourceRange(); 6396 6397 // Derive the return type from the pointer argument. 6398 TheCall->setType(FirstArgType); 6399 return false; 6400 } 6401 6402 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6403 if (checkArgCount(*this, TheCall, 2)) 6404 return true; 6405 6406 Expr *Arg0 = TheCall->getArg(0); 6407 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6408 if (FirstArg.isInvalid()) 6409 return true; 6410 QualType FirstArgType = FirstArg.get()->getType(); 6411 if (!FirstArgType->isAnyPointerType()) 6412 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6413 << "first" << FirstArgType << Arg0->getSourceRange(); 6414 TheCall->setArg(0, FirstArg.get()); 6415 6416 // Derive the return type from the pointer argument. 6417 TheCall->setType(FirstArgType); 6418 6419 // Second arg must be an constant in range [0,15] 6420 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6421 } 6422 6423 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6424 if (checkArgCount(*this, TheCall, 2)) 6425 return true; 6426 Expr *Arg0 = TheCall->getArg(0); 6427 Expr *Arg1 = TheCall->getArg(1); 6428 6429 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6430 if (FirstArg.isInvalid()) 6431 return true; 6432 QualType FirstArgType = FirstArg.get()->getType(); 6433 if (!FirstArgType->isAnyPointerType()) 6434 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6435 << "first" << FirstArgType << Arg0->getSourceRange(); 6436 6437 QualType SecArgType = Arg1->getType(); 6438 if (!SecArgType->isIntegerType()) 6439 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6440 << "second" << SecArgType << Arg1->getSourceRange(); 6441 TheCall->setType(Context.IntTy); 6442 return false; 6443 } 6444 6445 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6446 BuiltinID == AArch64::BI__builtin_arm_stg) { 6447 if (checkArgCount(*this, TheCall, 1)) 6448 return true; 6449 Expr *Arg0 = TheCall->getArg(0); 6450 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6451 if (FirstArg.isInvalid()) 6452 return true; 6453 6454 QualType FirstArgType = FirstArg.get()->getType(); 6455 if (!FirstArgType->isAnyPointerType()) 6456 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6457 << "first" << FirstArgType << Arg0->getSourceRange(); 6458 TheCall->setArg(0, FirstArg.get()); 6459 6460 // Derive the return type from the pointer argument. 6461 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6462 TheCall->setType(FirstArgType); 6463 return false; 6464 } 6465 6466 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6467 Expr *ArgA = TheCall->getArg(0); 6468 Expr *ArgB = TheCall->getArg(1); 6469 6470 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6471 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6472 6473 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6474 return true; 6475 6476 QualType ArgTypeA = ArgExprA.get()->getType(); 6477 QualType ArgTypeB = ArgExprB.get()->getType(); 6478 6479 auto isNull = [&] (Expr *E) -> bool { 6480 return E->isNullPointerConstant( 6481 Context, Expr::NPC_ValueDependentIsNotNull); }; 6482 6483 // argument should be either a pointer or null 6484 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6485 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6486 << "first" << ArgTypeA << ArgA->getSourceRange(); 6487 6488 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6489 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6490 << "second" << ArgTypeB << ArgB->getSourceRange(); 6491 6492 // Ensure Pointee types are compatible 6493 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6494 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6495 QualType pointeeA = ArgTypeA->getPointeeType(); 6496 QualType pointeeB = ArgTypeB->getPointeeType(); 6497 if (!Context.typesAreCompatible( 6498 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6499 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6500 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6501 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6502 << ArgB->getSourceRange(); 6503 } 6504 } 6505 6506 // at least one argument should be pointer type 6507 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6508 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6509 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6510 6511 if (isNull(ArgA)) // adopt type of the other pointer 6512 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6513 6514 if (isNull(ArgB)) 6515 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6516 6517 TheCall->setArg(0, ArgExprA.get()); 6518 TheCall->setArg(1, ArgExprB.get()); 6519 TheCall->setType(Context.LongLongTy); 6520 return false; 6521 } 6522 assert(false && "Unhandled ARM MTE intrinsic"); 6523 return true; 6524 } 6525 6526 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6527 /// TheCall is an ARM/AArch64 special register string literal. 6528 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6529 int ArgNum, unsigned ExpectedFieldNum, 6530 bool AllowName) { 6531 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6532 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6533 BuiltinID == ARM::BI__builtin_arm_rsr || 6534 BuiltinID == ARM::BI__builtin_arm_rsrp || 6535 BuiltinID == ARM::BI__builtin_arm_wsr || 6536 BuiltinID == ARM::BI__builtin_arm_wsrp; 6537 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6538 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6539 BuiltinID == AArch64::BI__builtin_arm_rsr || 6540 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6541 BuiltinID == AArch64::BI__builtin_arm_wsr || 6542 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6543 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6544 6545 // We can't check the value of a dependent argument. 6546 Expr *Arg = TheCall->getArg(ArgNum); 6547 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6548 return false; 6549 6550 // Check if the argument is a string literal. 6551 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6552 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6553 << Arg->getSourceRange(); 6554 6555 // Check the type of special register given. 6556 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6557 SmallVector<StringRef, 6> Fields; 6558 Reg.split(Fields, ":"); 6559 6560 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6561 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6562 << Arg->getSourceRange(); 6563 6564 // If the string is the name of a register then we cannot check that it is 6565 // valid here but if the string is of one the forms described in ACLE then we 6566 // can check that the supplied fields are integers and within the valid 6567 // ranges. 6568 if (Fields.size() > 1) { 6569 bool FiveFields = Fields.size() == 5; 6570 6571 bool ValidString = true; 6572 if (IsARMBuiltin) { 6573 ValidString &= Fields[0].startswith_lower("cp") || 6574 Fields[0].startswith_lower("p"); 6575 if (ValidString) 6576 Fields[0] = 6577 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6578 6579 ValidString &= Fields[2].startswith_lower("c"); 6580 if (ValidString) 6581 Fields[2] = Fields[2].drop_front(1); 6582 6583 if (FiveFields) { 6584 ValidString &= Fields[3].startswith_lower("c"); 6585 if (ValidString) 6586 Fields[3] = Fields[3].drop_front(1); 6587 } 6588 } 6589 6590 SmallVector<int, 5> Ranges; 6591 if (FiveFields) 6592 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6593 else 6594 Ranges.append({15, 7, 15}); 6595 6596 for (unsigned i=0; i<Fields.size(); ++i) { 6597 int IntField; 6598 ValidString &= !Fields[i].getAsInteger(10, IntField); 6599 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6600 } 6601 6602 if (!ValidString) 6603 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6604 << Arg->getSourceRange(); 6605 } else if (IsAArch64Builtin && Fields.size() == 1) { 6606 // If the register name is one of those that appear in the condition below 6607 // and the special register builtin being used is one of the write builtins, 6608 // then we require that the argument provided for writing to the register 6609 // is an integer constant expression. This is because it will be lowered to 6610 // an MSR (immediate) instruction, so we need to know the immediate at 6611 // compile time. 6612 if (TheCall->getNumArgs() != 2) 6613 return false; 6614 6615 std::string RegLower = Reg.lower(); 6616 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6617 RegLower != "pan" && RegLower != "uao") 6618 return false; 6619 6620 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6621 } 6622 6623 return false; 6624 } 6625 6626 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6627 /// This checks that the target supports __builtin_longjmp and 6628 /// that val is a constant 1. 6629 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6630 if (!Context.getTargetInfo().hasSjLjLowering()) 6631 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6632 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6633 6634 Expr *Arg = TheCall->getArg(1); 6635 llvm::APSInt Result; 6636 6637 // TODO: This is less than ideal. Overload this to take a value. 6638 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6639 return true; 6640 6641 if (Result != 1) 6642 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6643 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6644 6645 return false; 6646 } 6647 6648 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6649 /// This checks that the target supports __builtin_setjmp. 6650 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6651 if (!Context.getTargetInfo().hasSjLjLowering()) 6652 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6653 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6654 return false; 6655 } 6656 6657 namespace { 6658 6659 class UncoveredArgHandler { 6660 enum { Unknown = -1, AllCovered = -2 }; 6661 6662 signed FirstUncoveredArg = Unknown; 6663 SmallVector<const Expr *, 4> DiagnosticExprs; 6664 6665 public: 6666 UncoveredArgHandler() = default; 6667 6668 bool hasUncoveredArg() const { 6669 return (FirstUncoveredArg >= 0); 6670 } 6671 6672 unsigned getUncoveredArg() const { 6673 assert(hasUncoveredArg() && "no uncovered argument"); 6674 return FirstUncoveredArg; 6675 } 6676 6677 void setAllCovered() { 6678 // A string has been found with all arguments covered, so clear out 6679 // the diagnostics. 6680 DiagnosticExprs.clear(); 6681 FirstUncoveredArg = AllCovered; 6682 } 6683 6684 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6685 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6686 6687 // Don't update if a previous string covers all arguments. 6688 if (FirstUncoveredArg == AllCovered) 6689 return; 6690 6691 // UncoveredArgHandler tracks the highest uncovered argument index 6692 // and with it all the strings that match this index. 6693 if (NewFirstUncoveredArg == FirstUncoveredArg) 6694 DiagnosticExprs.push_back(StrExpr); 6695 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6696 DiagnosticExprs.clear(); 6697 DiagnosticExprs.push_back(StrExpr); 6698 FirstUncoveredArg = NewFirstUncoveredArg; 6699 } 6700 } 6701 6702 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6703 }; 6704 6705 enum StringLiteralCheckType { 6706 SLCT_NotALiteral, 6707 SLCT_UncheckedLiteral, 6708 SLCT_CheckedLiteral 6709 }; 6710 6711 } // namespace 6712 6713 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6714 BinaryOperatorKind BinOpKind, 6715 bool AddendIsRight) { 6716 unsigned BitWidth = Offset.getBitWidth(); 6717 unsigned AddendBitWidth = Addend.getBitWidth(); 6718 // There might be negative interim results. 6719 if (Addend.isUnsigned()) { 6720 Addend = Addend.zext(++AddendBitWidth); 6721 Addend.setIsSigned(true); 6722 } 6723 // Adjust the bit width of the APSInts. 6724 if (AddendBitWidth > BitWidth) { 6725 Offset = Offset.sext(AddendBitWidth); 6726 BitWidth = AddendBitWidth; 6727 } else if (BitWidth > AddendBitWidth) { 6728 Addend = Addend.sext(BitWidth); 6729 } 6730 6731 bool Ov = false; 6732 llvm::APSInt ResOffset = Offset; 6733 if (BinOpKind == BO_Add) 6734 ResOffset = Offset.sadd_ov(Addend, Ov); 6735 else { 6736 assert(AddendIsRight && BinOpKind == BO_Sub && 6737 "operator must be add or sub with addend on the right"); 6738 ResOffset = Offset.ssub_ov(Addend, Ov); 6739 } 6740 6741 // We add an offset to a pointer here so we should support an offset as big as 6742 // possible. 6743 if (Ov) { 6744 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6745 "index (intermediate) result too big"); 6746 Offset = Offset.sext(2 * BitWidth); 6747 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6748 return; 6749 } 6750 6751 Offset = ResOffset; 6752 } 6753 6754 namespace { 6755 6756 // This is a wrapper class around StringLiteral to support offsetted string 6757 // literals as format strings. It takes the offset into account when returning 6758 // the string and its length or the source locations to display notes correctly. 6759 class FormatStringLiteral { 6760 const StringLiteral *FExpr; 6761 int64_t Offset; 6762 6763 public: 6764 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6765 : FExpr(fexpr), Offset(Offset) {} 6766 6767 StringRef getString() const { 6768 return FExpr->getString().drop_front(Offset); 6769 } 6770 6771 unsigned getByteLength() const { 6772 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6773 } 6774 6775 unsigned getLength() const { return FExpr->getLength() - Offset; } 6776 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6777 6778 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6779 6780 QualType getType() const { return FExpr->getType(); } 6781 6782 bool isAscii() const { return FExpr->isAscii(); } 6783 bool isWide() const { return FExpr->isWide(); } 6784 bool isUTF8() const { return FExpr->isUTF8(); } 6785 bool isUTF16() const { return FExpr->isUTF16(); } 6786 bool isUTF32() const { return FExpr->isUTF32(); } 6787 bool isPascal() const { return FExpr->isPascal(); } 6788 6789 SourceLocation getLocationOfByte( 6790 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6791 const TargetInfo &Target, unsigned *StartToken = nullptr, 6792 unsigned *StartTokenByteOffset = nullptr) const { 6793 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6794 StartToken, StartTokenByteOffset); 6795 } 6796 6797 SourceLocation getBeginLoc() const LLVM_READONLY { 6798 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6799 } 6800 6801 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6802 }; 6803 6804 } // namespace 6805 6806 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6807 const Expr *OrigFormatExpr, 6808 ArrayRef<const Expr *> Args, 6809 bool HasVAListArg, unsigned format_idx, 6810 unsigned firstDataArg, 6811 Sema::FormatStringType Type, 6812 bool inFunctionCall, 6813 Sema::VariadicCallType CallType, 6814 llvm::SmallBitVector &CheckedVarArgs, 6815 UncoveredArgHandler &UncoveredArg, 6816 bool IgnoreStringsWithoutSpecifiers); 6817 6818 // Determine if an expression is a string literal or constant string. 6819 // If this function returns false on the arguments to a function expecting a 6820 // format string, we will usually need to emit a warning. 6821 // True string literals are then checked by CheckFormatString. 6822 static StringLiteralCheckType 6823 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6824 bool HasVAListArg, unsigned format_idx, 6825 unsigned firstDataArg, Sema::FormatStringType Type, 6826 Sema::VariadicCallType CallType, bool InFunctionCall, 6827 llvm::SmallBitVector &CheckedVarArgs, 6828 UncoveredArgHandler &UncoveredArg, 6829 llvm::APSInt Offset, 6830 bool IgnoreStringsWithoutSpecifiers = false) { 6831 if (S.isConstantEvaluated()) 6832 return SLCT_NotALiteral; 6833 tryAgain: 6834 assert(Offset.isSigned() && "invalid offset"); 6835 6836 if (E->isTypeDependent() || E->isValueDependent()) 6837 return SLCT_NotALiteral; 6838 6839 E = E->IgnoreParenCasts(); 6840 6841 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6842 // Technically -Wformat-nonliteral does not warn about this case. 6843 // The behavior of printf and friends in this case is implementation 6844 // dependent. Ideally if the format string cannot be null then 6845 // it should have a 'nonnull' attribute in the function prototype. 6846 return SLCT_UncheckedLiteral; 6847 6848 switch (E->getStmtClass()) { 6849 case Stmt::BinaryConditionalOperatorClass: 6850 case Stmt::ConditionalOperatorClass: { 6851 // The expression is a literal if both sub-expressions were, and it was 6852 // completely checked only if both sub-expressions were checked. 6853 const AbstractConditionalOperator *C = 6854 cast<AbstractConditionalOperator>(E); 6855 6856 // Determine whether it is necessary to check both sub-expressions, for 6857 // example, because the condition expression is a constant that can be 6858 // evaluated at compile time. 6859 bool CheckLeft = true, CheckRight = true; 6860 6861 bool Cond; 6862 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6863 S.isConstantEvaluated())) { 6864 if (Cond) 6865 CheckRight = false; 6866 else 6867 CheckLeft = false; 6868 } 6869 6870 // We need to maintain the offsets for the right and the left hand side 6871 // separately to check if every possible indexed expression is a valid 6872 // string literal. They might have different offsets for different string 6873 // literals in the end. 6874 StringLiteralCheckType Left; 6875 if (!CheckLeft) 6876 Left = SLCT_UncheckedLiteral; 6877 else { 6878 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6879 HasVAListArg, format_idx, firstDataArg, 6880 Type, CallType, InFunctionCall, 6881 CheckedVarArgs, UncoveredArg, Offset, 6882 IgnoreStringsWithoutSpecifiers); 6883 if (Left == SLCT_NotALiteral || !CheckRight) { 6884 return Left; 6885 } 6886 } 6887 6888 StringLiteralCheckType Right = checkFormatStringExpr( 6889 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6890 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6891 IgnoreStringsWithoutSpecifiers); 6892 6893 return (CheckLeft && Left < Right) ? Left : Right; 6894 } 6895 6896 case Stmt::ImplicitCastExprClass: 6897 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6898 goto tryAgain; 6899 6900 case Stmt::OpaqueValueExprClass: 6901 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6902 E = src; 6903 goto tryAgain; 6904 } 6905 return SLCT_NotALiteral; 6906 6907 case Stmt::PredefinedExprClass: 6908 // While __func__, etc., are technically not string literals, they 6909 // cannot contain format specifiers and thus are not a security 6910 // liability. 6911 return SLCT_UncheckedLiteral; 6912 6913 case Stmt::DeclRefExprClass: { 6914 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6915 6916 // As an exception, do not flag errors for variables binding to 6917 // const string literals. 6918 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6919 bool isConstant = false; 6920 QualType T = DR->getType(); 6921 6922 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6923 isConstant = AT->getElementType().isConstant(S.Context); 6924 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6925 isConstant = T.isConstant(S.Context) && 6926 PT->getPointeeType().isConstant(S.Context); 6927 } else if (T->isObjCObjectPointerType()) { 6928 // In ObjC, there is usually no "const ObjectPointer" type, 6929 // so don't check if the pointee type is constant. 6930 isConstant = T.isConstant(S.Context); 6931 } 6932 6933 if (isConstant) { 6934 if (const Expr *Init = VD->getAnyInitializer()) { 6935 // Look through initializers like const char c[] = { "foo" } 6936 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6937 if (InitList->isStringLiteralInit()) 6938 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6939 } 6940 return checkFormatStringExpr(S, Init, Args, 6941 HasVAListArg, format_idx, 6942 firstDataArg, Type, CallType, 6943 /*InFunctionCall*/ false, CheckedVarArgs, 6944 UncoveredArg, Offset); 6945 } 6946 } 6947 6948 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6949 // special check to see if the format string is a function parameter 6950 // of the function calling the printf function. If the function 6951 // has an attribute indicating it is a printf-like function, then we 6952 // should suppress warnings concerning non-literals being used in a call 6953 // to a vprintf function. For example: 6954 // 6955 // void 6956 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6957 // va_list ap; 6958 // va_start(ap, fmt); 6959 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6960 // ... 6961 // } 6962 if (HasVAListArg) { 6963 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6964 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6965 int PVIndex = PV->getFunctionScopeIndex() + 1; 6966 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6967 // adjust for implicit parameter 6968 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6969 if (MD->isInstance()) 6970 ++PVIndex; 6971 // We also check if the formats are compatible. 6972 // We can't pass a 'scanf' string to a 'printf' function. 6973 if (PVIndex == PVFormat->getFormatIdx() && 6974 Type == S.GetFormatStringType(PVFormat)) 6975 return SLCT_UncheckedLiteral; 6976 } 6977 } 6978 } 6979 } 6980 } 6981 6982 return SLCT_NotALiteral; 6983 } 6984 6985 case Stmt::CallExprClass: 6986 case Stmt::CXXMemberCallExprClass: { 6987 const CallExpr *CE = cast<CallExpr>(E); 6988 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6989 bool IsFirst = true; 6990 StringLiteralCheckType CommonResult; 6991 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6992 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6993 StringLiteralCheckType Result = checkFormatStringExpr( 6994 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6995 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6996 IgnoreStringsWithoutSpecifiers); 6997 if (IsFirst) { 6998 CommonResult = Result; 6999 IsFirst = false; 7000 } 7001 } 7002 if (!IsFirst) 7003 return CommonResult; 7004 7005 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7006 unsigned BuiltinID = FD->getBuiltinID(); 7007 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7008 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7009 const Expr *Arg = CE->getArg(0); 7010 return checkFormatStringExpr(S, Arg, Args, 7011 HasVAListArg, format_idx, 7012 firstDataArg, Type, CallType, 7013 InFunctionCall, CheckedVarArgs, 7014 UncoveredArg, Offset, 7015 IgnoreStringsWithoutSpecifiers); 7016 } 7017 } 7018 } 7019 7020 return SLCT_NotALiteral; 7021 } 7022 case Stmt::ObjCMessageExprClass: { 7023 const auto *ME = cast<ObjCMessageExpr>(E); 7024 if (const auto *MD = ME->getMethodDecl()) { 7025 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7026 // As a special case heuristic, if we're using the method -[NSBundle 7027 // localizedStringForKey:value:table:], ignore any key strings that lack 7028 // format specifiers. The idea is that if the key doesn't have any 7029 // format specifiers then its probably just a key to map to the 7030 // localized strings. If it does have format specifiers though, then its 7031 // likely that the text of the key is the format string in the 7032 // programmer's language, and should be checked. 7033 const ObjCInterfaceDecl *IFace; 7034 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7035 IFace->getIdentifier()->isStr("NSBundle") && 7036 MD->getSelector().isKeywordSelector( 7037 {"localizedStringForKey", "value", "table"})) { 7038 IgnoreStringsWithoutSpecifiers = true; 7039 } 7040 7041 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7042 return checkFormatStringExpr( 7043 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7044 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7045 IgnoreStringsWithoutSpecifiers); 7046 } 7047 } 7048 7049 return SLCT_NotALiteral; 7050 } 7051 case Stmt::ObjCStringLiteralClass: 7052 case Stmt::StringLiteralClass: { 7053 const StringLiteral *StrE = nullptr; 7054 7055 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7056 StrE = ObjCFExpr->getString(); 7057 else 7058 StrE = cast<StringLiteral>(E); 7059 7060 if (StrE) { 7061 if (Offset.isNegative() || Offset > StrE->getLength()) { 7062 // TODO: It would be better to have an explicit warning for out of 7063 // bounds literals. 7064 return SLCT_NotALiteral; 7065 } 7066 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7067 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7068 firstDataArg, Type, InFunctionCall, CallType, 7069 CheckedVarArgs, UncoveredArg, 7070 IgnoreStringsWithoutSpecifiers); 7071 return SLCT_CheckedLiteral; 7072 } 7073 7074 return SLCT_NotALiteral; 7075 } 7076 case Stmt::BinaryOperatorClass: { 7077 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7078 7079 // A string literal + an int offset is still a string literal. 7080 if (BinOp->isAdditiveOp()) { 7081 Expr::EvalResult LResult, RResult; 7082 7083 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7084 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7085 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7086 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7087 7088 if (LIsInt != RIsInt) { 7089 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7090 7091 if (LIsInt) { 7092 if (BinOpKind == BO_Add) { 7093 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7094 E = BinOp->getRHS(); 7095 goto tryAgain; 7096 } 7097 } else { 7098 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7099 E = BinOp->getLHS(); 7100 goto tryAgain; 7101 } 7102 } 7103 } 7104 7105 return SLCT_NotALiteral; 7106 } 7107 case Stmt::UnaryOperatorClass: { 7108 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7109 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7110 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7111 Expr::EvalResult IndexResult; 7112 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7113 Expr::SE_NoSideEffects, 7114 S.isConstantEvaluated())) { 7115 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7116 /*RHS is int*/ true); 7117 E = ASE->getBase(); 7118 goto tryAgain; 7119 } 7120 } 7121 7122 return SLCT_NotALiteral; 7123 } 7124 7125 default: 7126 return SLCT_NotALiteral; 7127 } 7128 } 7129 7130 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7131 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7132 .Case("scanf", FST_Scanf) 7133 .Cases("printf", "printf0", FST_Printf) 7134 .Cases("NSString", "CFString", FST_NSString) 7135 .Case("strftime", FST_Strftime) 7136 .Case("strfmon", FST_Strfmon) 7137 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7138 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7139 .Case("os_trace", FST_OSLog) 7140 .Case("os_log", FST_OSLog) 7141 .Default(FST_Unknown); 7142 } 7143 7144 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7145 /// functions) for correct use of format strings. 7146 /// Returns true if a format string has been fully checked. 7147 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7148 ArrayRef<const Expr *> Args, 7149 bool IsCXXMember, 7150 VariadicCallType CallType, 7151 SourceLocation Loc, SourceRange Range, 7152 llvm::SmallBitVector &CheckedVarArgs) { 7153 FormatStringInfo FSI; 7154 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7155 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7156 FSI.FirstDataArg, GetFormatStringType(Format), 7157 CallType, Loc, Range, CheckedVarArgs); 7158 return false; 7159 } 7160 7161 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7162 bool HasVAListArg, unsigned format_idx, 7163 unsigned firstDataArg, FormatStringType Type, 7164 VariadicCallType CallType, 7165 SourceLocation Loc, SourceRange Range, 7166 llvm::SmallBitVector &CheckedVarArgs) { 7167 // CHECK: printf/scanf-like function is called with no format string. 7168 if (format_idx >= Args.size()) { 7169 Diag(Loc, diag::warn_missing_format_string) << Range; 7170 return false; 7171 } 7172 7173 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7174 7175 // CHECK: format string is not a string literal. 7176 // 7177 // Dynamically generated format strings are difficult to 7178 // automatically vet at compile time. Requiring that format strings 7179 // are string literals: (1) permits the checking of format strings by 7180 // the compiler and thereby (2) can practically remove the source of 7181 // many format string exploits. 7182 7183 // Format string can be either ObjC string (e.g. @"%d") or 7184 // C string (e.g. "%d") 7185 // ObjC string uses the same format specifiers as C string, so we can use 7186 // the same format string checking logic for both ObjC and C strings. 7187 UncoveredArgHandler UncoveredArg; 7188 StringLiteralCheckType CT = 7189 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7190 format_idx, firstDataArg, Type, CallType, 7191 /*IsFunctionCall*/ true, CheckedVarArgs, 7192 UncoveredArg, 7193 /*no string offset*/ llvm::APSInt(64, false) = 0); 7194 7195 // Generate a diagnostic where an uncovered argument is detected. 7196 if (UncoveredArg.hasUncoveredArg()) { 7197 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7198 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7199 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7200 } 7201 7202 if (CT != SLCT_NotALiteral) 7203 // Literal format string found, check done! 7204 return CT == SLCT_CheckedLiteral; 7205 7206 // Strftime is particular as it always uses a single 'time' argument, 7207 // so it is safe to pass a non-literal string. 7208 if (Type == FST_Strftime) 7209 return false; 7210 7211 // Do not emit diag when the string param is a macro expansion and the 7212 // format is either NSString or CFString. This is a hack to prevent 7213 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7214 // which are usually used in place of NS and CF string literals. 7215 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7216 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7217 return false; 7218 7219 // If there are no arguments specified, warn with -Wformat-security, otherwise 7220 // warn only with -Wformat-nonliteral. 7221 if (Args.size() == firstDataArg) { 7222 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7223 << OrigFormatExpr->getSourceRange(); 7224 switch (Type) { 7225 default: 7226 break; 7227 case FST_Kprintf: 7228 case FST_FreeBSDKPrintf: 7229 case FST_Printf: 7230 Diag(FormatLoc, diag::note_format_security_fixit) 7231 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7232 break; 7233 case FST_NSString: 7234 Diag(FormatLoc, diag::note_format_security_fixit) 7235 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7236 break; 7237 } 7238 } else { 7239 Diag(FormatLoc, diag::warn_format_nonliteral) 7240 << OrigFormatExpr->getSourceRange(); 7241 } 7242 return false; 7243 } 7244 7245 namespace { 7246 7247 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7248 protected: 7249 Sema &S; 7250 const FormatStringLiteral *FExpr; 7251 const Expr *OrigFormatExpr; 7252 const Sema::FormatStringType FSType; 7253 const unsigned FirstDataArg; 7254 const unsigned NumDataArgs; 7255 const char *Beg; // Start of format string. 7256 const bool HasVAListArg; 7257 ArrayRef<const Expr *> Args; 7258 unsigned FormatIdx; 7259 llvm::SmallBitVector CoveredArgs; 7260 bool usesPositionalArgs = false; 7261 bool atFirstArg = true; 7262 bool inFunctionCall; 7263 Sema::VariadicCallType CallType; 7264 llvm::SmallBitVector &CheckedVarArgs; 7265 UncoveredArgHandler &UncoveredArg; 7266 7267 public: 7268 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7269 const Expr *origFormatExpr, 7270 const Sema::FormatStringType type, unsigned firstDataArg, 7271 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7272 ArrayRef<const Expr *> Args, unsigned formatIdx, 7273 bool inFunctionCall, Sema::VariadicCallType callType, 7274 llvm::SmallBitVector &CheckedVarArgs, 7275 UncoveredArgHandler &UncoveredArg) 7276 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7277 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7278 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7279 inFunctionCall(inFunctionCall), CallType(callType), 7280 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7281 CoveredArgs.resize(numDataArgs); 7282 CoveredArgs.reset(); 7283 } 7284 7285 void DoneProcessing(); 7286 7287 void HandleIncompleteSpecifier(const char *startSpecifier, 7288 unsigned specifierLen) override; 7289 7290 void HandleInvalidLengthModifier( 7291 const analyze_format_string::FormatSpecifier &FS, 7292 const analyze_format_string::ConversionSpecifier &CS, 7293 const char *startSpecifier, unsigned specifierLen, 7294 unsigned DiagID); 7295 7296 void HandleNonStandardLengthModifier( 7297 const analyze_format_string::FormatSpecifier &FS, 7298 const char *startSpecifier, unsigned specifierLen); 7299 7300 void HandleNonStandardConversionSpecifier( 7301 const analyze_format_string::ConversionSpecifier &CS, 7302 const char *startSpecifier, unsigned specifierLen); 7303 7304 void HandlePosition(const char *startPos, unsigned posLen) override; 7305 7306 void HandleInvalidPosition(const char *startSpecifier, 7307 unsigned specifierLen, 7308 analyze_format_string::PositionContext p) override; 7309 7310 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7311 7312 void HandleNullChar(const char *nullCharacter) override; 7313 7314 template <typename Range> 7315 static void 7316 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7317 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7318 bool IsStringLocation, Range StringRange, 7319 ArrayRef<FixItHint> Fixit = None); 7320 7321 protected: 7322 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7323 const char *startSpec, 7324 unsigned specifierLen, 7325 const char *csStart, unsigned csLen); 7326 7327 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7328 const char *startSpec, 7329 unsigned specifierLen); 7330 7331 SourceRange getFormatStringRange(); 7332 CharSourceRange getSpecifierRange(const char *startSpecifier, 7333 unsigned specifierLen); 7334 SourceLocation getLocationOfByte(const char *x); 7335 7336 const Expr *getDataArg(unsigned i) const; 7337 7338 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7339 const analyze_format_string::ConversionSpecifier &CS, 7340 const char *startSpecifier, unsigned specifierLen, 7341 unsigned argIndex); 7342 7343 template <typename Range> 7344 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7345 bool IsStringLocation, Range StringRange, 7346 ArrayRef<FixItHint> Fixit = None); 7347 }; 7348 7349 } // namespace 7350 7351 SourceRange CheckFormatHandler::getFormatStringRange() { 7352 return OrigFormatExpr->getSourceRange(); 7353 } 7354 7355 CharSourceRange CheckFormatHandler:: 7356 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7357 SourceLocation Start = getLocationOfByte(startSpecifier); 7358 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7359 7360 // Advance the end SourceLocation by one due to half-open ranges. 7361 End = End.getLocWithOffset(1); 7362 7363 return CharSourceRange::getCharRange(Start, End); 7364 } 7365 7366 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7367 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7368 S.getLangOpts(), S.Context.getTargetInfo()); 7369 } 7370 7371 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7372 unsigned specifierLen){ 7373 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7374 getLocationOfByte(startSpecifier), 7375 /*IsStringLocation*/true, 7376 getSpecifierRange(startSpecifier, specifierLen)); 7377 } 7378 7379 void CheckFormatHandler::HandleInvalidLengthModifier( 7380 const analyze_format_string::FormatSpecifier &FS, 7381 const analyze_format_string::ConversionSpecifier &CS, 7382 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7383 using namespace analyze_format_string; 7384 7385 const LengthModifier &LM = FS.getLengthModifier(); 7386 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7387 7388 // See if we know how to fix this length modifier. 7389 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7390 if (FixedLM) { 7391 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7392 getLocationOfByte(LM.getStart()), 7393 /*IsStringLocation*/true, 7394 getSpecifierRange(startSpecifier, specifierLen)); 7395 7396 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7397 << FixedLM->toString() 7398 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7399 7400 } else { 7401 FixItHint Hint; 7402 if (DiagID == diag::warn_format_nonsensical_length) 7403 Hint = FixItHint::CreateRemoval(LMRange); 7404 7405 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7406 getLocationOfByte(LM.getStart()), 7407 /*IsStringLocation*/true, 7408 getSpecifierRange(startSpecifier, specifierLen), 7409 Hint); 7410 } 7411 } 7412 7413 void CheckFormatHandler::HandleNonStandardLengthModifier( 7414 const analyze_format_string::FormatSpecifier &FS, 7415 const char *startSpecifier, unsigned specifierLen) { 7416 using namespace analyze_format_string; 7417 7418 const LengthModifier &LM = FS.getLengthModifier(); 7419 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7420 7421 // See if we know how to fix this length modifier. 7422 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7423 if (FixedLM) { 7424 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7425 << LM.toString() << 0, 7426 getLocationOfByte(LM.getStart()), 7427 /*IsStringLocation*/true, 7428 getSpecifierRange(startSpecifier, specifierLen)); 7429 7430 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7431 << FixedLM->toString() 7432 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7433 7434 } else { 7435 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7436 << LM.toString() << 0, 7437 getLocationOfByte(LM.getStart()), 7438 /*IsStringLocation*/true, 7439 getSpecifierRange(startSpecifier, specifierLen)); 7440 } 7441 } 7442 7443 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7444 const analyze_format_string::ConversionSpecifier &CS, 7445 const char *startSpecifier, unsigned specifierLen) { 7446 using namespace analyze_format_string; 7447 7448 // See if we know how to fix this conversion specifier. 7449 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7450 if (FixedCS) { 7451 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7452 << CS.toString() << /*conversion specifier*/1, 7453 getLocationOfByte(CS.getStart()), 7454 /*IsStringLocation*/true, 7455 getSpecifierRange(startSpecifier, specifierLen)); 7456 7457 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7458 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7459 << FixedCS->toString() 7460 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7461 } else { 7462 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7463 << CS.toString() << /*conversion specifier*/1, 7464 getLocationOfByte(CS.getStart()), 7465 /*IsStringLocation*/true, 7466 getSpecifierRange(startSpecifier, specifierLen)); 7467 } 7468 } 7469 7470 void CheckFormatHandler::HandlePosition(const char *startPos, 7471 unsigned posLen) { 7472 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7473 getLocationOfByte(startPos), 7474 /*IsStringLocation*/true, 7475 getSpecifierRange(startPos, posLen)); 7476 } 7477 7478 void 7479 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7480 analyze_format_string::PositionContext p) { 7481 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7482 << (unsigned) p, 7483 getLocationOfByte(startPos), /*IsStringLocation*/true, 7484 getSpecifierRange(startPos, posLen)); 7485 } 7486 7487 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7488 unsigned posLen) { 7489 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7490 getLocationOfByte(startPos), 7491 /*IsStringLocation*/true, 7492 getSpecifierRange(startPos, posLen)); 7493 } 7494 7495 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7496 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7497 // The presence of a null character is likely an error. 7498 EmitFormatDiagnostic( 7499 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7500 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7501 getFormatStringRange()); 7502 } 7503 } 7504 7505 // Note that this may return NULL if there was an error parsing or building 7506 // one of the argument expressions. 7507 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7508 return Args[FirstDataArg + i]; 7509 } 7510 7511 void CheckFormatHandler::DoneProcessing() { 7512 // Does the number of data arguments exceed the number of 7513 // format conversions in the format string? 7514 if (!HasVAListArg) { 7515 // Find any arguments that weren't covered. 7516 CoveredArgs.flip(); 7517 signed notCoveredArg = CoveredArgs.find_first(); 7518 if (notCoveredArg >= 0) { 7519 assert((unsigned)notCoveredArg < NumDataArgs); 7520 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7521 } else { 7522 UncoveredArg.setAllCovered(); 7523 } 7524 } 7525 } 7526 7527 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7528 const Expr *ArgExpr) { 7529 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7530 "Invalid state"); 7531 7532 if (!ArgExpr) 7533 return; 7534 7535 SourceLocation Loc = ArgExpr->getBeginLoc(); 7536 7537 if (S.getSourceManager().isInSystemMacro(Loc)) 7538 return; 7539 7540 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7541 for (auto E : DiagnosticExprs) 7542 PDiag << E->getSourceRange(); 7543 7544 CheckFormatHandler::EmitFormatDiagnostic( 7545 S, IsFunctionCall, DiagnosticExprs[0], 7546 PDiag, Loc, /*IsStringLocation*/false, 7547 DiagnosticExprs[0]->getSourceRange()); 7548 } 7549 7550 bool 7551 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7552 SourceLocation Loc, 7553 const char *startSpec, 7554 unsigned specifierLen, 7555 const char *csStart, 7556 unsigned csLen) { 7557 bool keepGoing = true; 7558 if (argIndex < NumDataArgs) { 7559 // Consider the argument coverered, even though the specifier doesn't 7560 // make sense. 7561 CoveredArgs.set(argIndex); 7562 } 7563 else { 7564 // If argIndex exceeds the number of data arguments we 7565 // don't issue a warning because that is just a cascade of warnings (and 7566 // they may have intended '%%' anyway). We don't want to continue processing 7567 // the format string after this point, however, as we will like just get 7568 // gibberish when trying to match arguments. 7569 keepGoing = false; 7570 } 7571 7572 StringRef Specifier(csStart, csLen); 7573 7574 // If the specifier in non-printable, it could be the first byte of a UTF-8 7575 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7576 // hex value. 7577 std::string CodePointStr; 7578 if (!llvm::sys::locale::isPrint(*csStart)) { 7579 llvm::UTF32 CodePoint; 7580 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7581 const llvm::UTF8 *E = 7582 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7583 llvm::ConversionResult Result = 7584 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7585 7586 if (Result != llvm::conversionOK) { 7587 unsigned char FirstChar = *csStart; 7588 CodePoint = (llvm::UTF32)FirstChar; 7589 } 7590 7591 llvm::raw_string_ostream OS(CodePointStr); 7592 if (CodePoint < 256) 7593 OS << "\\x" << llvm::format("%02x", CodePoint); 7594 else if (CodePoint <= 0xFFFF) 7595 OS << "\\u" << llvm::format("%04x", CodePoint); 7596 else 7597 OS << "\\U" << llvm::format("%08x", CodePoint); 7598 OS.flush(); 7599 Specifier = CodePointStr; 7600 } 7601 7602 EmitFormatDiagnostic( 7603 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7604 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7605 7606 return keepGoing; 7607 } 7608 7609 void 7610 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7611 const char *startSpec, 7612 unsigned specifierLen) { 7613 EmitFormatDiagnostic( 7614 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7615 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7616 } 7617 7618 bool 7619 CheckFormatHandler::CheckNumArgs( 7620 const analyze_format_string::FormatSpecifier &FS, 7621 const analyze_format_string::ConversionSpecifier &CS, 7622 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7623 7624 if (argIndex >= NumDataArgs) { 7625 PartialDiagnostic PDiag = FS.usesPositionalArg() 7626 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7627 << (argIndex+1) << NumDataArgs) 7628 : S.PDiag(diag::warn_printf_insufficient_data_args); 7629 EmitFormatDiagnostic( 7630 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7631 getSpecifierRange(startSpecifier, specifierLen)); 7632 7633 // Since more arguments than conversion tokens are given, by extension 7634 // all arguments are covered, so mark this as so. 7635 UncoveredArg.setAllCovered(); 7636 return false; 7637 } 7638 return true; 7639 } 7640 7641 template<typename Range> 7642 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7643 SourceLocation Loc, 7644 bool IsStringLocation, 7645 Range StringRange, 7646 ArrayRef<FixItHint> FixIt) { 7647 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7648 Loc, IsStringLocation, StringRange, FixIt); 7649 } 7650 7651 /// If the format string is not within the function call, emit a note 7652 /// so that the function call and string are in diagnostic messages. 7653 /// 7654 /// \param InFunctionCall if true, the format string is within the function 7655 /// call and only one diagnostic message will be produced. Otherwise, an 7656 /// extra note will be emitted pointing to location of the format string. 7657 /// 7658 /// \param ArgumentExpr the expression that is passed as the format string 7659 /// argument in the function call. Used for getting locations when two 7660 /// diagnostics are emitted. 7661 /// 7662 /// \param PDiag the callee should already have provided any strings for the 7663 /// diagnostic message. This function only adds locations and fixits 7664 /// to diagnostics. 7665 /// 7666 /// \param Loc primary location for diagnostic. If two diagnostics are 7667 /// required, one will be at Loc and a new SourceLocation will be created for 7668 /// the other one. 7669 /// 7670 /// \param IsStringLocation if true, Loc points to the format string should be 7671 /// used for the note. Otherwise, Loc points to the argument list and will 7672 /// be used with PDiag. 7673 /// 7674 /// \param StringRange some or all of the string to highlight. This is 7675 /// templated so it can accept either a CharSourceRange or a SourceRange. 7676 /// 7677 /// \param FixIt optional fix it hint for the format string. 7678 template <typename Range> 7679 void CheckFormatHandler::EmitFormatDiagnostic( 7680 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7681 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7682 Range StringRange, ArrayRef<FixItHint> FixIt) { 7683 if (InFunctionCall) { 7684 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7685 D << StringRange; 7686 D << FixIt; 7687 } else { 7688 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7689 << ArgumentExpr->getSourceRange(); 7690 7691 const Sema::SemaDiagnosticBuilder &Note = 7692 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7693 diag::note_format_string_defined); 7694 7695 Note << StringRange; 7696 Note << FixIt; 7697 } 7698 } 7699 7700 //===--- CHECK: Printf format string checking ------------------------------===// 7701 7702 namespace { 7703 7704 class CheckPrintfHandler : public CheckFormatHandler { 7705 public: 7706 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7707 const Expr *origFormatExpr, 7708 const Sema::FormatStringType type, unsigned firstDataArg, 7709 unsigned numDataArgs, bool isObjC, const char *beg, 7710 bool hasVAListArg, ArrayRef<const Expr *> Args, 7711 unsigned formatIdx, bool inFunctionCall, 7712 Sema::VariadicCallType CallType, 7713 llvm::SmallBitVector &CheckedVarArgs, 7714 UncoveredArgHandler &UncoveredArg) 7715 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7716 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7717 inFunctionCall, CallType, CheckedVarArgs, 7718 UncoveredArg) {} 7719 7720 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7721 7722 /// Returns true if '%@' specifiers are allowed in the format string. 7723 bool allowsObjCArg() const { 7724 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7725 FSType == Sema::FST_OSTrace; 7726 } 7727 7728 bool HandleInvalidPrintfConversionSpecifier( 7729 const analyze_printf::PrintfSpecifier &FS, 7730 const char *startSpecifier, 7731 unsigned specifierLen) override; 7732 7733 void handleInvalidMaskType(StringRef MaskType) override; 7734 7735 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7736 const char *startSpecifier, 7737 unsigned specifierLen) override; 7738 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7739 const char *StartSpecifier, 7740 unsigned SpecifierLen, 7741 const Expr *E); 7742 7743 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7744 const char *startSpecifier, unsigned specifierLen); 7745 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7746 const analyze_printf::OptionalAmount &Amt, 7747 unsigned type, 7748 const char *startSpecifier, unsigned specifierLen); 7749 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7750 const analyze_printf::OptionalFlag &flag, 7751 const char *startSpecifier, unsigned specifierLen); 7752 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7753 const analyze_printf::OptionalFlag &ignoredFlag, 7754 const analyze_printf::OptionalFlag &flag, 7755 const char *startSpecifier, unsigned specifierLen); 7756 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7757 const Expr *E); 7758 7759 void HandleEmptyObjCModifierFlag(const char *startFlag, 7760 unsigned flagLen) override; 7761 7762 void HandleInvalidObjCModifierFlag(const char *startFlag, 7763 unsigned flagLen) override; 7764 7765 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7766 const char *flagsEnd, 7767 const char *conversionPosition) 7768 override; 7769 }; 7770 7771 } // namespace 7772 7773 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7774 const analyze_printf::PrintfSpecifier &FS, 7775 const char *startSpecifier, 7776 unsigned specifierLen) { 7777 const analyze_printf::PrintfConversionSpecifier &CS = 7778 FS.getConversionSpecifier(); 7779 7780 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7781 getLocationOfByte(CS.getStart()), 7782 startSpecifier, specifierLen, 7783 CS.getStart(), CS.getLength()); 7784 } 7785 7786 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7787 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7788 } 7789 7790 bool CheckPrintfHandler::HandleAmount( 7791 const analyze_format_string::OptionalAmount &Amt, 7792 unsigned k, const char *startSpecifier, 7793 unsigned specifierLen) { 7794 if (Amt.hasDataArgument()) { 7795 if (!HasVAListArg) { 7796 unsigned argIndex = Amt.getArgIndex(); 7797 if (argIndex >= NumDataArgs) { 7798 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7799 << k, 7800 getLocationOfByte(Amt.getStart()), 7801 /*IsStringLocation*/true, 7802 getSpecifierRange(startSpecifier, specifierLen)); 7803 // Don't do any more checking. We will just emit 7804 // spurious errors. 7805 return false; 7806 } 7807 7808 // Type check the data argument. It should be an 'int'. 7809 // Although not in conformance with C99, we also allow the argument to be 7810 // an 'unsigned int' as that is a reasonably safe case. GCC also 7811 // doesn't emit a warning for that case. 7812 CoveredArgs.set(argIndex); 7813 const Expr *Arg = getDataArg(argIndex); 7814 if (!Arg) 7815 return false; 7816 7817 QualType T = Arg->getType(); 7818 7819 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7820 assert(AT.isValid()); 7821 7822 if (!AT.matchesType(S.Context, T)) { 7823 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7824 << k << AT.getRepresentativeTypeName(S.Context) 7825 << T << Arg->getSourceRange(), 7826 getLocationOfByte(Amt.getStart()), 7827 /*IsStringLocation*/true, 7828 getSpecifierRange(startSpecifier, specifierLen)); 7829 // Don't do any more checking. We will just emit 7830 // spurious errors. 7831 return false; 7832 } 7833 } 7834 } 7835 return true; 7836 } 7837 7838 void CheckPrintfHandler::HandleInvalidAmount( 7839 const analyze_printf::PrintfSpecifier &FS, 7840 const analyze_printf::OptionalAmount &Amt, 7841 unsigned type, 7842 const char *startSpecifier, 7843 unsigned specifierLen) { 7844 const analyze_printf::PrintfConversionSpecifier &CS = 7845 FS.getConversionSpecifier(); 7846 7847 FixItHint fixit = 7848 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7849 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7850 Amt.getConstantLength())) 7851 : FixItHint(); 7852 7853 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7854 << type << CS.toString(), 7855 getLocationOfByte(Amt.getStart()), 7856 /*IsStringLocation*/true, 7857 getSpecifierRange(startSpecifier, specifierLen), 7858 fixit); 7859 } 7860 7861 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7862 const analyze_printf::OptionalFlag &flag, 7863 const char *startSpecifier, 7864 unsigned specifierLen) { 7865 // Warn about pointless flag with a fixit removal. 7866 const analyze_printf::PrintfConversionSpecifier &CS = 7867 FS.getConversionSpecifier(); 7868 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7869 << flag.toString() << CS.toString(), 7870 getLocationOfByte(flag.getPosition()), 7871 /*IsStringLocation*/true, 7872 getSpecifierRange(startSpecifier, specifierLen), 7873 FixItHint::CreateRemoval( 7874 getSpecifierRange(flag.getPosition(), 1))); 7875 } 7876 7877 void CheckPrintfHandler::HandleIgnoredFlag( 7878 const analyze_printf::PrintfSpecifier &FS, 7879 const analyze_printf::OptionalFlag &ignoredFlag, 7880 const analyze_printf::OptionalFlag &flag, 7881 const char *startSpecifier, 7882 unsigned specifierLen) { 7883 // Warn about ignored flag with a fixit removal. 7884 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7885 << ignoredFlag.toString() << flag.toString(), 7886 getLocationOfByte(ignoredFlag.getPosition()), 7887 /*IsStringLocation*/true, 7888 getSpecifierRange(startSpecifier, specifierLen), 7889 FixItHint::CreateRemoval( 7890 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7891 } 7892 7893 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7894 unsigned flagLen) { 7895 // Warn about an empty flag. 7896 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7897 getLocationOfByte(startFlag), 7898 /*IsStringLocation*/true, 7899 getSpecifierRange(startFlag, flagLen)); 7900 } 7901 7902 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7903 unsigned flagLen) { 7904 // Warn about an invalid flag. 7905 auto Range = getSpecifierRange(startFlag, flagLen); 7906 StringRef flag(startFlag, flagLen); 7907 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7908 getLocationOfByte(startFlag), 7909 /*IsStringLocation*/true, 7910 Range, FixItHint::CreateRemoval(Range)); 7911 } 7912 7913 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7914 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7915 // Warn about using '[...]' without a '@' conversion. 7916 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7917 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7918 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7919 getLocationOfByte(conversionPosition), 7920 /*IsStringLocation*/true, 7921 Range, FixItHint::CreateRemoval(Range)); 7922 } 7923 7924 // Determines if the specified is a C++ class or struct containing 7925 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7926 // "c_str()"). 7927 template<typename MemberKind> 7928 static llvm::SmallPtrSet<MemberKind*, 1> 7929 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7930 const RecordType *RT = Ty->getAs<RecordType>(); 7931 llvm::SmallPtrSet<MemberKind*, 1> Results; 7932 7933 if (!RT) 7934 return Results; 7935 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7936 if (!RD || !RD->getDefinition()) 7937 return Results; 7938 7939 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7940 Sema::LookupMemberName); 7941 R.suppressDiagnostics(); 7942 7943 // We just need to include all members of the right kind turned up by the 7944 // filter, at this point. 7945 if (S.LookupQualifiedName(R, RT->getDecl())) 7946 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7947 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7948 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7949 Results.insert(FK); 7950 } 7951 return Results; 7952 } 7953 7954 /// Check if we could call '.c_str()' on an object. 7955 /// 7956 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7957 /// allow the call, or if it would be ambiguous). 7958 bool Sema::hasCStrMethod(const Expr *E) { 7959 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7960 7961 MethodSet Results = 7962 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7963 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7964 MI != ME; ++MI) 7965 if ((*MI)->getMinRequiredArguments() == 0) 7966 return true; 7967 return false; 7968 } 7969 7970 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7971 // better diagnostic if so. AT is assumed to be valid. 7972 // Returns true when a c_str() conversion method is found. 7973 bool CheckPrintfHandler::checkForCStrMembers( 7974 const analyze_printf::ArgType &AT, const Expr *E) { 7975 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7976 7977 MethodSet Results = 7978 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7979 7980 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7981 MI != ME; ++MI) { 7982 const CXXMethodDecl *Method = *MI; 7983 if (Method->getMinRequiredArguments() == 0 && 7984 AT.matchesType(S.Context, Method->getReturnType())) { 7985 // FIXME: Suggest parens if the expression needs them. 7986 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7987 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7988 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7989 return true; 7990 } 7991 } 7992 7993 return false; 7994 } 7995 7996 bool 7997 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7998 &FS, 7999 const char *startSpecifier, 8000 unsigned specifierLen) { 8001 using namespace analyze_format_string; 8002 using namespace analyze_printf; 8003 8004 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8005 8006 if (FS.consumesDataArgument()) { 8007 if (atFirstArg) { 8008 atFirstArg = false; 8009 usesPositionalArgs = FS.usesPositionalArg(); 8010 } 8011 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8012 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8013 startSpecifier, specifierLen); 8014 return false; 8015 } 8016 } 8017 8018 // First check if the field width, precision, and conversion specifier 8019 // have matching data arguments. 8020 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8021 startSpecifier, specifierLen)) { 8022 return false; 8023 } 8024 8025 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8026 startSpecifier, specifierLen)) { 8027 return false; 8028 } 8029 8030 if (!CS.consumesDataArgument()) { 8031 // FIXME: Technically specifying a precision or field width here 8032 // makes no sense. Worth issuing a warning at some point. 8033 return true; 8034 } 8035 8036 // Consume the argument. 8037 unsigned argIndex = FS.getArgIndex(); 8038 if (argIndex < NumDataArgs) { 8039 // The check to see if the argIndex is valid will come later. 8040 // We set the bit here because we may exit early from this 8041 // function if we encounter some other error. 8042 CoveredArgs.set(argIndex); 8043 } 8044 8045 // FreeBSD kernel extensions. 8046 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8047 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8048 // We need at least two arguments. 8049 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8050 return false; 8051 8052 // Claim the second argument. 8053 CoveredArgs.set(argIndex + 1); 8054 8055 // Type check the first argument (int for %b, pointer for %D) 8056 const Expr *Ex = getDataArg(argIndex); 8057 const analyze_printf::ArgType &AT = 8058 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8059 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8060 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8061 EmitFormatDiagnostic( 8062 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8063 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8064 << false << Ex->getSourceRange(), 8065 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8066 getSpecifierRange(startSpecifier, specifierLen)); 8067 8068 // Type check the second argument (char * for both %b and %D) 8069 Ex = getDataArg(argIndex + 1); 8070 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8071 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8072 EmitFormatDiagnostic( 8073 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8074 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8075 << false << Ex->getSourceRange(), 8076 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8077 getSpecifierRange(startSpecifier, specifierLen)); 8078 8079 return true; 8080 } 8081 8082 // Check for using an Objective-C specific conversion specifier 8083 // in a non-ObjC literal. 8084 if (!allowsObjCArg() && CS.isObjCArg()) { 8085 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8086 specifierLen); 8087 } 8088 8089 // %P can only be used with os_log. 8090 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8091 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8092 specifierLen); 8093 } 8094 8095 // %n is not allowed with os_log. 8096 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8097 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8098 getLocationOfByte(CS.getStart()), 8099 /*IsStringLocation*/ false, 8100 getSpecifierRange(startSpecifier, specifierLen)); 8101 8102 return true; 8103 } 8104 8105 // Only scalars are allowed for os_trace. 8106 if (FSType == Sema::FST_OSTrace && 8107 (CS.getKind() == ConversionSpecifier::PArg || 8108 CS.getKind() == ConversionSpecifier::sArg || 8109 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8110 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8111 specifierLen); 8112 } 8113 8114 // Check for use of public/private annotation outside of os_log(). 8115 if (FSType != Sema::FST_OSLog) { 8116 if (FS.isPublic().isSet()) { 8117 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8118 << "public", 8119 getLocationOfByte(FS.isPublic().getPosition()), 8120 /*IsStringLocation*/ false, 8121 getSpecifierRange(startSpecifier, specifierLen)); 8122 } 8123 if (FS.isPrivate().isSet()) { 8124 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8125 << "private", 8126 getLocationOfByte(FS.isPrivate().getPosition()), 8127 /*IsStringLocation*/ false, 8128 getSpecifierRange(startSpecifier, specifierLen)); 8129 } 8130 } 8131 8132 // Check for invalid use of field width 8133 if (!FS.hasValidFieldWidth()) { 8134 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8135 startSpecifier, specifierLen); 8136 } 8137 8138 // Check for invalid use of precision 8139 if (!FS.hasValidPrecision()) { 8140 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8141 startSpecifier, specifierLen); 8142 } 8143 8144 // Precision is mandatory for %P specifier. 8145 if (CS.getKind() == ConversionSpecifier::PArg && 8146 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8147 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8148 getLocationOfByte(startSpecifier), 8149 /*IsStringLocation*/ false, 8150 getSpecifierRange(startSpecifier, specifierLen)); 8151 } 8152 8153 // Check each flag does not conflict with any other component. 8154 if (!FS.hasValidThousandsGroupingPrefix()) 8155 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8156 if (!FS.hasValidLeadingZeros()) 8157 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8158 if (!FS.hasValidPlusPrefix()) 8159 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8160 if (!FS.hasValidSpacePrefix()) 8161 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8162 if (!FS.hasValidAlternativeForm()) 8163 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8164 if (!FS.hasValidLeftJustified()) 8165 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8166 8167 // Check that flags are not ignored by another flag 8168 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8169 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8170 startSpecifier, specifierLen); 8171 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8172 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8173 startSpecifier, specifierLen); 8174 8175 // Check the length modifier is valid with the given conversion specifier. 8176 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8177 S.getLangOpts())) 8178 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8179 diag::warn_format_nonsensical_length); 8180 else if (!FS.hasStandardLengthModifier()) 8181 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8182 else if (!FS.hasStandardLengthConversionCombination()) 8183 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8184 diag::warn_format_non_standard_conversion_spec); 8185 8186 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8187 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8188 8189 // The remaining checks depend on the data arguments. 8190 if (HasVAListArg) 8191 return true; 8192 8193 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8194 return false; 8195 8196 const Expr *Arg = getDataArg(argIndex); 8197 if (!Arg) 8198 return true; 8199 8200 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8201 } 8202 8203 static bool requiresParensToAddCast(const Expr *E) { 8204 // FIXME: We should have a general way to reason about operator 8205 // precedence and whether parens are actually needed here. 8206 // Take care of a few common cases where they aren't. 8207 const Expr *Inside = E->IgnoreImpCasts(); 8208 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8209 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8210 8211 switch (Inside->getStmtClass()) { 8212 case Stmt::ArraySubscriptExprClass: 8213 case Stmt::CallExprClass: 8214 case Stmt::CharacterLiteralClass: 8215 case Stmt::CXXBoolLiteralExprClass: 8216 case Stmt::DeclRefExprClass: 8217 case Stmt::FloatingLiteralClass: 8218 case Stmt::IntegerLiteralClass: 8219 case Stmt::MemberExprClass: 8220 case Stmt::ObjCArrayLiteralClass: 8221 case Stmt::ObjCBoolLiteralExprClass: 8222 case Stmt::ObjCBoxedExprClass: 8223 case Stmt::ObjCDictionaryLiteralClass: 8224 case Stmt::ObjCEncodeExprClass: 8225 case Stmt::ObjCIvarRefExprClass: 8226 case Stmt::ObjCMessageExprClass: 8227 case Stmt::ObjCPropertyRefExprClass: 8228 case Stmt::ObjCStringLiteralClass: 8229 case Stmt::ObjCSubscriptRefExprClass: 8230 case Stmt::ParenExprClass: 8231 case Stmt::StringLiteralClass: 8232 case Stmt::UnaryOperatorClass: 8233 return false; 8234 default: 8235 return true; 8236 } 8237 } 8238 8239 static std::pair<QualType, StringRef> 8240 shouldNotPrintDirectly(const ASTContext &Context, 8241 QualType IntendedTy, 8242 const Expr *E) { 8243 // Use a 'while' to peel off layers of typedefs. 8244 QualType TyTy = IntendedTy; 8245 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8246 StringRef Name = UserTy->getDecl()->getName(); 8247 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8248 .Case("CFIndex", Context.getNSIntegerType()) 8249 .Case("NSInteger", Context.getNSIntegerType()) 8250 .Case("NSUInteger", Context.getNSUIntegerType()) 8251 .Case("SInt32", Context.IntTy) 8252 .Case("UInt32", Context.UnsignedIntTy) 8253 .Default(QualType()); 8254 8255 if (!CastTy.isNull()) 8256 return std::make_pair(CastTy, Name); 8257 8258 TyTy = UserTy->desugar(); 8259 } 8260 8261 // Strip parens if necessary. 8262 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8263 return shouldNotPrintDirectly(Context, 8264 PE->getSubExpr()->getType(), 8265 PE->getSubExpr()); 8266 8267 // If this is a conditional expression, then its result type is constructed 8268 // via usual arithmetic conversions and thus there might be no necessary 8269 // typedef sugar there. Recurse to operands to check for NSInteger & 8270 // Co. usage condition. 8271 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8272 QualType TrueTy, FalseTy; 8273 StringRef TrueName, FalseName; 8274 8275 std::tie(TrueTy, TrueName) = 8276 shouldNotPrintDirectly(Context, 8277 CO->getTrueExpr()->getType(), 8278 CO->getTrueExpr()); 8279 std::tie(FalseTy, FalseName) = 8280 shouldNotPrintDirectly(Context, 8281 CO->getFalseExpr()->getType(), 8282 CO->getFalseExpr()); 8283 8284 if (TrueTy == FalseTy) 8285 return std::make_pair(TrueTy, TrueName); 8286 else if (TrueTy.isNull()) 8287 return std::make_pair(FalseTy, FalseName); 8288 else if (FalseTy.isNull()) 8289 return std::make_pair(TrueTy, TrueName); 8290 } 8291 8292 return std::make_pair(QualType(), StringRef()); 8293 } 8294 8295 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8296 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8297 /// type do not count. 8298 static bool 8299 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8300 QualType From = ICE->getSubExpr()->getType(); 8301 QualType To = ICE->getType(); 8302 // It's an integer promotion if the destination type is the promoted 8303 // source type. 8304 if (ICE->getCastKind() == CK_IntegralCast && 8305 From->isPromotableIntegerType() && 8306 S.Context.getPromotedIntegerType(From) == To) 8307 return true; 8308 // Look through vector types, since we do default argument promotion for 8309 // those in OpenCL. 8310 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8311 From = VecTy->getElementType(); 8312 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8313 To = VecTy->getElementType(); 8314 // It's a floating promotion if the source type is a lower rank. 8315 return ICE->getCastKind() == CK_FloatingCast && 8316 S.Context.getFloatingTypeOrder(From, To) < 0; 8317 } 8318 8319 bool 8320 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8321 const char *StartSpecifier, 8322 unsigned SpecifierLen, 8323 const Expr *E) { 8324 using namespace analyze_format_string; 8325 using namespace analyze_printf; 8326 8327 // Now type check the data expression that matches the 8328 // format specifier. 8329 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8330 if (!AT.isValid()) 8331 return true; 8332 8333 QualType ExprTy = E->getType(); 8334 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8335 ExprTy = TET->getUnderlyingExpr()->getType(); 8336 } 8337 8338 // Diagnose attempts to print a boolean value as a character. Unlike other 8339 // -Wformat diagnostics, this is fine from a type perspective, but it still 8340 // doesn't make sense. 8341 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8342 E->isKnownToHaveBooleanValue()) { 8343 const CharSourceRange &CSR = 8344 getSpecifierRange(StartSpecifier, SpecifierLen); 8345 SmallString<4> FSString; 8346 llvm::raw_svector_ostream os(FSString); 8347 FS.toString(os); 8348 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8349 << FSString, 8350 E->getExprLoc(), false, CSR); 8351 return true; 8352 } 8353 8354 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8355 if (Match == analyze_printf::ArgType::Match) 8356 return true; 8357 8358 // Look through argument promotions for our error message's reported type. 8359 // This includes the integral and floating promotions, but excludes array 8360 // and function pointer decay (seeing that an argument intended to be a 8361 // string has type 'char [6]' is probably more confusing than 'char *') and 8362 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8363 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8364 if (isArithmeticArgumentPromotion(S, ICE)) { 8365 E = ICE->getSubExpr(); 8366 ExprTy = E->getType(); 8367 8368 // Check if we didn't match because of an implicit cast from a 'char' 8369 // or 'short' to an 'int'. This is done because printf is a varargs 8370 // function. 8371 if (ICE->getType() == S.Context.IntTy || 8372 ICE->getType() == S.Context.UnsignedIntTy) { 8373 // All further checking is done on the subexpression 8374 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8375 AT.matchesType(S.Context, ExprTy); 8376 if (ImplicitMatch == analyze_printf::ArgType::Match) 8377 return true; 8378 if (ImplicitMatch == ArgType::NoMatchPedantic || 8379 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8380 Match = ImplicitMatch; 8381 } 8382 } 8383 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8384 // Special case for 'a', which has type 'int' in C. 8385 // Note, however, that we do /not/ want to treat multibyte constants like 8386 // 'MooV' as characters! This form is deprecated but still exists. 8387 if (ExprTy == S.Context.IntTy) 8388 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8389 ExprTy = S.Context.CharTy; 8390 } 8391 8392 // Look through enums to their underlying type. 8393 bool IsEnum = false; 8394 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8395 ExprTy = EnumTy->getDecl()->getIntegerType(); 8396 IsEnum = true; 8397 } 8398 8399 // %C in an Objective-C context prints a unichar, not a wchar_t. 8400 // If the argument is an integer of some kind, believe the %C and suggest 8401 // a cast instead of changing the conversion specifier. 8402 QualType IntendedTy = ExprTy; 8403 if (isObjCContext() && 8404 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8405 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8406 !ExprTy->isCharType()) { 8407 // 'unichar' is defined as a typedef of unsigned short, but we should 8408 // prefer using the typedef if it is visible. 8409 IntendedTy = S.Context.UnsignedShortTy; 8410 8411 // While we are here, check if the value is an IntegerLiteral that happens 8412 // to be within the valid range. 8413 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8414 const llvm::APInt &V = IL->getValue(); 8415 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8416 return true; 8417 } 8418 8419 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8420 Sema::LookupOrdinaryName); 8421 if (S.LookupName(Result, S.getCurScope())) { 8422 NamedDecl *ND = Result.getFoundDecl(); 8423 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8424 if (TD->getUnderlyingType() == IntendedTy) 8425 IntendedTy = S.Context.getTypedefType(TD); 8426 } 8427 } 8428 } 8429 8430 // Special-case some of Darwin's platform-independence types by suggesting 8431 // casts to primitive types that are known to be large enough. 8432 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8433 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8434 QualType CastTy; 8435 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8436 if (!CastTy.isNull()) { 8437 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8438 // (long in ASTContext). Only complain to pedants. 8439 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8440 (AT.isSizeT() || AT.isPtrdiffT()) && 8441 AT.matchesType(S.Context, CastTy)) 8442 Match = ArgType::NoMatchPedantic; 8443 IntendedTy = CastTy; 8444 ShouldNotPrintDirectly = true; 8445 } 8446 } 8447 8448 // We may be able to offer a FixItHint if it is a supported type. 8449 PrintfSpecifier fixedFS = FS; 8450 bool Success = 8451 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8452 8453 if (Success) { 8454 // Get the fix string from the fixed format specifier 8455 SmallString<16> buf; 8456 llvm::raw_svector_ostream os(buf); 8457 fixedFS.toString(os); 8458 8459 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8460 8461 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8462 unsigned Diag; 8463 switch (Match) { 8464 case ArgType::Match: llvm_unreachable("expected non-matching"); 8465 case ArgType::NoMatchPedantic: 8466 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8467 break; 8468 case ArgType::NoMatchTypeConfusion: 8469 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8470 break; 8471 case ArgType::NoMatch: 8472 Diag = diag::warn_format_conversion_argument_type_mismatch; 8473 break; 8474 } 8475 8476 // In this case, the specifier is wrong and should be changed to match 8477 // the argument. 8478 EmitFormatDiagnostic(S.PDiag(Diag) 8479 << AT.getRepresentativeTypeName(S.Context) 8480 << IntendedTy << IsEnum << E->getSourceRange(), 8481 E->getBeginLoc(), 8482 /*IsStringLocation*/ false, SpecRange, 8483 FixItHint::CreateReplacement(SpecRange, os.str())); 8484 } else { 8485 // The canonical type for formatting this value is different from the 8486 // actual type of the expression. (This occurs, for example, with Darwin's 8487 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8488 // should be printed as 'long' for 64-bit compatibility.) 8489 // Rather than emitting a normal format/argument mismatch, we want to 8490 // add a cast to the recommended type (and correct the format string 8491 // if necessary). 8492 SmallString<16> CastBuf; 8493 llvm::raw_svector_ostream CastFix(CastBuf); 8494 CastFix << "("; 8495 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8496 CastFix << ")"; 8497 8498 SmallVector<FixItHint,4> Hints; 8499 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8500 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8501 8502 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8503 // If there's already a cast present, just replace it. 8504 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8505 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8506 8507 } else if (!requiresParensToAddCast(E)) { 8508 // If the expression has high enough precedence, 8509 // just write the C-style cast. 8510 Hints.push_back( 8511 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8512 } else { 8513 // Otherwise, add parens around the expression as well as the cast. 8514 CastFix << "("; 8515 Hints.push_back( 8516 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8517 8518 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8519 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8520 } 8521 8522 if (ShouldNotPrintDirectly) { 8523 // The expression has a type that should not be printed directly. 8524 // We extract the name from the typedef because we don't want to show 8525 // the underlying type in the diagnostic. 8526 StringRef Name; 8527 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8528 Name = TypedefTy->getDecl()->getName(); 8529 else 8530 Name = CastTyName; 8531 unsigned Diag = Match == ArgType::NoMatchPedantic 8532 ? diag::warn_format_argument_needs_cast_pedantic 8533 : diag::warn_format_argument_needs_cast; 8534 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8535 << E->getSourceRange(), 8536 E->getBeginLoc(), /*IsStringLocation=*/false, 8537 SpecRange, Hints); 8538 } else { 8539 // In this case, the expression could be printed using a different 8540 // specifier, but we've decided that the specifier is probably correct 8541 // and we should cast instead. Just use the normal warning message. 8542 EmitFormatDiagnostic( 8543 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8544 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8545 << E->getSourceRange(), 8546 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8547 } 8548 } 8549 } else { 8550 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8551 SpecifierLen); 8552 // Since the warning for passing non-POD types to variadic functions 8553 // was deferred until now, we emit a warning for non-POD 8554 // arguments here. 8555 switch (S.isValidVarArgType(ExprTy)) { 8556 case Sema::VAK_Valid: 8557 case Sema::VAK_ValidInCXX11: { 8558 unsigned Diag; 8559 switch (Match) { 8560 case ArgType::Match: llvm_unreachable("expected non-matching"); 8561 case ArgType::NoMatchPedantic: 8562 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8563 break; 8564 case ArgType::NoMatchTypeConfusion: 8565 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8566 break; 8567 case ArgType::NoMatch: 8568 Diag = diag::warn_format_conversion_argument_type_mismatch; 8569 break; 8570 } 8571 8572 EmitFormatDiagnostic( 8573 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8574 << IsEnum << CSR << E->getSourceRange(), 8575 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8576 break; 8577 } 8578 case Sema::VAK_Undefined: 8579 case Sema::VAK_MSVCUndefined: 8580 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8581 << S.getLangOpts().CPlusPlus11 << ExprTy 8582 << CallType 8583 << AT.getRepresentativeTypeName(S.Context) << CSR 8584 << E->getSourceRange(), 8585 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8586 checkForCStrMembers(AT, E); 8587 break; 8588 8589 case Sema::VAK_Invalid: 8590 if (ExprTy->isObjCObjectType()) 8591 EmitFormatDiagnostic( 8592 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8593 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8594 << AT.getRepresentativeTypeName(S.Context) << CSR 8595 << E->getSourceRange(), 8596 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8597 else 8598 // FIXME: If this is an initializer list, suggest removing the braces 8599 // or inserting a cast to the target type. 8600 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8601 << isa<InitListExpr>(E) << ExprTy << CallType 8602 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8603 break; 8604 } 8605 8606 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8607 "format string specifier index out of range"); 8608 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8609 } 8610 8611 return true; 8612 } 8613 8614 //===--- CHECK: Scanf format string checking ------------------------------===// 8615 8616 namespace { 8617 8618 class CheckScanfHandler : public CheckFormatHandler { 8619 public: 8620 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8621 const Expr *origFormatExpr, Sema::FormatStringType type, 8622 unsigned firstDataArg, unsigned numDataArgs, 8623 const char *beg, bool hasVAListArg, 8624 ArrayRef<const Expr *> Args, unsigned formatIdx, 8625 bool inFunctionCall, Sema::VariadicCallType CallType, 8626 llvm::SmallBitVector &CheckedVarArgs, 8627 UncoveredArgHandler &UncoveredArg) 8628 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8629 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8630 inFunctionCall, CallType, CheckedVarArgs, 8631 UncoveredArg) {} 8632 8633 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8634 const char *startSpecifier, 8635 unsigned specifierLen) override; 8636 8637 bool HandleInvalidScanfConversionSpecifier( 8638 const analyze_scanf::ScanfSpecifier &FS, 8639 const char *startSpecifier, 8640 unsigned specifierLen) override; 8641 8642 void HandleIncompleteScanList(const char *start, const char *end) override; 8643 }; 8644 8645 } // namespace 8646 8647 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8648 const char *end) { 8649 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8650 getLocationOfByte(end), /*IsStringLocation*/true, 8651 getSpecifierRange(start, end - start)); 8652 } 8653 8654 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8655 const analyze_scanf::ScanfSpecifier &FS, 8656 const char *startSpecifier, 8657 unsigned specifierLen) { 8658 const analyze_scanf::ScanfConversionSpecifier &CS = 8659 FS.getConversionSpecifier(); 8660 8661 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8662 getLocationOfByte(CS.getStart()), 8663 startSpecifier, specifierLen, 8664 CS.getStart(), CS.getLength()); 8665 } 8666 8667 bool CheckScanfHandler::HandleScanfSpecifier( 8668 const analyze_scanf::ScanfSpecifier &FS, 8669 const char *startSpecifier, 8670 unsigned specifierLen) { 8671 using namespace analyze_scanf; 8672 using namespace analyze_format_string; 8673 8674 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8675 8676 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8677 // be used to decide if we are using positional arguments consistently. 8678 if (FS.consumesDataArgument()) { 8679 if (atFirstArg) { 8680 atFirstArg = false; 8681 usesPositionalArgs = FS.usesPositionalArg(); 8682 } 8683 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8684 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8685 startSpecifier, specifierLen); 8686 return false; 8687 } 8688 } 8689 8690 // Check if the field with is non-zero. 8691 const OptionalAmount &Amt = FS.getFieldWidth(); 8692 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8693 if (Amt.getConstantAmount() == 0) { 8694 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8695 Amt.getConstantLength()); 8696 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8697 getLocationOfByte(Amt.getStart()), 8698 /*IsStringLocation*/true, R, 8699 FixItHint::CreateRemoval(R)); 8700 } 8701 } 8702 8703 if (!FS.consumesDataArgument()) { 8704 // FIXME: Technically specifying a precision or field width here 8705 // makes no sense. Worth issuing a warning at some point. 8706 return true; 8707 } 8708 8709 // Consume the argument. 8710 unsigned argIndex = FS.getArgIndex(); 8711 if (argIndex < NumDataArgs) { 8712 // The check to see if the argIndex is valid will come later. 8713 // We set the bit here because we may exit early from this 8714 // function if we encounter some other error. 8715 CoveredArgs.set(argIndex); 8716 } 8717 8718 // Check the length modifier is valid with the given conversion specifier. 8719 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8720 S.getLangOpts())) 8721 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8722 diag::warn_format_nonsensical_length); 8723 else if (!FS.hasStandardLengthModifier()) 8724 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8725 else if (!FS.hasStandardLengthConversionCombination()) 8726 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8727 diag::warn_format_non_standard_conversion_spec); 8728 8729 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8730 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8731 8732 // The remaining checks depend on the data arguments. 8733 if (HasVAListArg) 8734 return true; 8735 8736 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8737 return false; 8738 8739 // Check that the argument type matches the format specifier. 8740 const Expr *Ex = getDataArg(argIndex); 8741 if (!Ex) 8742 return true; 8743 8744 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8745 8746 if (!AT.isValid()) { 8747 return true; 8748 } 8749 8750 analyze_format_string::ArgType::MatchKind Match = 8751 AT.matchesType(S.Context, Ex->getType()); 8752 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8753 if (Match == analyze_format_string::ArgType::Match) 8754 return true; 8755 8756 ScanfSpecifier fixedFS = FS; 8757 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8758 S.getLangOpts(), S.Context); 8759 8760 unsigned Diag = 8761 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8762 : diag::warn_format_conversion_argument_type_mismatch; 8763 8764 if (Success) { 8765 // Get the fix string from the fixed format specifier. 8766 SmallString<128> buf; 8767 llvm::raw_svector_ostream os(buf); 8768 fixedFS.toString(os); 8769 8770 EmitFormatDiagnostic( 8771 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8772 << Ex->getType() << false << Ex->getSourceRange(), 8773 Ex->getBeginLoc(), 8774 /*IsStringLocation*/ false, 8775 getSpecifierRange(startSpecifier, specifierLen), 8776 FixItHint::CreateReplacement( 8777 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8778 } else { 8779 EmitFormatDiagnostic(S.PDiag(Diag) 8780 << AT.getRepresentativeTypeName(S.Context) 8781 << Ex->getType() << false << Ex->getSourceRange(), 8782 Ex->getBeginLoc(), 8783 /*IsStringLocation*/ false, 8784 getSpecifierRange(startSpecifier, specifierLen)); 8785 } 8786 8787 return true; 8788 } 8789 8790 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8791 const Expr *OrigFormatExpr, 8792 ArrayRef<const Expr *> Args, 8793 bool HasVAListArg, unsigned format_idx, 8794 unsigned firstDataArg, 8795 Sema::FormatStringType Type, 8796 bool inFunctionCall, 8797 Sema::VariadicCallType CallType, 8798 llvm::SmallBitVector &CheckedVarArgs, 8799 UncoveredArgHandler &UncoveredArg, 8800 bool IgnoreStringsWithoutSpecifiers) { 8801 // CHECK: is the format string a wide literal? 8802 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8803 CheckFormatHandler::EmitFormatDiagnostic( 8804 S, inFunctionCall, Args[format_idx], 8805 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8806 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8807 return; 8808 } 8809 8810 // Str - The format string. NOTE: this is NOT null-terminated! 8811 StringRef StrRef = FExpr->getString(); 8812 const char *Str = StrRef.data(); 8813 // Account for cases where the string literal is truncated in a declaration. 8814 const ConstantArrayType *T = 8815 S.Context.getAsConstantArrayType(FExpr->getType()); 8816 assert(T && "String literal not of constant array type!"); 8817 size_t TypeSize = T->getSize().getZExtValue(); 8818 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8819 const unsigned numDataArgs = Args.size() - firstDataArg; 8820 8821 if (IgnoreStringsWithoutSpecifiers && 8822 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8823 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8824 return; 8825 8826 // Emit a warning if the string literal is truncated and does not contain an 8827 // embedded null character. 8828 if (TypeSize <= StrRef.size() && 8829 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8830 CheckFormatHandler::EmitFormatDiagnostic( 8831 S, inFunctionCall, Args[format_idx], 8832 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8833 FExpr->getBeginLoc(), 8834 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8835 return; 8836 } 8837 8838 // CHECK: empty format string? 8839 if (StrLen == 0 && numDataArgs > 0) { 8840 CheckFormatHandler::EmitFormatDiagnostic( 8841 S, inFunctionCall, Args[format_idx], 8842 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8843 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8844 return; 8845 } 8846 8847 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8848 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8849 Type == Sema::FST_OSTrace) { 8850 CheckPrintfHandler H( 8851 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8852 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8853 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8854 CheckedVarArgs, UncoveredArg); 8855 8856 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8857 S.getLangOpts(), 8858 S.Context.getTargetInfo(), 8859 Type == Sema::FST_FreeBSDKPrintf)) 8860 H.DoneProcessing(); 8861 } else if (Type == Sema::FST_Scanf) { 8862 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8863 numDataArgs, Str, HasVAListArg, Args, format_idx, 8864 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8865 8866 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8867 S.getLangOpts(), 8868 S.Context.getTargetInfo())) 8869 H.DoneProcessing(); 8870 } // TODO: handle other formats 8871 } 8872 8873 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8874 // Str - The format string. NOTE: this is NOT null-terminated! 8875 StringRef StrRef = FExpr->getString(); 8876 const char *Str = StrRef.data(); 8877 // Account for cases where the string literal is truncated in a declaration. 8878 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8879 assert(T && "String literal not of constant array type!"); 8880 size_t TypeSize = T->getSize().getZExtValue(); 8881 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8882 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8883 getLangOpts(), 8884 Context.getTargetInfo()); 8885 } 8886 8887 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8888 8889 // Returns the related absolute value function that is larger, of 0 if one 8890 // does not exist. 8891 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8892 switch (AbsFunction) { 8893 default: 8894 return 0; 8895 8896 case Builtin::BI__builtin_abs: 8897 return Builtin::BI__builtin_labs; 8898 case Builtin::BI__builtin_labs: 8899 return Builtin::BI__builtin_llabs; 8900 case Builtin::BI__builtin_llabs: 8901 return 0; 8902 8903 case Builtin::BI__builtin_fabsf: 8904 return Builtin::BI__builtin_fabs; 8905 case Builtin::BI__builtin_fabs: 8906 return Builtin::BI__builtin_fabsl; 8907 case Builtin::BI__builtin_fabsl: 8908 return 0; 8909 8910 case Builtin::BI__builtin_cabsf: 8911 return Builtin::BI__builtin_cabs; 8912 case Builtin::BI__builtin_cabs: 8913 return Builtin::BI__builtin_cabsl; 8914 case Builtin::BI__builtin_cabsl: 8915 return 0; 8916 8917 case Builtin::BIabs: 8918 return Builtin::BIlabs; 8919 case Builtin::BIlabs: 8920 return Builtin::BIllabs; 8921 case Builtin::BIllabs: 8922 return 0; 8923 8924 case Builtin::BIfabsf: 8925 return Builtin::BIfabs; 8926 case Builtin::BIfabs: 8927 return Builtin::BIfabsl; 8928 case Builtin::BIfabsl: 8929 return 0; 8930 8931 case Builtin::BIcabsf: 8932 return Builtin::BIcabs; 8933 case Builtin::BIcabs: 8934 return Builtin::BIcabsl; 8935 case Builtin::BIcabsl: 8936 return 0; 8937 } 8938 } 8939 8940 // Returns the argument type of the absolute value function. 8941 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8942 unsigned AbsType) { 8943 if (AbsType == 0) 8944 return QualType(); 8945 8946 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8947 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8948 if (Error != ASTContext::GE_None) 8949 return QualType(); 8950 8951 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8952 if (!FT) 8953 return QualType(); 8954 8955 if (FT->getNumParams() != 1) 8956 return QualType(); 8957 8958 return FT->getParamType(0); 8959 } 8960 8961 // Returns the best absolute value function, or zero, based on type and 8962 // current absolute value function. 8963 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8964 unsigned AbsFunctionKind) { 8965 unsigned BestKind = 0; 8966 uint64_t ArgSize = Context.getTypeSize(ArgType); 8967 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8968 Kind = getLargerAbsoluteValueFunction(Kind)) { 8969 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8970 if (Context.getTypeSize(ParamType) >= ArgSize) { 8971 if (BestKind == 0) 8972 BestKind = Kind; 8973 else if (Context.hasSameType(ParamType, ArgType)) { 8974 BestKind = Kind; 8975 break; 8976 } 8977 } 8978 } 8979 return BestKind; 8980 } 8981 8982 enum AbsoluteValueKind { 8983 AVK_Integer, 8984 AVK_Floating, 8985 AVK_Complex 8986 }; 8987 8988 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8989 if (T->isIntegralOrEnumerationType()) 8990 return AVK_Integer; 8991 if (T->isRealFloatingType()) 8992 return AVK_Floating; 8993 if (T->isAnyComplexType()) 8994 return AVK_Complex; 8995 8996 llvm_unreachable("Type not integer, floating, or complex"); 8997 } 8998 8999 // Changes the absolute value function to a different type. Preserves whether 9000 // the function is a builtin. 9001 static unsigned changeAbsFunction(unsigned AbsKind, 9002 AbsoluteValueKind ValueKind) { 9003 switch (ValueKind) { 9004 case AVK_Integer: 9005 switch (AbsKind) { 9006 default: 9007 return 0; 9008 case Builtin::BI__builtin_fabsf: 9009 case Builtin::BI__builtin_fabs: 9010 case Builtin::BI__builtin_fabsl: 9011 case Builtin::BI__builtin_cabsf: 9012 case Builtin::BI__builtin_cabs: 9013 case Builtin::BI__builtin_cabsl: 9014 return Builtin::BI__builtin_abs; 9015 case Builtin::BIfabsf: 9016 case Builtin::BIfabs: 9017 case Builtin::BIfabsl: 9018 case Builtin::BIcabsf: 9019 case Builtin::BIcabs: 9020 case Builtin::BIcabsl: 9021 return Builtin::BIabs; 9022 } 9023 case AVK_Floating: 9024 switch (AbsKind) { 9025 default: 9026 return 0; 9027 case Builtin::BI__builtin_abs: 9028 case Builtin::BI__builtin_labs: 9029 case Builtin::BI__builtin_llabs: 9030 case Builtin::BI__builtin_cabsf: 9031 case Builtin::BI__builtin_cabs: 9032 case Builtin::BI__builtin_cabsl: 9033 return Builtin::BI__builtin_fabsf; 9034 case Builtin::BIabs: 9035 case Builtin::BIlabs: 9036 case Builtin::BIllabs: 9037 case Builtin::BIcabsf: 9038 case Builtin::BIcabs: 9039 case Builtin::BIcabsl: 9040 return Builtin::BIfabsf; 9041 } 9042 case AVK_Complex: 9043 switch (AbsKind) { 9044 default: 9045 return 0; 9046 case Builtin::BI__builtin_abs: 9047 case Builtin::BI__builtin_labs: 9048 case Builtin::BI__builtin_llabs: 9049 case Builtin::BI__builtin_fabsf: 9050 case Builtin::BI__builtin_fabs: 9051 case Builtin::BI__builtin_fabsl: 9052 return Builtin::BI__builtin_cabsf; 9053 case Builtin::BIabs: 9054 case Builtin::BIlabs: 9055 case Builtin::BIllabs: 9056 case Builtin::BIfabsf: 9057 case Builtin::BIfabs: 9058 case Builtin::BIfabsl: 9059 return Builtin::BIcabsf; 9060 } 9061 } 9062 llvm_unreachable("Unable to convert function"); 9063 } 9064 9065 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9066 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9067 if (!FnInfo) 9068 return 0; 9069 9070 switch (FDecl->getBuiltinID()) { 9071 default: 9072 return 0; 9073 case Builtin::BI__builtin_abs: 9074 case Builtin::BI__builtin_fabs: 9075 case Builtin::BI__builtin_fabsf: 9076 case Builtin::BI__builtin_fabsl: 9077 case Builtin::BI__builtin_labs: 9078 case Builtin::BI__builtin_llabs: 9079 case Builtin::BI__builtin_cabs: 9080 case Builtin::BI__builtin_cabsf: 9081 case Builtin::BI__builtin_cabsl: 9082 case Builtin::BIabs: 9083 case Builtin::BIlabs: 9084 case Builtin::BIllabs: 9085 case Builtin::BIfabs: 9086 case Builtin::BIfabsf: 9087 case Builtin::BIfabsl: 9088 case Builtin::BIcabs: 9089 case Builtin::BIcabsf: 9090 case Builtin::BIcabsl: 9091 return FDecl->getBuiltinID(); 9092 } 9093 llvm_unreachable("Unknown Builtin type"); 9094 } 9095 9096 // If the replacement is valid, emit a note with replacement function. 9097 // Additionally, suggest including the proper header if not already included. 9098 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9099 unsigned AbsKind, QualType ArgType) { 9100 bool EmitHeaderHint = true; 9101 const char *HeaderName = nullptr; 9102 const char *FunctionName = nullptr; 9103 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9104 FunctionName = "std::abs"; 9105 if (ArgType->isIntegralOrEnumerationType()) { 9106 HeaderName = "cstdlib"; 9107 } else if (ArgType->isRealFloatingType()) { 9108 HeaderName = "cmath"; 9109 } else { 9110 llvm_unreachable("Invalid Type"); 9111 } 9112 9113 // Lookup all std::abs 9114 if (NamespaceDecl *Std = S.getStdNamespace()) { 9115 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9116 R.suppressDiagnostics(); 9117 S.LookupQualifiedName(R, Std); 9118 9119 for (const auto *I : R) { 9120 const FunctionDecl *FDecl = nullptr; 9121 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9122 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9123 } else { 9124 FDecl = dyn_cast<FunctionDecl>(I); 9125 } 9126 if (!FDecl) 9127 continue; 9128 9129 // Found std::abs(), check that they are the right ones. 9130 if (FDecl->getNumParams() != 1) 9131 continue; 9132 9133 // Check that the parameter type can handle the argument. 9134 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9135 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9136 S.Context.getTypeSize(ArgType) <= 9137 S.Context.getTypeSize(ParamType)) { 9138 // Found a function, don't need the header hint. 9139 EmitHeaderHint = false; 9140 break; 9141 } 9142 } 9143 } 9144 } else { 9145 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9146 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9147 9148 if (HeaderName) { 9149 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9150 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9151 R.suppressDiagnostics(); 9152 S.LookupName(R, S.getCurScope()); 9153 9154 if (R.isSingleResult()) { 9155 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9156 if (FD && FD->getBuiltinID() == AbsKind) { 9157 EmitHeaderHint = false; 9158 } else { 9159 return; 9160 } 9161 } else if (!R.empty()) { 9162 return; 9163 } 9164 } 9165 } 9166 9167 S.Diag(Loc, diag::note_replace_abs_function) 9168 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9169 9170 if (!HeaderName) 9171 return; 9172 9173 if (!EmitHeaderHint) 9174 return; 9175 9176 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9177 << FunctionName; 9178 } 9179 9180 template <std::size_t StrLen> 9181 static bool IsStdFunction(const FunctionDecl *FDecl, 9182 const char (&Str)[StrLen]) { 9183 if (!FDecl) 9184 return false; 9185 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9186 return false; 9187 if (!FDecl->isInStdNamespace()) 9188 return false; 9189 9190 return true; 9191 } 9192 9193 // Warn when using the wrong abs() function. 9194 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9195 const FunctionDecl *FDecl) { 9196 if (Call->getNumArgs() != 1) 9197 return; 9198 9199 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9200 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9201 if (AbsKind == 0 && !IsStdAbs) 9202 return; 9203 9204 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9205 QualType ParamType = Call->getArg(0)->getType(); 9206 9207 // Unsigned types cannot be negative. Suggest removing the absolute value 9208 // function call. 9209 if (ArgType->isUnsignedIntegerType()) { 9210 const char *FunctionName = 9211 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9212 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9213 Diag(Call->getExprLoc(), diag::note_remove_abs) 9214 << FunctionName 9215 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9216 return; 9217 } 9218 9219 // Taking the absolute value of a pointer is very suspicious, they probably 9220 // wanted to index into an array, dereference a pointer, call a function, etc. 9221 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9222 unsigned DiagType = 0; 9223 if (ArgType->isFunctionType()) 9224 DiagType = 1; 9225 else if (ArgType->isArrayType()) 9226 DiagType = 2; 9227 9228 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9229 return; 9230 } 9231 9232 // std::abs has overloads which prevent most of the absolute value problems 9233 // from occurring. 9234 if (IsStdAbs) 9235 return; 9236 9237 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9238 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9239 9240 // The argument and parameter are the same kind. Check if they are the right 9241 // size. 9242 if (ArgValueKind == ParamValueKind) { 9243 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9244 return; 9245 9246 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9247 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9248 << FDecl << ArgType << ParamType; 9249 9250 if (NewAbsKind == 0) 9251 return; 9252 9253 emitReplacement(*this, Call->getExprLoc(), 9254 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9255 return; 9256 } 9257 9258 // ArgValueKind != ParamValueKind 9259 // The wrong type of absolute value function was used. Attempt to find the 9260 // proper one. 9261 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9262 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9263 if (NewAbsKind == 0) 9264 return; 9265 9266 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9267 << FDecl << ParamValueKind << ArgValueKind; 9268 9269 emitReplacement(*this, Call->getExprLoc(), 9270 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9271 } 9272 9273 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9274 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9275 const FunctionDecl *FDecl) { 9276 if (!Call || !FDecl) return; 9277 9278 // Ignore template specializations and macros. 9279 if (inTemplateInstantiation()) return; 9280 if (Call->getExprLoc().isMacroID()) return; 9281 9282 // Only care about the one template argument, two function parameter std::max 9283 if (Call->getNumArgs() != 2) return; 9284 if (!IsStdFunction(FDecl, "max")) return; 9285 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9286 if (!ArgList) return; 9287 if (ArgList->size() != 1) return; 9288 9289 // Check that template type argument is unsigned integer. 9290 const auto& TA = ArgList->get(0); 9291 if (TA.getKind() != TemplateArgument::Type) return; 9292 QualType ArgType = TA.getAsType(); 9293 if (!ArgType->isUnsignedIntegerType()) return; 9294 9295 // See if either argument is a literal zero. 9296 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9297 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9298 if (!MTE) return false; 9299 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9300 if (!Num) return false; 9301 if (Num->getValue() != 0) return false; 9302 return true; 9303 }; 9304 9305 const Expr *FirstArg = Call->getArg(0); 9306 const Expr *SecondArg = Call->getArg(1); 9307 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9308 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9309 9310 // Only warn when exactly one argument is zero. 9311 if (IsFirstArgZero == IsSecondArgZero) return; 9312 9313 SourceRange FirstRange = FirstArg->getSourceRange(); 9314 SourceRange SecondRange = SecondArg->getSourceRange(); 9315 9316 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9317 9318 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9319 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9320 9321 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9322 SourceRange RemovalRange; 9323 if (IsFirstArgZero) { 9324 RemovalRange = SourceRange(FirstRange.getBegin(), 9325 SecondRange.getBegin().getLocWithOffset(-1)); 9326 } else { 9327 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9328 SecondRange.getEnd()); 9329 } 9330 9331 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9332 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9333 << FixItHint::CreateRemoval(RemovalRange); 9334 } 9335 9336 //===--- CHECK: Standard memory functions ---------------------------------===// 9337 9338 /// Takes the expression passed to the size_t parameter of functions 9339 /// such as memcmp, strncat, etc and warns if it's a comparison. 9340 /// 9341 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9342 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9343 IdentifierInfo *FnName, 9344 SourceLocation FnLoc, 9345 SourceLocation RParenLoc) { 9346 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9347 if (!Size) 9348 return false; 9349 9350 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9351 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9352 return false; 9353 9354 SourceRange SizeRange = Size->getSourceRange(); 9355 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9356 << SizeRange << FnName; 9357 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9358 << FnName 9359 << FixItHint::CreateInsertion( 9360 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9361 << FixItHint::CreateRemoval(RParenLoc); 9362 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9363 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9364 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9365 ")"); 9366 9367 return true; 9368 } 9369 9370 /// Determine whether the given type is or contains a dynamic class type 9371 /// (e.g., whether it has a vtable). 9372 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9373 bool &IsContained) { 9374 // Look through array types while ignoring qualifiers. 9375 const Type *Ty = T->getBaseElementTypeUnsafe(); 9376 IsContained = false; 9377 9378 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9379 RD = RD ? RD->getDefinition() : nullptr; 9380 if (!RD || RD->isInvalidDecl()) 9381 return nullptr; 9382 9383 if (RD->isDynamicClass()) 9384 return RD; 9385 9386 // Check all the fields. If any bases were dynamic, the class is dynamic. 9387 // It's impossible for a class to transitively contain itself by value, so 9388 // infinite recursion is impossible. 9389 for (auto *FD : RD->fields()) { 9390 bool SubContained; 9391 if (const CXXRecordDecl *ContainedRD = 9392 getContainedDynamicClass(FD->getType(), SubContained)) { 9393 IsContained = true; 9394 return ContainedRD; 9395 } 9396 } 9397 9398 return nullptr; 9399 } 9400 9401 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9402 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9403 if (Unary->getKind() == UETT_SizeOf) 9404 return Unary; 9405 return nullptr; 9406 } 9407 9408 /// If E is a sizeof expression, returns its argument expression, 9409 /// otherwise returns NULL. 9410 static const Expr *getSizeOfExprArg(const Expr *E) { 9411 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9412 if (!SizeOf->isArgumentType()) 9413 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9414 return nullptr; 9415 } 9416 9417 /// If E is a sizeof expression, returns its argument type. 9418 static QualType getSizeOfArgType(const Expr *E) { 9419 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9420 return SizeOf->getTypeOfArgument(); 9421 return QualType(); 9422 } 9423 9424 namespace { 9425 9426 struct SearchNonTrivialToInitializeField 9427 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9428 using Super = 9429 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9430 9431 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9432 9433 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9434 SourceLocation SL) { 9435 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9436 asDerived().visitArray(PDIK, AT, SL); 9437 return; 9438 } 9439 9440 Super::visitWithKind(PDIK, FT, SL); 9441 } 9442 9443 void visitARCStrong(QualType FT, SourceLocation SL) { 9444 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9445 } 9446 void visitARCWeak(QualType FT, SourceLocation SL) { 9447 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9448 } 9449 void visitStruct(QualType FT, SourceLocation SL) { 9450 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9451 visit(FD->getType(), FD->getLocation()); 9452 } 9453 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9454 const ArrayType *AT, SourceLocation SL) { 9455 visit(getContext().getBaseElementType(AT), SL); 9456 } 9457 void visitTrivial(QualType FT, SourceLocation SL) {} 9458 9459 static void diag(QualType RT, const Expr *E, Sema &S) { 9460 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9461 } 9462 9463 ASTContext &getContext() { return S.getASTContext(); } 9464 9465 const Expr *E; 9466 Sema &S; 9467 }; 9468 9469 struct SearchNonTrivialToCopyField 9470 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9471 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9472 9473 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9474 9475 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9476 SourceLocation SL) { 9477 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9478 asDerived().visitArray(PCK, AT, SL); 9479 return; 9480 } 9481 9482 Super::visitWithKind(PCK, FT, SL); 9483 } 9484 9485 void visitARCStrong(QualType FT, SourceLocation SL) { 9486 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9487 } 9488 void visitARCWeak(QualType FT, SourceLocation SL) { 9489 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9490 } 9491 void visitStruct(QualType FT, SourceLocation SL) { 9492 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9493 visit(FD->getType(), FD->getLocation()); 9494 } 9495 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9496 SourceLocation SL) { 9497 visit(getContext().getBaseElementType(AT), SL); 9498 } 9499 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9500 SourceLocation SL) {} 9501 void visitTrivial(QualType FT, SourceLocation SL) {} 9502 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9503 9504 static void diag(QualType RT, const Expr *E, Sema &S) { 9505 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9506 } 9507 9508 ASTContext &getContext() { return S.getASTContext(); } 9509 9510 const Expr *E; 9511 Sema &S; 9512 }; 9513 9514 } 9515 9516 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9517 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9518 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9519 9520 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9521 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9522 return false; 9523 9524 return doesExprLikelyComputeSize(BO->getLHS()) || 9525 doesExprLikelyComputeSize(BO->getRHS()); 9526 } 9527 9528 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9529 } 9530 9531 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9532 /// 9533 /// \code 9534 /// #define MACRO 0 9535 /// foo(MACRO); 9536 /// foo(0); 9537 /// \endcode 9538 /// 9539 /// This should return true for the first call to foo, but not for the second 9540 /// (regardless of whether foo is a macro or function). 9541 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9542 SourceLocation CallLoc, 9543 SourceLocation ArgLoc) { 9544 if (!CallLoc.isMacroID()) 9545 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9546 9547 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9548 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9549 } 9550 9551 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9552 /// last two arguments transposed. 9553 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9554 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9555 return; 9556 9557 const Expr *SizeArg = 9558 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9559 9560 auto isLiteralZero = [](const Expr *E) { 9561 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9562 }; 9563 9564 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9565 SourceLocation CallLoc = Call->getRParenLoc(); 9566 SourceManager &SM = S.getSourceManager(); 9567 if (isLiteralZero(SizeArg) && 9568 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9569 9570 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9571 9572 // Some platforms #define bzero to __builtin_memset. See if this is the 9573 // case, and if so, emit a better diagnostic. 9574 if (BId == Builtin::BIbzero || 9575 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9576 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9577 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9578 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9579 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9580 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9581 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9582 } 9583 return; 9584 } 9585 9586 // If the second argument to a memset is a sizeof expression and the third 9587 // isn't, this is also likely an error. This should catch 9588 // 'memset(buf, sizeof(buf), 0xff)'. 9589 if (BId == Builtin::BImemset && 9590 doesExprLikelyComputeSize(Call->getArg(1)) && 9591 !doesExprLikelyComputeSize(Call->getArg(2))) { 9592 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9593 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9594 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9595 return; 9596 } 9597 } 9598 9599 /// Check for dangerous or invalid arguments to memset(). 9600 /// 9601 /// This issues warnings on known problematic, dangerous or unspecified 9602 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9603 /// function calls. 9604 /// 9605 /// \param Call The call expression to diagnose. 9606 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9607 unsigned BId, 9608 IdentifierInfo *FnName) { 9609 assert(BId != 0); 9610 9611 // It is possible to have a non-standard definition of memset. Validate 9612 // we have enough arguments, and if not, abort further checking. 9613 unsigned ExpectedNumArgs = 9614 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9615 if (Call->getNumArgs() < ExpectedNumArgs) 9616 return; 9617 9618 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9619 BId == Builtin::BIstrndup ? 1 : 2); 9620 unsigned LenArg = 9621 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9622 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9623 9624 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9625 Call->getBeginLoc(), Call->getRParenLoc())) 9626 return; 9627 9628 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9629 CheckMemaccessSize(*this, BId, Call); 9630 9631 // We have special checking when the length is a sizeof expression. 9632 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9633 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9634 llvm::FoldingSetNodeID SizeOfArgID; 9635 9636 // Although widely used, 'bzero' is not a standard function. Be more strict 9637 // with the argument types before allowing diagnostics and only allow the 9638 // form bzero(ptr, sizeof(...)). 9639 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9640 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9641 return; 9642 9643 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9644 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9645 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9646 9647 QualType DestTy = Dest->getType(); 9648 QualType PointeeTy; 9649 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9650 PointeeTy = DestPtrTy->getPointeeType(); 9651 9652 // Never warn about void type pointers. This can be used to suppress 9653 // false positives. 9654 if (PointeeTy->isVoidType()) 9655 continue; 9656 9657 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9658 // actually comparing the expressions for equality. Because computing the 9659 // expression IDs can be expensive, we only do this if the diagnostic is 9660 // enabled. 9661 if (SizeOfArg && 9662 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9663 SizeOfArg->getExprLoc())) { 9664 // We only compute IDs for expressions if the warning is enabled, and 9665 // cache the sizeof arg's ID. 9666 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9667 SizeOfArg->Profile(SizeOfArgID, Context, true); 9668 llvm::FoldingSetNodeID DestID; 9669 Dest->Profile(DestID, Context, true); 9670 if (DestID == SizeOfArgID) { 9671 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9672 // over sizeof(src) as well. 9673 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9674 StringRef ReadableName = FnName->getName(); 9675 9676 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9677 if (UnaryOp->getOpcode() == UO_AddrOf) 9678 ActionIdx = 1; // If its an address-of operator, just remove it. 9679 if (!PointeeTy->isIncompleteType() && 9680 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9681 ActionIdx = 2; // If the pointee's size is sizeof(char), 9682 // suggest an explicit length. 9683 9684 // If the function is defined as a builtin macro, do not show macro 9685 // expansion. 9686 SourceLocation SL = SizeOfArg->getExprLoc(); 9687 SourceRange DSR = Dest->getSourceRange(); 9688 SourceRange SSR = SizeOfArg->getSourceRange(); 9689 SourceManager &SM = getSourceManager(); 9690 9691 if (SM.isMacroArgExpansion(SL)) { 9692 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9693 SL = SM.getSpellingLoc(SL); 9694 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9695 SM.getSpellingLoc(DSR.getEnd())); 9696 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9697 SM.getSpellingLoc(SSR.getEnd())); 9698 } 9699 9700 DiagRuntimeBehavior(SL, SizeOfArg, 9701 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9702 << ReadableName 9703 << PointeeTy 9704 << DestTy 9705 << DSR 9706 << SSR); 9707 DiagRuntimeBehavior(SL, SizeOfArg, 9708 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9709 << ActionIdx 9710 << SSR); 9711 9712 break; 9713 } 9714 } 9715 9716 // Also check for cases where the sizeof argument is the exact same 9717 // type as the memory argument, and where it points to a user-defined 9718 // record type. 9719 if (SizeOfArgTy != QualType()) { 9720 if (PointeeTy->isRecordType() && 9721 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9722 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9723 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9724 << FnName << SizeOfArgTy << ArgIdx 9725 << PointeeTy << Dest->getSourceRange() 9726 << LenExpr->getSourceRange()); 9727 break; 9728 } 9729 } 9730 } else if (DestTy->isArrayType()) { 9731 PointeeTy = DestTy; 9732 } 9733 9734 if (PointeeTy == QualType()) 9735 continue; 9736 9737 // Always complain about dynamic classes. 9738 bool IsContained; 9739 if (const CXXRecordDecl *ContainedRD = 9740 getContainedDynamicClass(PointeeTy, IsContained)) { 9741 9742 unsigned OperationType = 0; 9743 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9744 // "overwritten" if we're warning about the destination for any call 9745 // but memcmp; otherwise a verb appropriate to the call. 9746 if (ArgIdx != 0 || IsCmp) { 9747 if (BId == Builtin::BImemcpy) 9748 OperationType = 1; 9749 else if(BId == Builtin::BImemmove) 9750 OperationType = 2; 9751 else if (IsCmp) 9752 OperationType = 3; 9753 } 9754 9755 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9756 PDiag(diag::warn_dyn_class_memaccess) 9757 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9758 << IsContained << ContainedRD << OperationType 9759 << Call->getCallee()->getSourceRange()); 9760 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9761 BId != Builtin::BImemset) 9762 DiagRuntimeBehavior( 9763 Dest->getExprLoc(), Dest, 9764 PDiag(diag::warn_arc_object_memaccess) 9765 << ArgIdx << FnName << PointeeTy 9766 << Call->getCallee()->getSourceRange()); 9767 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9768 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9769 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9770 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9771 PDiag(diag::warn_cstruct_memaccess) 9772 << ArgIdx << FnName << PointeeTy << 0); 9773 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9774 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9775 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9776 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9777 PDiag(diag::warn_cstruct_memaccess) 9778 << ArgIdx << FnName << PointeeTy << 1); 9779 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9780 } else { 9781 continue; 9782 } 9783 } else 9784 continue; 9785 9786 DiagRuntimeBehavior( 9787 Dest->getExprLoc(), Dest, 9788 PDiag(diag::note_bad_memaccess_silence) 9789 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9790 break; 9791 } 9792 } 9793 9794 // A little helper routine: ignore addition and subtraction of integer literals. 9795 // This intentionally does not ignore all integer constant expressions because 9796 // we don't want to remove sizeof(). 9797 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9798 Ex = Ex->IgnoreParenCasts(); 9799 9800 while (true) { 9801 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9802 if (!BO || !BO->isAdditiveOp()) 9803 break; 9804 9805 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9806 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9807 9808 if (isa<IntegerLiteral>(RHS)) 9809 Ex = LHS; 9810 else if (isa<IntegerLiteral>(LHS)) 9811 Ex = RHS; 9812 else 9813 break; 9814 } 9815 9816 return Ex; 9817 } 9818 9819 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9820 ASTContext &Context) { 9821 // Only handle constant-sized or VLAs, but not flexible members. 9822 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9823 // Only issue the FIXIT for arrays of size > 1. 9824 if (CAT->getSize().getSExtValue() <= 1) 9825 return false; 9826 } else if (!Ty->isVariableArrayType()) { 9827 return false; 9828 } 9829 return true; 9830 } 9831 9832 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9833 // be the size of the source, instead of the destination. 9834 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9835 IdentifierInfo *FnName) { 9836 9837 // Don't crash if the user has the wrong number of arguments 9838 unsigned NumArgs = Call->getNumArgs(); 9839 if ((NumArgs != 3) && (NumArgs != 4)) 9840 return; 9841 9842 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9843 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9844 const Expr *CompareWithSrc = nullptr; 9845 9846 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9847 Call->getBeginLoc(), Call->getRParenLoc())) 9848 return; 9849 9850 // Look for 'strlcpy(dst, x, sizeof(x))' 9851 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9852 CompareWithSrc = Ex; 9853 else { 9854 // Look for 'strlcpy(dst, x, strlen(x))' 9855 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9856 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9857 SizeCall->getNumArgs() == 1) 9858 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9859 } 9860 } 9861 9862 if (!CompareWithSrc) 9863 return; 9864 9865 // Determine if the argument to sizeof/strlen is equal to the source 9866 // argument. In principle there's all kinds of things you could do 9867 // here, for instance creating an == expression and evaluating it with 9868 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9869 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9870 if (!SrcArgDRE) 9871 return; 9872 9873 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9874 if (!CompareWithSrcDRE || 9875 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9876 return; 9877 9878 const Expr *OriginalSizeArg = Call->getArg(2); 9879 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9880 << OriginalSizeArg->getSourceRange() << FnName; 9881 9882 // Output a FIXIT hint if the destination is an array (rather than a 9883 // pointer to an array). This could be enhanced to handle some 9884 // pointers if we know the actual size, like if DstArg is 'array+2' 9885 // we could say 'sizeof(array)-2'. 9886 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9887 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9888 return; 9889 9890 SmallString<128> sizeString; 9891 llvm::raw_svector_ostream OS(sizeString); 9892 OS << "sizeof("; 9893 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9894 OS << ")"; 9895 9896 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9897 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9898 OS.str()); 9899 } 9900 9901 /// Check if two expressions refer to the same declaration. 9902 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9903 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9904 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9905 return D1->getDecl() == D2->getDecl(); 9906 return false; 9907 } 9908 9909 static const Expr *getStrlenExprArg(const Expr *E) { 9910 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9911 const FunctionDecl *FD = CE->getDirectCallee(); 9912 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9913 return nullptr; 9914 return CE->getArg(0)->IgnoreParenCasts(); 9915 } 9916 return nullptr; 9917 } 9918 9919 // Warn on anti-patterns as the 'size' argument to strncat. 9920 // The correct size argument should look like following: 9921 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9922 void Sema::CheckStrncatArguments(const CallExpr *CE, 9923 IdentifierInfo *FnName) { 9924 // Don't crash if the user has the wrong number of arguments. 9925 if (CE->getNumArgs() < 3) 9926 return; 9927 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9928 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9929 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9930 9931 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9932 CE->getRParenLoc())) 9933 return; 9934 9935 // Identify common expressions, which are wrongly used as the size argument 9936 // to strncat and may lead to buffer overflows. 9937 unsigned PatternType = 0; 9938 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9939 // - sizeof(dst) 9940 if (referToTheSameDecl(SizeOfArg, DstArg)) 9941 PatternType = 1; 9942 // - sizeof(src) 9943 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9944 PatternType = 2; 9945 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9946 if (BE->getOpcode() == BO_Sub) { 9947 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9948 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9949 // - sizeof(dst) - strlen(dst) 9950 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9951 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9952 PatternType = 1; 9953 // - sizeof(src) - (anything) 9954 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9955 PatternType = 2; 9956 } 9957 } 9958 9959 if (PatternType == 0) 9960 return; 9961 9962 // Generate the diagnostic. 9963 SourceLocation SL = LenArg->getBeginLoc(); 9964 SourceRange SR = LenArg->getSourceRange(); 9965 SourceManager &SM = getSourceManager(); 9966 9967 // If the function is defined as a builtin macro, do not show macro expansion. 9968 if (SM.isMacroArgExpansion(SL)) { 9969 SL = SM.getSpellingLoc(SL); 9970 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9971 SM.getSpellingLoc(SR.getEnd())); 9972 } 9973 9974 // Check if the destination is an array (rather than a pointer to an array). 9975 QualType DstTy = DstArg->getType(); 9976 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9977 Context); 9978 if (!isKnownSizeArray) { 9979 if (PatternType == 1) 9980 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9981 else 9982 Diag(SL, diag::warn_strncat_src_size) << SR; 9983 return; 9984 } 9985 9986 if (PatternType == 1) 9987 Diag(SL, diag::warn_strncat_large_size) << SR; 9988 else 9989 Diag(SL, diag::warn_strncat_src_size) << SR; 9990 9991 SmallString<128> sizeString; 9992 llvm::raw_svector_ostream OS(sizeString); 9993 OS << "sizeof("; 9994 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9995 OS << ") - "; 9996 OS << "strlen("; 9997 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9998 OS << ") - 1"; 9999 10000 Diag(SL, diag::note_strncat_wrong_size) 10001 << FixItHint::CreateReplacement(SR, OS.str()); 10002 } 10003 10004 void 10005 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10006 SourceLocation ReturnLoc, 10007 bool isObjCMethod, 10008 const AttrVec *Attrs, 10009 const FunctionDecl *FD) { 10010 // Check if the return value is null but should not be. 10011 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10012 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10013 CheckNonNullExpr(*this, RetValExp)) 10014 Diag(ReturnLoc, diag::warn_null_ret) 10015 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10016 10017 // C++11 [basic.stc.dynamic.allocation]p4: 10018 // If an allocation function declared with a non-throwing 10019 // exception-specification fails to allocate storage, it shall return 10020 // a null pointer. Any other allocation function that fails to allocate 10021 // storage shall indicate failure only by throwing an exception [...] 10022 if (FD) { 10023 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10024 if (Op == OO_New || Op == OO_Array_New) { 10025 const FunctionProtoType *Proto 10026 = FD->getType()->castAs<FunctionProtoType>(); 10027 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10028 CheckNonNullExpr(*this, RetValExp)) 10029 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10030 << FD << getLangOpts().CPlusPlus11; 10031 } 10032 } 10033 } 10034 10035 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10036 10037 /// Check for comparisons of floating point operands using != and ==. 10038 /// Issue a warning if these are no self-comparisons, as they are not likely 10039 /// to do what the programmer intended. 10040 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10041 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10042 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10043 10044 // Special case: check for x == x (which is OK). 10045 // Do not emit warnings for such cases. 10046 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10047 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10048 if (DRL->getDecl() == DRR->getDecl()) 10049 return; 10050 10051 // Special case: check for comparisons against literals that can be exactly 10052 // represented by APFloat. In such cases, do not emit a warning. This 10053 // is a heuristic: often comparison against such literals are used to 10054 // detect if a value in a variable has not changed. This clearly can 10055 // lead to false negatives. 10056 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10057 if (FLL->isExact()) 10058 return; 10059 } else 10060 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10061 if (FLR->isExact()) 10062 return; 10063 10064 // Check for comparisons with builtin types. 10065 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10066 if (CL->getBuiltinCallee()) 10067 return; 10068 10069 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10070 if (CR->getBuiltinCallee()) 10071 return; 10072 10073 // Emit the diagnostic. 10074 Diag(Loc, diag::warn_floatingpoint_eq) 10075 << LHS->getSourceRange() << RHS->getSourceRange(); 10076 } 10077 10078 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10079 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10080 10081 namespace { 10082 10083 /// Structure recording the 'active' range of an integer-valued 10084 /// expression. 10085 struct IntRange { 10086 /// The number of bits active in the int. 10087 unsigned Width; 10088 10089 /// True if the int is known not to have negative values. 10090 bool NonNegative; 10091 10092 IntRange(unsigned Width, bool NonNegative) 10093 : Width(Width), NonNegative(NonNegative) {} 10094 10095 /// Returns the range of the bool type. 10096 static IntRange forBoolType() { 10097 return IntRange(1, true); 10098 } 10099 10100 /// Returns the range of an opaque value of the given integral type. 10101 static IntRange forValueOfType(ASTContext &C, QualType T) { 10102 return forValueOfCanonicalType(C, 10103 T->getCanonicalTypeInternal().getTypePtr()); 10104 } 10105 10106 /// Returns the range of an opaque value of a canonical integral type. 10107 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10108 assert(T->isCanonicalUnqualified()); 10109 10110 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10111 T = VT->getElementType().getTypePtr(); 10112 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10113 T = CT->getElementType().getTypePtr(); 10114 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10115 T = AT->getValueType().getTypePtr(); 10116 10117 if (!C.getLangOpts().CPlusPlus) { 10118 // For enum types in C code, use the underlying datatype. 10119 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10120 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10121 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10122 // For enum types in C++, use the known bit width of the enumerators. 10123 EnumDecl *Enum = ET->getDecl(); 10124 // In C++11, enums can have a fixed underlying type. Use this type to 10125 // compute the range. 10126 if (Enum->isFixed()) { 10127 return IntRange(C.getIntWidth(QualType(T, 0)), 10128 !ET->isSignedIntegerOrEnumerationType()); 10129 } 10130 10131 unsigned NumPositive = Enum->getNumPositiveBits(); 10132 unsigned NumNegative = Enum->getNumNegativeBits(); 10133 10134 if (NumNegative == 0) 10135 return IntRange(NumPositive, true/*NonNegative*/); 10136 else 10137 return IntRange(std::max(NumPositive + 1, NumNegative), 10138 false/*NonNegative*/); 10139 } 10140 10141 const BuiltinType *BT = cast<BuiltinType>(T); 10142 assert(BT->isInteger()); 10143 10144 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10145 } 10146 10147 /// Returns the "target" range of a canonical integral type, i.e. 10148 /// the range of values expressible in the type. 10149 /// 10150 /// This matches forValueOfCanonicalType except that enums have the 10151 /// full range of their type, not the range of their enumerators. 10152 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10153 assert(T->isCanonicalUnqualified()); 10154 10155 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10156 T = VT->getElementType().getTypePtr(); 10157 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10158 T = CT->getElementType().getTypePtr(); 10159 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10160 T = AT->getValueType().getTypePtr(); 10161 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10162 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10163 10164 const BuiltinType *BT = cast<BuiltinType>(T); 10165 assert(BT->isInteger()); 10166 10167 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10168 } 10169 10170 /// Returns the supremum of two ranges: i.e. their conservative merge. 10171 static IntRange join(IntRange L, IntRange R) { 10172 return IntRange(std::max(L.Width, R.Width), 10173 L.NonNegative && R.NonNegative); 10174 } 10175 10176 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10177 static IntRange meet(IntRange L, IntRange R) { 10178 return IntRange(std::min(L.Width, R.Width), 10179 L.NonNegative || R.NonNegative); 10180 } 10181 }; 10182 10183 } // namespace 10184 10185 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10186 unsigned MaxWidth) { 10187 if (value.isSigned() && value.isNegative()) 10188 return IntRange(value.getMinSignedBits(), false); 10189 10190 if (value.getBitWidth() > MaxWidth) 10191 value = value.trunc(MaxWidth); 10192 10193 // isNonNegative() just checks the sign bit without considering 10194 // signedness. 10195 return IntRange(value.getActiveBits(), true); 10196 } 10197 10198 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10199 unsigned MaxWidth) { 10200 if (result.isInt()) 10201 return GetValueRange(C, result.getInt(), MaxWidth); 10202 10203 if (result.isVector()) { 10204 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10205 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10206 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10207 R = IntRange::join(R, El); 10208 } 10209 return R; 10210 } 10211 10212 if (result.isComplexInt()) { 10213 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10214 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10215 return IntRange::join(R, I); 10216 } 10217 10218 // This can happen with lossless casts to intptr_t of "based" lvalues. 10219 // Assume it might use arbitrary bits. 10220 // FIXME: The only reason we need to pass the type in here is to get 10221 // the sign right on this one case. It would be nice if APValue 10222 // preserved this. 10223 assert(result.isLValue() || result.isAddrLabelDiff()); 10224 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10225 } 10226 10227 static QualType GetExprType(const Expr *E) { 10228 QualType Ty = E->getType(); 10229 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10230 Ty = AtomicRHS->getValueType(); 10231 return Ty; 10232 } 10233 10234 /// Pseudo-evaluate the given integer expression, estimating the 10235 /// range of values it might take. 10236 /// 10237 /// \param MaxWidth - the width to which the value will be truncated 10238 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10239 bool InConstantContext) { 10240 E = E->IgnoreParens(); 10241 10242 // Try a full evaluation first. 10243 Expr::EvalResult result; 10244 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10245 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10246 10247 // I think we only want to look through implicit casts here; if the 10248 // user has an explicit widening cast, we should treat the value as 10249 // being of the new, wider type. 10250 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10251 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10252 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10253 10254 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10255 10256 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10257 CE->getCastKind() == CK_BooleanToSignedIntegral; 10258 10259 // Assume that non-integer casts can span the full range of the type. 10260 if (!isIntegerCast) 10261 return OutputTypeRange; 10262 10263 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10264 std::min(MaxWidth, OutputTypeRange.Width), 10265 InConstantContext); 10266 10267 // Bail out if the subexpr's range is as wide as the cast type. 10268 if (SubRange.Width >= OutputTypeRange.Width) 10269 return OutputTypeRange; 10270 10271 // Otherwise, we take the smaller width, and we're non-negative if 10272 // either the output type or the subexpr is. 10273 return IntRange(SubRange.Width, 10274 SubRange.NonNegative || OutputTypeRange.NonNegative); 10275 } 10276 10277 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10278 // If we can fold the condition, just take that operand. 10279 bool CondResult; 10280 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10281 return GetExprRange(C, 10282 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10283 MaxWidth, InConstantContext); 10284 10285 // Otherwise, conservatively merge. 10286 IntRange L = 10287 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10288 IntRange R = 10289 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10290 return IntRange::join(L, R); 10291 } 10292 10293 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10294 switch (BO->getOpcode()) { 10295 case BO_Cmp: 10296 llvm_unreachable("builtin <=> should have class type"); 10297 10298 // Boolean-valued operations are single-bit and positive. 10299 case BO_LAnd: 10300 case BO_LOr: 10301 case BO_LT: 10302 case BO_GT: 10303 case BO_LE: 10304 case BO_GE: 10305 case BO_EQ: 10306 case BO_NE: 10307 return IntRange::forBoolType(); 10308 10309 // The type of the assignments is the type of the LHS, so the RHS 10310 // is not necessarily the same type. 10311 case BO_MulAssign: 10312 case BO_DivAssign: 10313 case BO_RemAssign: 10314 case BO_AddAssign: 10315 case BO_SubAssign: 10316 case BO_XorAssign: 10317 case BO_OrAssign: 10318 // TODO: bitfields? 10319 return IntRange::forValueOfType(C, GetExprType(E)); 10320 10321 // Simple assignments just pass through the RHS, which will have 10322 // been coerced to the LHS type. 10323 case BO_Assign: 10324 // TODO: bitfields? 10325 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10326 10327 // Operations with opaque sources are black-listed. 10328 case BO_PtrMemD: 10329 case BO_PtrMemI: 10330 return IntRange::forValueOfType(C, GetExprType(E)); 10331 10332 // Bitwise-and uses the *infinum* of the two source ranges. 10333 case BO_And: 10334 case BO_AndAssign: 10335 return IntRange::meet( 10336 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10337 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10338 10339 // Left shift gets black-listed based on a judgement call. 10340 case BO_Shl: 10341 // ...except that we want to treat '1 << (blah)' as logically 10342 // positive. It's an important idiom. 10343 if (IntegerLiteral *I 10344 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10345 if (I->getValue() == 1) { 10346 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10347 return IntRange(R.Width, /*NonNegative*/ true); 10348 } 10349 } 10350 LLVM_FALLTHROUGH; 10351 10352 case BO_ShlAssign: 10353 return IntRange::forValueOfType(C, GetExprType(E)); 10354 10355 // Right shift by a constant can narrow its left argument. 10356 case BO_Shr: 10357 case BO_ShrAssign: { 10358 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10359 10360 // If the shift amount is a positive constant, drop the width by 10361 // that much. 10362 llvm::APSInt shift; 10363 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10364 shift.isNonNegative()) { 10365 unsigned zext = shift.getZExtValue(); 10366 if (zext >= L.Width) 10367 L.Width = (L.NonNegative ? 0 : 1); 10368 else 10369 L.Width -= zext; 10370 } 10371 10372 return L; 10373 } 10374 10375 // Comma acts as its right operand. 10376 case BO_Comma: 10377 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10378 10379 // Black-list pointer subtractions. 10380 case BO_Sub: 10381 if (BO->getLHS()->getType()->isPointerType()) 10382 return IntRange::forValueOfType(C, GetExprType(E)); 10383 break; 10384 10385 // The width of a division result is mostly determined by the size 10386 // of the LHS. 10387 case BO_Div: { 10388 // Don't 'pre-truncate' the operands. 10389 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10390 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10391 10392 // If the divisor is constant, use that. 10393 llvm::APSInt divisor; 10394 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10395 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10396 if (log2 >= L.Width) 10397 L.Width = (L.NonNegative ? 0 : 1); 10398 else 10399 L.Width = std::min(L.Width - log2, MaxWidth); 10400 return L; 10401 } 10402 10403 // Otherwise, just use the LHS's width. 10404 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10405 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10406 } 10407 10408 // The result of a remainder can't be larger than the result of 10409 // either side. 10410 case BO_Rem: { 10411 // Don't 'pre-truncate' the operands. 10412 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10413 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10414 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10415 10416 IntRange meet = IntRange::meet(L, R); 10417 meet.Width = std::min(meet.Width, MaxWidth); 10418 return meet; 10419 } 10420 10421 // The default behavior is okay for these. 10422 case BO_Mul: 10423 case BO_Add: 10424 case BO_Xor: 10425 case BO_Or: 10426 break; 10427 } 10428 10429 // The default case is to treat the operation as if it were closed 10430 // on the narrowest type that encompasses both operands. 10431 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10432 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10433 return IntRange::join(L, R); 10434 } 10435 10436 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10437 switch (UO->getOpcode()) { 10438 // Boolean-valued operations are white-listed. 10439 case UO_LNot: 10440 return IntRange::forBoolType(); 10441 10442 // Operations with opaque sources are black-listed. 10443 case UO_Deref: 10444 case UO_AddrOf: // should be impossible 10445 return IntRange::forValueOfType(C, GetExprType(E)); 10446 10447 default: 10448 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10449 } 10450 } 10451 10452 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10453 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10454 10455 if (const auto *BitField = E->getSourceBitField()) 10456 return IntRange(BitField->getBitWidthValue(C), 10457 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10458 10459 return IntRange::forValueOfType(C, GetExprType(E)); 10460 } 10461 10462 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10463 bool InConstantContext) { 10464 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10465 } 10466 10467 /// Checks whether the given value, which currently has the given 10468 /// source semantics, has the same value when coerced through the 10469 /// target semantics. 10470 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10471 const llvm::fltSemantics &Src, 10472 const llvm::fltSemantics &Tgt) { 10473 llvm::APFloat truncated = value; 10474 10475 bool ignored; 10476 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10477 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10478 10479 return truncated.bitwiseIsEqual(value); 10480 } 10481 10482 /// Checks whether the given value, which currently has the given 10483 /// source semantics, has the same value when coerced through the 10484 /// target semantics. 10485 /// 10486 /// The value might be a vector of floats (or a complex number). 10487 static bool IsSameFloatAfterCast(const APValue &value, 10488 const llvm::fltSemantics &Src, 10489 const llvm::fltSemantics &Tgt) { 10490 if (value.isFloat()) 10491 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10492 10493 if (value.isVector()) { 10494 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10495 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10496 return false; 10497 return true; 10498 } 10499 10500 assert(value.isComplexFloat()); 10501 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10502 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10503 } 10504 10505 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10506 bool IsListInit = false); 10507 10508 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10509 // Suppress cases where we are comparing against an enum constant. 10510 if (const DeclRefExpr *DR = 10511 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10512 if (isa<EnumConstantDecl>(DR->getDecl())) 10513 return true; 10514 10515 // Suppress cases where the value is expanded from a macro, unless that macro 10516 // is how a language represents a boolean literal. This is the case in both C 10517 // and Objective-C. 10518 SourceLocation BeginLoc = E->getBeginLoc(); 10519 if (BeginLoc.isMacroID()) { 10520 StringRef MacroName = Lexer::getImmediateMacroName( 10521 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10522 return MacroName != "YES" && MacroName != "NO" && 10523 MacroName != "true" && MacroName != "false"; 10524 } 10525 10526 return false; 10527 } 10528 10529 static bool isKnownToHaveUnsignedValue(Expr *E) { 10530 return E->getType()->isIntegerType() && 10531 (!E->getType()->isSignedIntegerType() || 10532 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10533 } 10534 10535 namespace { 10536 /// The promoted range of values of a type. In general this has the 10537 /// following structure: 10538 /// 10539 /// |-----------| . . . |-----------| 10540 /// ^ ^ ^ ^ 10541 /// Min HoleMin HoleMax Max 10542 /// 10543 /// ... where there is only a hole if a signed type is promoted to unsigned 10544 /// (in which case Min and Max are the smallest and largest representable 10545 /// values). 10546 struct PromotedRange { 10547 // Min, or HoleMax if there is a hole. 10548 llvm::APSInt PromotedMin; 10549 // Max, or HoleMin if there is a hole. 10550 llvm::APSInt PromotedMax; 10551 10552 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10553 if (R.Width == 0) 10554 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10555 else if (R.Width >= BitWidth && !Unsigned) { 10556 // Promotion made the type *narrower*. This happens when promoting 10557 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10558 // Treat all values of 'signed int' as being in range for now. 10559 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10560 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10561 } else { 10562 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10563 .extOrTrunc(BitWidth); 10564 PromotedMin.setIsUnsigned(Unsigned); 10565 10566 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10567 .extOrTrunc(BitWidth); 10568 PromotedMax.setIsUnsigned(Unsigned); 10569 } 10570 } 10571 10572 // Determine whether this range is contiguous (has no hole). 10573 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10574 10575 // Where a constant value is within the range. 10576 enum ComparisonResult { 10577 LT = 0x1, 10578 LE = 0x2, 10579 GT = 0x4, 10580 GE = 0x8, 10581 EQ = 0x10, 10582 NE = 0x20, 10583 InRangeFlag = 0x40, 10584 10585 Less = LE | LT | NE, 10586 Min = LE | InRangeFlag, 10587 InRange = InRangeFlag, 10588 Max = GE | InRangeFlag, 10589 Greater = GE | GT | NE, 10590 10591 OnlyValue = LE | GE | EQ | InRangeFlag, 10592 InHole = NE 10593 }; 10594 10595 ComparisonResult compare(const llvm::APSInt &Value) const { 10596 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10597 Value.isUnsigned() == PromotedMin.isUnsigned()); 10598 if (!isContiguous()) { 10599 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10600 if (Value.isMinValue()) return Min; 10601 if (Value.isMaxValue()) return Max; 10602 if (Value >= PromotedMin) return InRange; 10603 if (Value <= PromotedMax) return InRange; 10604 return InHole; 10605 } 10606 10607 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10608 case -1: return Less; 10609 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10610 case 1: 10611 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10612 case -1: return InRange; 10613 case 0: return Max; 10614 case 1: return Greater; 10615 } 10616 } 10617 10618 llvm_unreachable("impossible compare result"); 10619 } 10620 10621 static llvm::Optional<StringRef> 10622 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10623 if (Op == BO_Cmp) { 10624 ComparisonResult LTFlag = LT, GTFlag = GT; 10625 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10626 10627 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10628 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10629 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10630 return llvm::None; 10631 } 10632 10633 ComparisonResult TrueFlag, FalseFlag; 10634 if (Op == BO_EQ) { 10635 TrueFlag = EQ; 10636 FalseFlag = NE; 10637 } else if (Op == BO_NE) { 10638 TrueFlag = NE; 10639 FalseFlag = EQ; 10640 } else { 10641 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10642 TrueFlag = LT; 10643 FalseFlag = GE; 10644 } else { 10645 TrueFlag = GT; 10646 FalseFlag = LE; 10647 } 10648 if (Op == BO_GE || Op == BO_LE) 10649 std::swap(TrueFlag, FalseFlag); 10650 } 10651 if (R & TrueFlag) 10652 return StringRef("true"); 10653 if (R & FalseFlag) 10654 return StringRef("false"); 10655 return llvm::None; 10656 } 10657 }; 10658 } 10659 10660 static bool HasEnumType(Expr *E) { 10661 // Strip off implicit integral promotions. 10662 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10663 if (ICE->getCastKind() != CK_IntegralCast && 10664 ICE->getCastKind() != CK_NoOp) 10665 break; 10666 E = ICE->getSubExpr(); 10667 } 10668 10669 return E->getType()->isEnumeralType(); 10670 } 10671 10672 static int classifyConstantValue(Expr *Constant) { 10673 // The values of this enumeration are used in the diagnostics 10674 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10675 enum ConstantValueKind { 10676 Miscellaneous = 0, 10677 LiteralTrue, 10678 LiteralFalse 10679 }; 10680 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10681 return BL->getValue() ? ConstantValueKind::LiteralTrue 10682 : ConstantValueKind::LiteralFalse; 10683 return ConstantValueKind::Miscellaneous; 10684 } 10685 10686 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10687 Expr *Constant, Expr *Other, 10688 const llvm::APSInt &Value, 10689 bool RhsConstant) { 10690 if (S.inTemplateInstantiation()) 10691 return false; 10692 10693 Expr *OriginalOther = Other; 10694 10695 Constant = Constant->IgnoreParenImpCasts(); 10696 Other = Other->IgnoreParenImpCasts(); 10697 10698 // Suppress warnings on tautological comparisons between values of the same 10699 // enumeration type. There are only two ways we could warn on this: 10700 // - If the constant is outside the range of representable values of 10701 // the enumeration. In such a case, we should warn about the cast 10702 // to enumeration type, not about the comparison. 10703 // - If the constant is the maximum / minimum in-range value. For an 10704 // enumeratin type, such comparisons can be meaningful and useful. 10705 if (Constant->getType()->isEnumeralType() && 10706 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10707 return false; 10708 10709 // TODO: Investigate using GetExprRange() to get tighter bounds 10710 // on the bit ranges. 10711 QualType OtherT = Other->getType(); 10712 if (const auto *AT = OtherT->getAs<AtomicType>()) 10713 OtherT = AT->getValueType(); 10714 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10715 10716 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10717 // (Namely, macOS). 10718 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10719 S.NSAPIObj->isObjCBOOLType(OtherT) && 10720 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10721 10722 // Whether we're treating Other as being a bool because of the form of 10723 // expression despite it having another type (typically 'int' in C). 10724 bool OtherIsBooleanDespiteType = 10725 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10726 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10727 OtherRange = IntRange::forBoolType(); 10728 10729 // Determine the promoted range of the other type and see if a comparison of 10730 // the constant against that range is tautological. 10731 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10732 Value.isUnsigned()); 10733 auto Cmp = OtherPromotedRange.compare(Value); 10734 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10735 if (!Result) 10736 return false; 10737 10738 // Suppress the diagnostic for an in-range comparison if the constant comes 10739 // from a macro or enumerator. We don't want to diagnose 10740 // 10741 // some_long_value <= INT_MAX 10742 // 10743 // when sizeof(int) == sizeof(long). 10744 bool InRange = Cmp & PromotedRange::InRangeFlag; 10745 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10746 return false; 10747 10748 // If this is a comparison to an enum constant, include that 10749 // constant in the diagnostic. 10750 const EnumConstantDecl *ED = nullptr; 10751 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10752 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10753 10754 // Should be enough for uint128 (39 decimal digits) 10755 SmallString<64> PrettySourceValue; 10756 llvm::raw_svector_ostream OS(PrettySourceValue); 10757 if (ED) { 10758 OS << '\'' << *ED << "' (" << Value << ")"; 10759 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10760 Constant->IgnoreParenImpCasts())) { 10761 OS << (BL->getValue() ? "YES" : "NO"); 10762 } else { 10763 OS << Value; 10764 } 10765 10766 if (IsObjCSignedCharBool) { 10767 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10768 S.PDiag(diag::warn_tautological_compare_objc_bool) 10769 << OS.str() << *Result); 10770 return true; 10771 } 10772 10773 // FIXME: We use a somewhat different formatting for the in-range cases and 10774 // cases involving boolean values for historical reasons. We should pick a 10775 // consistent way of presenting these diagnostics. 10776 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10777 10778 S.DiagRuntimeBehavior( 10779 E->getOperatorLoc(), E, 10780 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10781 : diag::warn_tautological_bool_compare) 10782 << OS.str() << classifyConstantValue(Constant) << OtherT 10783 << OtherIsBooleanDespiteType << *Result 10784 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10785 } else { 10786 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10787 ? (HasEnumType(OriginalOther) 10788 ? diag::warn_unsigned_enum_always_true_comparison 10789 : diag::warn_unsigned_always_true_comparison) 10790 : diag::warn_tautological_constant_compare; 10791 10792 S.Diag(E->getOperatorLoc(), Diag) 10793 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10794 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10795 } 10796 10797 return true; 10798 } 10799 10800 /// Analyze the operands of the given comparison. Implements the 10801 /// fallback case from AnalyzeComparison. 10802 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10803 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10804 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10805 } 10806 10807 /// Implements -Wsign-compare. 10808 /// 10809 /// \param E the binary operator to check for warnings 10810 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10811 // The type the comparison is being performed in. 10812 QualType T = E->getLHS()->getType(); 10813 10814 // Only analyze comparison operators where both sides have been converted to 10815 // the same type. 10816 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10817 return AnalyzeImpConvsInComparison(S, E); 10818 10819 // Don't analyze value-dependent comparisons directly. 10820 if (E->isValueDependent()) 10821 return AnalyzeImpConvsInComparison(S, E); 10822 10823 Expr *LHS = E->getLHS(); 10824 Expr *RHS = E->getRHS(); 10825 10826 if (T->isIntegralType(S.Context)) { 10827 llvm::APSInt RHSValue; 10828 llvm::APSInt LHSValue; 10829 10830 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10831 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10832 10833 // We don't care about expressions whose result is a constant. 10834 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10835 return AnalyzeImpConvsInComparison(S, E); 10836 10837 // We only care about expressions where just one side is literal 10838 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10839 // Is the constant on the RHS or LHS? 10840 const bool RhsConstant = IsRHSIntegralLiteral; 10841 Expr *Const = RhsConstant ? RHS : LHS; 10842 Expr *Other = RhsConstant ? LHS : RHS; 10843 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10844 10845 // Check whether an integer constant comparison results in a value 10846 // of 'true' or 'false'. 10847 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10848 return AnalyzeImpConvsInComparison(S, E); 10849 } 10850 } 10851 10852 if (!T->hasUnsignedIntegerRepresentation()) { 10853 // We don't do anything special if this isn't an unsigned integral 10854 // comparison: we're only interested in integral comparisons, and 10855 // signed comparisons only happen in cases we don't care to warn about. 10856 return AnalyzeImpConvsInComparison(S, E); 10857 } 10858 10859 LHS = LHS->IgnoreParenImpCasts(); 10860 RHS = RHS->IgnoreParenImpCasts(); 10861 10862 if (!S.getLangOpts().CPlusPlus) { 10863 // Avoid warning about comparison of integers with different signs when 10864 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10865 // the type of `E`. 10866 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10867 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10868 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10869 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10870 } 10871 10872 // Check to see if one of the (unmodified) operands is of different 10873 // signedness. 10874 Expr *signedOperand, *unsignedOperand; 10875 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10876 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10877 "unsigned comparison between two signed integer expressions?"); 10878 signedOperand = LHS; 10879 unsignedOperand = RHS; 10880 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10881 signedOperand = RHS; 10882 unsignedOperand = LHS; 10883 } else { 10884 return AnalyzeImpConvsInComparison(S, E); 10885 } 10886 10887 // Otherwise, calculate the effective range of the signed operand. 10888 IntRange signedRange = 10889 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10890 10891 // Go ahead and analyze implicit conversions in the operands. Note 10892 // that we skip the implicit conversions on both sides. 10893 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10894 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10895 10896 // If the signed range is non-negative, -Wsign-compare won't fire. 10897 if (signedRange.NonNegative) 10898 return; 10899 10900 // For (in)equality comparisons, if the unsigned operand is a 10901 // constant which cannot collide with a overflowed signed operand, 10902 // then reinterpreting the signed operand as unsigned will not 10903 // change the result of the comparison. 10904 if (E->isEqualityOp()) { 10905 unsigned comparisonWidth = S.Context.getIntWidth(T); 10906 IntRange unsignedRange = 10907 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10908 10909 // We should never be unable to prove that the unsigned operand is 10910 // non-negative. 10911 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10912 10913 if (unsignedRange.Width < comparisonWidth) 10914 return; 10915 } 10916 10917 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10918 S.PDiag(diag::warn_mixed_sign_comparison) 10919 << LHS->getType() << RHS->getType() 10920 << LHS->getSourceRange() << RHS->getSourceRange()); 10921 } 10922 10923 /// Analyzes an attempt to assign the given value to a bitfield. 10924 /// 10925 /// Returns true if there was something fishy about the attempt. 10926 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10927 SourceLocation InitLoc) { 10928 assert(Bitfield->isBitField()); 10929 if (Bitfield->isInvalidDecl()) 10930 return false; 10931 10932 // White-list bool bitfields. 10933 QualType BitfieldType = Bitfield->getType(); 10934 if (BitfieldType->isBooleanType()) 10935 return false; 10936 10937 if (BitfieldType->isEnumeralType()) { 10938 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10939 // If the underlying enum type was not explicitly specified as an unsigned 10940 // type and the enum contain only positive values, MSVC++ will cause an 10941 // inconsistency by storing this as a signed type. 10942 if (S.getLangOpts().CPlusPlus11 && 10943 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10944 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10945 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10946 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10947 << BitfieldEnumDecl->getNameAsString(); 10948 } 10949 } 10950 10951 if (Bitfield->getType()->isBooleanType()) 10952 return false; 10953 10954 // Ignore value- or type-dependent expressions. 10955 if (Bitfield->getBitWidth()->isValueDependent() || 10956 Bitfield->getBitWidth()->isTypeDependent() || 10957 Init->isValueDependent() || 10958 Init->isTypeDependent()) 10959 return false; 10960 10961 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10962 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10963 10964 Expr::EvalResult Result; 10965 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10966 Expr::SE_AllowSideEffects)) { 10967 // The RHS is not constant. If the RHS has an enum type, make sure the 10968 // bitfield is wide enough to hold all the values of the enum without 10969 // truncation. 10970 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10971 EnumDecl *ED = EnumTy->getDecl(); 10972 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10973 10974 // Enum types are implicitly signed on Windows, so check if there are any 10975 // negative enumerators to see if the enum was intended to be signed or 10976 // not. 10977 bool SignedEnum = ED->getNumNegativeBits() > 0; 10978 10979 // Check for surprising sign changes when assigning enum values to a 10980 // bitfield of different signedness. If the bitfield is signed and we 10981 // have exactly the right number of bits to store this unsigned enum, 10982 // suggest changing the enum to an unsigned type. This typically happens 10983 // on Windows where unfixed enums always use an underlying type of 'int'. 10984 unsigned DiagID = 0; 10985 if (SignedEnum && !SignedBitfield) { 10986 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10987 } else if (SignedBitfield && !SignedEnum && 10988 ED->getNumPositiveBits() == FieldWidth) { 10989 DiagID = diag::warn_signed_bitfield_enum_conversion; 10990 } 10991 10992 if (DiagID) { 10993 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10994 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10995 SourceRange TypeRange = 10996 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10997 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10998 << SignedEnum << TypeRange; 10999 } 11000 11001 // Compute the required bitwidth. If the enum has negative values, we need 11002 // one more bit than the normal number of positive bits to represent the 11003 // sign bit. 11004 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11005 ED->getNumNegativeBits()) 11006 : ED->getNumPositiveBits(); 11007 11008 // Check the bitwidth. 11009 if (BitsNeeded > FieldWidth) { 11010 Expr *WidthExpr = Bitfield->getBitWidth(); 11011 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11012 << Bitfield << ED; 11013 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11014 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11015 } 11016 } 11017 11018 return false; 11019 } 11020 11021 llvm::APSInt Value = Result.Val.getInt(); 11022 11023 unsigned OriginalWidth = Value.getBitWidth(); 11024 11025 if (!Value.isSigned() || Value.isNegative()) 11026 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11027 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11028 OriginalWidth = Value.getMinSignedBits(); 11029 11030 if (OriginalWidth <= FieldWidth) 11031 return false; 11032 11033 // Compute the value which the bitfield will contain. 11034 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11035 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11036 11037 // Check whether the stored value is equal to the original value. 11038 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11039 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11040 return false; 11041 11042 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11043 // therefore don't strictly fit into a signed bitfield of width 1. 11044 if (FieldWidth == 1 && Value == 1) 11045 return false; 11046 11047 std::string PrettyValue = Value.toString(10); 11048 std::string PrettyTrunc = TruncatedValue.toString(10); 11049 11050 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11051 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11052 << Init->getSourceRange(); 11053 11054 return true; 11055 } 11056 11057 /// Analyze the given simple or compound assignment for warning-worthy 11058 /// operations. 11059 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11060 // Just recurse on the LHS. 11061 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11062 11063 // We want to recurse on the RHS as normal unless we're assigning to 11064 // a bitfield. 11065 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11066 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11067 E->getOperatorLoc())) { 11068 // Recurse, ignoring any implicit conversions on the RHS. 11069 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11070 E->getOperatorLoc()); 11071 } 11072 } 11073 11074 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11075 11076 // Diagnose implicitly sequentially-consistent atomic assignment. 11077 if (E->getLHS()->getType()->isAtomicType()) 11078 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11079 } 11080 11081 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11082 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11083 SourceLocation CContext, unsigned diag, 11084 bool pruneControlFlow = false) { 11085 if (pruneControlFlow) { 11086 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11087 S.PDiag(diag) 11088 << SourceType << T << E->getSourceRange() 11089 << SourceRange(CContext)); 11090 return; 11091 } 11092 S.Diag(E->getExprLoc(), diag) 11093 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11094 } 11095 11096 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11097 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11098 SourceLocation CContext, 11099 unsigned diag, bool pruneControlFlow = false) { 11100 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11101 } 11102 11103 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11104 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11105 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11106 } 11107 11108 static void adornObjCBoolConversionDiagWithTernaryFixit( 11109 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11110 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11111 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11112 Ignored = OVE->getSourceExpr(); 11113 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11114 isa<BinaryOperator>(Ignored) || 11115 isa<CXXOperatorCallExpr>(Ignored); 11116 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11117 if (NeedsParens) 11118 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11119 << FixItHint::CreateInsertion(EndLoc, ")"); 11120 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11121 } 11122 11123 /// Diagnose an implicit cast from a floating point value to an integer value. 11124 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11125 SourceLocation CContext) { 11126 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11127 const bool PruneWarnings = S.inTemplateInstantiation(); 11128 11129 Expr *InnerE = E->IgnoreParenImpCasts(); 11130 // We also want to warn on, e.g., "int i = -1.234" 11131 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11132 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11133 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11134 11135 const bool IsLiteral = 11136 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11137 11138 llvm::APFloat Value(0.0); 11139 bool IsConstant = 11140 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11141 if (!IsConstant) { 11142 if (isObjCSignedCharBool(S, T)) { 11143 return adornObjCBoolConversionDiagWithTernaryFixit( 11144 S, E, 11145 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11146 << E->getType()); 11147 } 11148 11149 return DiagnoseImpCast(S, E, T, CContext, 11150 diag::warn_impcast_float_integer, PruneWarnings); 11151 } 11152 11153 bool isExact = false; 11154 11155 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11156 T->hasUnsignedIntegerRepresentation()); 11157 llvm::APFloat::opStatus Result = Value.convertToInteger( 11158 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11159 11160 // FIXME: Force the precision of the source value down so we don't print 11161 // digits which are usually useless (we don't really care here if we 11162 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11163 // would automatically print the shortest representation, but it's a bit 11164 // tricky to implement. 11165 SmallString<16> PrettySourceValue; 11166 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11167 precision = (precision * 59 + 195) / 196; 11168 Value.toString(PrettySourceValue, precision); 11169 11170 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11171 return adornObjCBoolConversionDiagWithTernaryFixit( 11172 S, E, 11173 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11174 << PrettySourceValue); 11175 } 11176 11177 if (Result == llvm::APFloat::opOK && isExact) { 11178 if (IsLiteral) return; 11179 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11180 PruneWarnings); 11181 } 11182 11183 // Conversion of a floating-point value to a non-bool integer where the 11184 // integral part cannot be represented by the integer type is undefined. 11185 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11186 return DiagnoseImpCast( 11187 S, E, T, CContext, 11188 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11189 : diag::warn_impcast_float_to_integer_out_of_range, 11190 PruneWarnings); 11191 11192 unsigned DiagID = 0; 11193 if (IsLiteral) { 11194 // Warn on floating point literal to integer. 11195 DiagID = diag::warn_impcast_literal_float_to_integer; 11196 } else if (IntegerValue == 0) { 11197 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11198 return DiagnoseImpCast(S, E, T, CContext, 11199 diag::warn_impcast_float_integer, PruneWarnings); 11200 } 11201 // Warn on non-zero to zero conversion. 11202 DiagID = diag::warn_impcast_float_to_integer_zero; 11203 } else { 11204 if (IntegerValue.isUnsigned()) { 11205 if (!IntegerValue.isMaxValue()) { 11206 return DiagnoseImpCast(S, E, T, CContext, 11207 diag::warn_impcast_float_integer, PruneWarnings); 11208 } 11209 } else { // IntegerValue.isSigned() 11210 if (!IntegerValue.isMaxSignedValue() && 11211 !IntegerValue.isMinSignedValue()) { 11212 return DiagnoseImpCast(S, E, T, CContext, 11213 diag::warn_impcast_float_integer, PruneWarnings); 11214 } 11215 } 11216 // Warn on evaluatable floating point expression to integer conversion. 11217 DiagID = diag::warn_impcast_float_to_integer; 11218 } 11219 11220 SmallString<16> PrettyTargetValue; 11221 if (IsBool) 11222 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11223 else 11224 IntegerValue.toString(PrettyTargetValue); 11225 11226 if (PruneWarnings) { 11227 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11228 S.PDiag(DiagID) 11229 << E->getType() << T.getUnqualifiedType() 11230 << PrettySourceValue << PrettyTargetValue 11231 << E->getSourceRange() << SourceRange(CContext)); 11232 } else { 11233 S.Diag(E->getExprLoc(), DiagID) 11234 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11235 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11236 } 11237 } 11238 11239 /// Analyze the given compound assignment for the possible losing of 11240 /// floating-point precision. 11241 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11242 assert(isa<CompoundAssignOperator>(E) && 11243 "Must be compound assignment operation"); 11244 // Recurse on the LHS and RHS in here 11245 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11246 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11247 11248 if (E->getLHS()->getType()->isAtomicType()) 11249 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11250 11251 // Now check the outermost expression 11252 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11253 const auto *RBT = cast<CompoundAssignOperator>(E) 11254 ->getComputationResultType() 11255 ->getAs<BuiltinType>(); 11256 11257 // The below checks assume source is floating point. 11258 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11259 11260 // If source is floating point but target is an integer. 11261 if (ResultBT->isInteger()) 11262 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11263 E->getExprLoc(), diag::warn_impcast_float_integer); 11264 11265 if (!ResultBT->isFloatingPoint()) 11266 return; 11267 11268 // If both source and target are floating points, warn about losing precision. 11269 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11270 QualType(ResultBT, 0), QualType(RBT, 0)); 11271 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11272 // warn about dropping FP rank. 11273 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11274 diag::warn_impcast_float_result_precision); 11275 } 11276 11277 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11278 IntRange Range) { 11279 if (!Range.Width) return "0"; 11280 11281 llvm::APSInt ValueInRange = Value; 11282 ValueInRange.setIsSigned(!Range.NonNegative); 11283 ValueInRange = ValueInRange.trunc(Range.Width); 11284 return ValueInRange.toString(10); 11285 } 11286 11287 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11288 if (!isa<ImplicitCastExpr>(Ex)) 11289 return false; 11290 11291 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11292 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11293 const Type *Source = 11294 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11295 if (Target->isDependentType()) 11296 return false; 11297 11298 const BuiltinType *FloatCandidateBT = 11299 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11300 const Type *BoolCandidateType = ToBool ? Target : Source; 11301 11302 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11303 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11304 } 11305 11306 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11307 SourceLocation CC) { 11308 unsigned NumArgs = TheCall->getNumArgs(); 11309 for (unsigned i = 0; i < NumArgs; ++i) { 11310 Expr *CurrA = TheCall->getArg(i); 11311 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11312 continue; 11313 11314 bool IsSwapped = ((i > 0) && 11315 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11316 IsSwapped |= ((i < (NumArgs - 1)) && 11317 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11318 if (IsSwapped) { 11319 // Warn on this floating-point to bool conversion. 11320 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11321 CurrA->getType(), CC, 11322 diag::warn_impcast_floating_point_to_bool); 11323 } 11324 } 11325 } 11326 11327 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11328 SourceLocation CC) { 11329 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11330 E->getExprLoc())) 11331 return; 11332 11333 // Don't warn on functions which have return type nullptr_t. 11334 if (isa<CallExpr>(E)) 11335 return; 11336 11337 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11338 const Expr::NullPointerConstantKind NullKind = 11339 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11340 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11341 return; 11342 11343 // Return if target type is a safe conversion. 11344 if (T->isAnyPointerType() || T->isBlockPointerType() || 11345 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11346 return; 11347 11348 SourceLocation Loc = E->getSourceRange().getBegin(); 11349 11350 // Venture through the macro stacks to get to the source of macro arguments. 11351 // The new location is a better location than the complete location that was 11352 // passed in. 11353 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11354 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11355 11356 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11357 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11358 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11359 Loc, S.SourceMgr, S.getLangOpts()); 11360 if (MacroName == "NULL") 11361 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11362 } 11363 11364 // Only warn if the null and context location are in the same macro expansion. 11365 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11366 return; 11367 11368 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11369 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11370 << FixItHint::CreateReplacement(Loc, 11371 S.getFixItZeroLiteralForType(T, Loc)); 11372 } 11373 11374 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11375 ObjCArrayLiteral *ArrayLiteral); 11376 11377 static void 11378 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11379 ObjCDictionaryLiteral *DictionaryLiteral); 11380 11381 /// Check a single element within a collection literal against the 11382 /// target element type. 11383 static void checkObjCCollectionLiteralElement(Sema &S, 11384 QualType TargetElementType, 11385 Expr *Element, 11386 unsigned ElementKind) { 11387 // Skip a bitcast to 'id' or qualified 'id'. 11388 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11389 if (ICE->getCastKind() == CK_BitCast && 11390 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11391 Element = ICE->getSubExpr(); 11392 } 11393 11394 QualType ElementType = Element->getType(); 11395 ExprResult ElementResult(Element); 11396 if (ElementType->getAs<ObjCObjectPointerType>() && 11397 S.CheckSingleAssignmentConstraints(TargetElementType, 11398 ElementResult, 11399 false, false) 11400 != Sema::Compatible) { 11401 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11402 << ElementType << ElementKind << TargetElementType 11403 << Element->getSourceRange(); 11404 } 11405 11406 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11407 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11408 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11409 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11410 } 11411 11412 /// Check an Objective-C array literal being converted to the given 11413 /// target type. 11414 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11415 ObjCArrayLiteral *ArrayLiteral) { 11416 if (!S.NSArrayDecl) 11417 return; 11418 11419 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11420 if (!TargetObjCPtr) 11421 return; 11422 11423 if (TargetObjCPtr->isUnspecialized() || 11424 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11425 != S.NSArrayDecl->getCanonicalDecl()) 11426 return; 11427 11428 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11429 if (TypeArgs.size() != 1) 11430 return; 11431 11432 QualType TargetElementType = TypeArgs[0]; 11433 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11434 checkObjCCollectionLiteralElement(S, TargetElementType, 11435 ArrayLiteral->getElement(I), 11436 0); 11437 } 11438 } 11439 11440 /// Check an Objective-C dictionary literal being converted to the given 11441 /// target type. 11442 static void 11443 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11444 ObjCDictionaryLiteral *DictionaryLiteral) { 11445 if (!S.NSDictionaryDecl) 11446 return; 11447 11448 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11449 if (!TargetObjCPtr) 11450 return; 11451 11452 if (TargetObjCPtr->isUnspecialized() || 11453 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11454 != S.NSDictionaryDecl->getCanonicalDecl()) 11455 return; 11456 11457 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11458 if (TypeArgs.size() != 2) 11459 return; 11460 11461 QualType TargetKeyType = TypeArgs[0]; 11462 QualType TargetObjectType = TypeArgs[1]; 11463 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11464 auto Element = DictionaryLiteral->getKeyValueElement(I); 11465 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11466 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11467 } 11468 } 11469 11470 // Helper function to filter out cases for constant width constant conversion. 11471 // Don't warn on char array initialization or for non-decimal values. 11472 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11473 SourceLocation CC) { 11474 // If initializing from a constant, and the constant starts with '0', 11475 // then it is a binary, octal, or hexadecimal. Allow these constants 11476 // to fill all the bits, even if there is a sign change. 11477 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11478 const char FirstLiteralCharacter = 11479 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11480 if (FirstLiteralCharacter == '0') 11481 return false; 11482 } 11483 11484 // If the CC location points to a '{', and the type is char, then assume 11485 // assume it is an array initialization. 11486 if (CC.isValid() && T->isCharType()) { 11487 const char FirstContextCharacter = 11488 S.getSourceManager().getCharacterData(CC)[0]; 11489 if (FirstContextCharacter == '{') 11490 return false; 11491 } 11492 11493 return true; 11494 } 11495 11496 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11497 const auto *IL = dyn_cast<IntegerLiteral>(E); 11498 if (!IL) { 11499 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11500 if (UO->getOpcode() == UO_Minus) 11501 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11502 } 11503 } 11504 11505 return IL; 11506 } 11507 11508 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11509 E = E->IgnoreParenImpCasts(); 11510 SourceLocation ExprLoc = E->getExprLoc(); 11511 11512 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11513 BinaryOperator::Opcode Opc = BO->getOpcode(); 11514 Expr::EvalResult Result; 11515 // Do not diagnose unsigned shifts. 11516 if (Opc == BO_Shl) { 11517 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11518 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11519 if (LHS && LHS->getValue() == 0) 11520 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11521 else if (!E->isValueDependent() && LHS && RHS && 11522 RHS->getValue().isNonNegative() && 11523 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11524 S.Diag(ExprLoc, diag::warn_left_shift_always) 11525 << (Result.Val.getInt() != 0); 11526 else if (E->getType()->isSignedIntegerType()) 11527 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11528 } 11529 } 11530 11531 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11532 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11533 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11534 if (!LHS || !RHS) 11535 return; 11536 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11537 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11538 // Do not diagnose common idioms. 11539 return; 11540 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11541 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11542 } 11543 } 11544 11545 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11546 SourceLocation CC, 11547 bool *ICContext = nullptr, 11548 bool IsListInit = false) { 11549 if (E->isTypeDependent() || E->isValueDependent()) return; 11550 11551 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11552 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11553 if (Source == Target) return; 11554 if (Target->isDependentType()) return; 11555 11556 // If the conversion context location is invalid don't complain. We also 11557 // don't want to emit a warning if the issue occurs from the expansion of 11558 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11559 // delay this check as long as possible. Once we detect we are in that 11560 // scenario, we just return. 11561 if (CC.isInvalid()) 11562 return; 11563 11564 if (Source->isAtomicType()) 11565 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11566 11567 // Diagnose implicit casts to bool. 11568 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11569 if (isa<StringLiteral>(E)) 11570 // Warn on string literal to bool. Checks for string literals in logical 11571 // and expressions, for instance, assert(0 && "error here"), are 11572 // prevented by a check in AnalyzeImplicitConversions(). 11573 return DiagnoseImpCast(S, E, T, CC, 11574 diag::warn_impcast_string_literal_to_bool); 11575 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11576 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11577 // This covers the literal expressions that evaluate to Objective-C 11578 // objects. 11579 return DiagnoseImpCast(S, E, T, CC, 11580 diag::warn_impcast_objective_c_literal_to_bool); 11581 } 11582 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11583 // Warn on pointer to bool conversion that is always true. 11584 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11585 SourceRange(CC)); 11586 } 11587 } 11588 11589 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11590 // is a typedef for signed char (macOS), then that constant value has to be 1 11591 // or 0. 11592 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11593 Expr::EvalResult Result; 11594 if (E->EvaluateAsInt(Result, S.getASTContext(), 11595 Expr::SE_AllowSideEffects)) { 11596 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11597 adornObjCBoolConversionDiagWithTernaryFixit( 11598 S, E, 11599 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11600 << Result.Val.getInt().toString(10)); 11601 } 11602 return; 11603 } 11604 } 11605 11606 // Check implicit casts from Objective-C collection literals to specialized 11607 // collection types, e.g., NSArray<NSString *> *. 11608 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11609 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11610 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11611 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11612 11613 // Strip vector types. 11614 if (isa<VectorType>(Source)) { 11615 if (!isa<VectorType>(Target)) { 11616 if (S.SourceMgr.isInSystemMacro(CC)) 11617 return; 11618 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11619 } 11620 11621 // If the vector cast is cast between two vectors of the same size, it is 11622 // a bitcast, not a conversion. 11623 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11624 return; 11625 11626 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11627 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11628 } 11629 if (auto VecTy = dyn_cast<VectorType>(Target)) 11630 Target = VecTy->getElementType().getTypePtr(); 11631 11632 // Strip complex types. 11633 if (isa<ComplexType>(Source)) { 11634 if (!isa<ComplexType>(Target)) { 11635 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11636 return; 11637 11638 return DiagnoseImpCast(S, E, T, CC, 11639 S.getLangOpts().CPlusPlus 11640 ? diag::err_impcast_complex_scalar 11641 : diag::warn_impcast_complex_scalar); 11642 } 11643 11644 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11645 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11646 } 11647 11648 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11649 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11650 11651 // If the source is floating point... 11652 if (SourceBT && SourceBT->isFloatingPoint()) { 11653 // ...and the target is floating point... 11654 if (TargetBT && TargetBT->isFloatingPoint()) { 11655 // ...then warn if we're dropping FP rank. 11656 11657 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11658 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11659 if (Order > 0) { 11660 // Don't warn about float constants that are precisely 11661 // representable in the target type. 11662 Expr::EvalResult result; 11663 if (E->EvaluateAsRValue(result, S.Context)) { 11664 // Value might be a float, a float vector, or a float complex. 11665 if (IsSameFloatAfterCast(result.Val, 11666 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11667 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11668 return; 11669 } 11670 11671 if (S.SourceMgr.isInSystemMacro(CC)) 11672 return; 11673 11674 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11675 } 11676 // ... or possibly if we're increasing rank, too 11677 else if (Order < 0) { 11678 if (S.SourceMgr.isInSystemMacro(CC)) 11679 return; 11680 11681 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11682 } 11683 return; 11684 } 11685 11686 // If the target is integral, always warn. 11687 if (TargetBT && TargetBT->isInteger()) { 11688 if (S.SourceMgr.isInSystemMacro(CC)) 11689 return; 11690 11691 DiagnoseFloatingImpCast(S, E, T, CC); 11692 } 11693 11694 // Detect the case where a call result is converted from floating-point to 11695 // to bool, and the final argument to the call is converted from bool, to 11696 // discover this typo: 11697 // 11698 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11699 // 11700 // FIXME: This is an incredibly special case; is there some more general 11701 // way to detect this class of misplaced-parentheses bug? 11702 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11703 // Check last argument of function call to see if it is an 11704 // implicit cast from a type matching the type the result 11705 // is being cast to. 11706 CallExpr *CEx = cast<CallExpr>(E); 11707 if (unsigned NumArgs = CEx->getNumArgs()) { 11708 Expr *LastA = CEx->getArg(NumArgs - 1); 11709 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11710 if (isa<ImplicitCastExpr>(LastA) && 11711 InnerE->getType()->isBooleanType()) { 11712 // Warn on this floating-point to bool conversion 11713 DiagnoseImpCast(S, E, T, CC, 11714 diag::warn_impcast_floating_point_to_bool); 11715 } 11716 } 11717 } 11718 return; 11719 } 11720 11721 // Valid casts involving fixed point types should be accounted for here. 11722 if (Source->isFixedPointType()) { 11723 if (Target->isUnsaturatedFixedPointType()) { 11724 Expr::EvalResult Result; 11725 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11726 S.isConstantEvaluated())) { 11727 APFixedPoint Value = Result.Val.getFixedPoint(); 11728 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11729 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11730 if (Value > MaxVal || Value < MinVal) { 11731 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11732 S.PDiag(diag::warn_impcast_fixed_point_range) 11733 << Value.toString() << T 11734 << E->getSourceRange() 11735 << clang::SourceRange(CC)); 11736 return; 11737 } 11738 } 11739 } else if (Target->isIntegerType()) { 11740 Expr::EvalResult Result; 11741 if (!S.isConstantEvaluated() && 11742 E->EvaluateAsFixedPoint(Result, S.Context, 11743 Expr::SE_AllowSideEffects)) { 11744 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11745 11746 bool Overflowed; 11747 llvm::APSInt IntResult = FXResult.convertToInt( 11748 S.Context.getIntWidth(T), 11749 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11750 11751 if (Overflowed) { 11752 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11753 S.PDiag(diag::warn_impcast_fixed_point_range) 11754 << FXResult.toString() << T 11755 << E->getSourceRange() 11756 << clang::SourceRange(CC)); 11757 return; 11758 } 11759 } 11760 } 11761 } else if (Target->isUnsaturatedFixedPointType()) { 11762 if (Source->isIntegerType()) { 11763 Expr::EvalResult Result; 11764 if (!S.isConstantEvaluated() && 11765 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11766 llvm::APSInt Value = Result.Val.getInt(); 11767 11768 bool Overflowed; 11769 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11770 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11771 11772 if (Overflowed) { 11773 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11774 S.PDiag(diag::warn_impcast_fixed_point_range) 11775 << Value.toString(/*Radix=*/10) << T 11776 << E->getSourceRange() 11777 << clang::SourceRange(CC)); 11778 return; 11779 } 11780 } 11781 } 11782 } 11783 11784 // If we are casting an integer type to a floating point type without 11785 // initialization-list syntax, we might lose accuracy if the floating 11786 // point type has a narrower significand than the integer type. 11787 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11788 TargetBT->isFloatingType() && !IsListInit) { 11789 // Determine the number of precision bits in the source integer type. 11790 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11791 unsigned int SourcePrecision = SourceRange.Width; 11792 11793 // Determine the number of precision bits in the 11794 // target floating point type. 11795 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11796 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11797 11798 if (SourcePrecision > 0 && TargetPrecision > 0 && 11799 SourcePrecision > TargetPrecision) { 11800 11801 llvm::APSInt SourceInt; 11802 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11803 // If the source integer is a constant, convert it to the target 11804 // floating point type. Issue a warning if the value changes 11805 // during the whole conversion. 11806 llvm::APFloat TargetFloatValue( 11807 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11808 llvm::APFloat::opStatus ConversionStatus = 11809 TargetFloatValue.convertFromAPInt( 11810 SourceInt, SourceBT->isSignedInteger(), 11811 llvm::APFloat::rmNearestTiesToEven); 11812 11813 if (ConversionStatus != llvm::APFloat::opOK) { 11814 std::string PrettySourceValue = SourceInt.toString(10); 11815 SmallString<32> PrettyTargetValue; 11816 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11817 11818 S.DiagRuntimeBehavior( 11819 E->getExprLoc(), E, 11820 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11821 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11822 << E->getSourceRange() << clang::SourceRange(CC)); 11823 } 11824 } else { 11825 // Otherwise, the implicit conversion may lose precision. 11826 DiagnoseImpCast(S, E, T, CC, 11827 diag::warn_impcast_integer_float_precision); 11828 } 11829 } 11830 } 11831 11832 DiagnoseNullConversion(S, E, T, CC); 11833 11834 S.DiscardMisalignedMemberAddress(Target, E); 11835 11836 if (Target->isBooleanType()) 11837 DiagnoseIntInBoolContext(S, E); 11838 11839 if (!Source->isIntegerType() || !Target->isIntegerType()) 11840 return; 11841 11842 // TODO: remove this early return once the false positives for constant->bool 11843 // in templates, macros, etc, are reduced or removed. 11844 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11845 return; 11846 11847 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11848 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11849 return adornObjCBoolConversionDiagWithTernaryFixit( 11850 S, E, 11851 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11852 << E->getType()); 11853 } 11854 11855 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11856 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11857 11858 if (SourceRange.Width > TargetRange.Width) { 11859 // If the source is a constant, use a default-on diagnostic. 11860 // TODO: this should happen for bitfield stores, too. 11861 Expr::EvalResult Result; 11862 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11863 S.isConstantEvaluated())) { 11864 llvm::APSInt Value(32); 11865 Value = Result.Val.getInt(); 11866 11867 if (S.SourceMgr.isInSystemMacro(CC)) 11868 return; 11869 11870 std::string PrettySourceValue = Value.toString(10); 11871 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11872 11873 S.DiagRuntimeBehavior( 11874 E->getExprLoc(), E, 11875 S.PDiag(diag::warn_impcast_integer_precision_constant) 11876 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11877 << E->getSourceRange() << clang::SourceRange(CC)); 11878 return; 11879 } 11880 11881 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11882 if (S.SourceMgr.isInSystemMacro(CC)) 11883 return; 11884 11885 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11886 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11887 /* pruneControlFlow */ true); 11888 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11889 } 11890 11891 if (TargetRange.Width > SourceRange.Width) { 11892 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11893 if (UO->getOpcode() == UO_Minus) 11894 if (Source->isUnsignedIntegerType()) { 11895 if (Target->isUnsignedIntegerType()) 11896 return DiagnoseImpCast(S, E, T, CC, 11897 diag::warn_impcast_high_order_zero_bits); 11898 if (Target->isSignedIntegerType()) 11899 return DiagnoseImpCast(S, E, T, CC, 11900 diag::warn_impcast_nonnegative_result); 11901 } 11902 } 11903 11904 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11905 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11906 // Warn when doing a signed to signed conversion, warn if the positive 11907 // source value is exactly the width of the target type, which will 11908 // cause a negative value to be stored. 11909 11910 Expr::EvalResult Result; 11911 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11912 !S.SourceMgr.isInSystemMacro(CC)) { 11913 llvm::APSInt Value = Result.Val.getInt(); 11914 if (isSameWidthConstantConversion(S, E, T, CC)) { 11915 std::string PrettySourceValue = Value.toString(10); 11916 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11917 11918 S.DiagRuntimeBehavior( 11919 E->getExprLoc(), E, 11920 S.PDiag(diag::warn_impcast_integer_precision_constant) 11921 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11922 << E->getSourceRange() << clang::SourceRange(CC)); 11923 return; 11924 } 11925 } 11926 11927 // Fall through for non-constants to give a sign conversion warning. 11928 } 11929 11930 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11931 (!TargetRange.NonNegative && SourceRange.NonNegative && 11932 SourceRange.Width == TargetRange.Width)) { 11933 if (S.SourceMgr.isInSystemMacro(CC)) 11934 return; 11935 11936 unsigned DiagID = diag::warn_impcast_integer_sign; 11937 11938 // Traditionally, gcc has warned about this under -Wsign-compare. 11939 // We also want to warn about it in -Wconversion. 11940 // So if -Wconversion is off, use a completely identical diagnostic 11941 // in the sign-compare group. 11942 // The conditional-checking code will 11943 if (ICContext) { 11944 DiagID = diag::warn_impcast_integer_sign_conditional; 11945 *ICContext = true; 11946 } 11947 11948 return DiagnoseImpCast(S, E, T, CC, DiagID); 11949 } 11950 11951 // Diagnose conversions between different enumeration types. 11952 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11953 // type, to give us better diagnostics. 11954 QualType SourceType = E->getType(); 11955 if (!S.getLangOpts().CPlusPlus) { 11956 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11957 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11958 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11959 SourceType = S.Context.getTypeDeclType(Enum); 11960 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11961 } 11962 } 11963 11964 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11965 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11966 if (SourceEnum->getDecl()->hasNameForLinkage() && 11967 TargetEnum->getDecl()->hasNameForLinkage() && 11968 SourceEnum != TargetEnum) { 11969 if (S.SourceMgr.isInSystemMacro(CC)) 11970 return; 11971 11972 return DiagnoseImpCast(S, E, SourceType, T, CC, 11973 diag::warn_impcast_different_enum_types); 11974 } 11975 } 11976 11977 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11978 SourceLocation CC, QualType T); 11979 11980 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11981 SourceLocation CC, bool &ICContext) { 11982 E = E->IgnoreParenImpCasts(); 11983 11984 if (isa<ConditionalOperator>(E)) 11985 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11986 11987 AnalyzeImplicitConversions(S, E, CC); 11988 if (E->getType() != T) 11989 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11990 } 11991 11992 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11993 SourceLocation CC, QualType T) { 11994 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11995 11996 bool Suspicious = false; 11997 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11998 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11999 12000 if (T->isBooleanType()) 12001 DiagnoseIntInBoolContext(S, E); 12002 12003 // If -Wconversion would have warned about either of the candidates 12004 // for a signedness conversion to the context type... 12005 if (!Suspicious) return; 12006 12007 // ...but it's currently ignored... 12008 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12009 return; 12010 12011 // ...then check whether it would have warned about either of the 12012 // candidates for a signedness conversion to the condition type. 12013 if (E->getType() == T) return; 12014 12015 Suspicious = false; 12016 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 12017 E->getType(), CC, &Suspicious); 12018 if (!Suspicious) 12019 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12020 E->getType(), CC, &Suspicious); 12021 } 12022 12023 /// Check conversion of given expression to boolean. 12024 /// Input argument E is a logical expression. 12025 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12026 if (S.getLangOpts().Bool) 12027 return; 12028 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12029 return; 12030 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12031 } 12032 12033 /// AnalyzeImplicitConversions - Find and report any interesting 12034 /// implicit conversions in the given expression. There are a couple 12035 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12036 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12037 bool IsListInit/*= false*/) { 12038 QualType T = OrigE->getType(); 12039 Expr *E = OrigE->IgnoreParenImpCasts(); 12040 12041 // Propagate whether we are in a C++ list initialization expression. 12042 // If so, we do not issue warnings for implicit int-float conversion 12043 // precision loss, because C++11 narrowing already handles it. 12044 IsListInit = 12045 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12046 12047 if (E->isTypeDependent() || E->isValueDependent()) 12048 return; 12049 12050 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 12051 if (UO->getOpcode() == UO_Not && 12052 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12053 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12054 << OrigE->getSourceRange() << T->isBooleanType() 12055 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12056 12057 // For conditional operators, we analyze the arguments as if they 12058 // were being fed directly into the output. 12059 if (isa<ConditionalOperator>(E)) { 12060 ConditionalOperator *CO = cast<ConditionalOperator>(E); 12061 CheckConditionalOperator(S, CO, CC, T); 12062 return; 12063 } 12064 12065 // Check implicit argument conversions for function calls. 12066 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 12067 CheckImplicitArgumentConversions(S, Call, CC); 12068 12069 // Go ahead and check any implicit conversions we might have skipped. 12070 // The non-canonical typecheck is just an optimization; 12071 // CheckImplicitConversion will filter out dead implicit conversions. 12072 if (E->getType() != T) 12073 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit); 12074 12075 // Now continue drilling into this expression. 12076 12077 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12078 // The bound subexpressions in a PseudoObjectExpr are not reachable 12079 // as transitive children. 12080 // FIXME: Use a more uniform representation for this. 12081 for (auto *SE : POE->semantics()) 12082 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12083 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 12084 } 12085 12086 // Skip past explicit casts. 12087 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12088 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12089 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12090 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12091 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 12092 } 12093 12094 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12095 // Do a somewhat different check with comparison operators. 12096 if (BO->isComparisonOp()) 12097 return AnalyzeComparison(S, BO); 12098 12099 // And with simple assignments. 12100 if (BO->getOpcode() == BO_Assign) 12101 return AnalyzeAssignment(S, BO); 12102 // And with compound assignments. 12103 if (BO->isAssignmentOp()) 12104 return AnalyzeCompoundAssignment(S, BO); 12105 } 12106 12107 // These break the otherwise-useful invariant below. Fortunately, 12108 // we don't really need to recurse into them, because any internal 12109 // expressions should have been analyzed already when they were 12110 // built into statements. 12111 if (isa<StmtExpr>(E)) return; 12112 12113 // Don't descend into unevaluated contexts. 12114 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12115 12116 // Now just recurse over the expression's children. 12117 CC = E->getExprLoc(); 12118 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12119 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12120 for (Stmt *SubStmt : E->children()) { 12121 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12122 if (!ChildExpr) 12123 continue; 12124 12125 if (IsLogicalAndOperator && 12126 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12127 // Ignore checking string literals that are in logical and operators. 12128 // This is a common pattern for asserts. 12129 continue; 12130 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 12131 } 12132 12133 if (BO && BO->isLogicalOp()) { 12134 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12135 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12136 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12137 12138 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12139 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12140 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12141 } 12142 12143 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12144 if (U->getOpcode() == UO_LNot) { 12145 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12146 } else if (U->getOpcode() != UO_AddrOf) { 12147 if (U->getSubExpr()->getType()->isAtomicType()) 12148 S.Diag(U->getSubExpr()->getBeginLoc(), 12149 diag::warn_atomic_implicit_seq_cst); 12150 } 12151 } 12152 } 12153 12154 /// Diagnose integer type and any valid implicit conversion to it. 12155 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12156 // Taking into account implicit conversions, 12157 // allow any integer. 12158 if (!E->getType()->isIntegerType()) { 12159 S.Diag(E->getBeginLoc(), 12160 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12161 return true; 12162 } 12163 // Potentially emit standard warnings for implicit conversions if enabled 12164 // using -Wconversion. 12165 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12166 return false; 12167 } 12168 12169 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12170 // Returns true when emitting a warning about taking the address of a reference. 12171 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12172 const PartialDiagnostic &PD) { 12173 E = E->IgnoreParenImpCasts(); 12174 12175 const FunctionDecl *FD = nullptr; 12176 12177 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12178 if (!DRE->getDecl()->getType()->isReferenceType()) 12179 return false; 12180 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12181 if (!M->getMemberDecl()->getType()->isReferenceType()) 12182 return false; 12183 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12184 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12185 return false; 12186 FD = Call->getDirectCallee(); 12187 } else { 12188 return false; 12189 } 12190 12191 SemaRef.Diag(E->getExprLoc(), PD); 12192 12193 // If possible, point to location of function. 12194 if (FD) { 12195 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12196 } 12197 12198 return true; 12199 } 12200 12201 // Returns true if the SourceLocation is expanded from any macro body. 12202 // Returns false if the SourceLocation is invalid, is from not in a macro 12203 // expansion, or is from expanded from a top-level macro argument. 12204 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12205 if (Loc.isInvalid()) 12206 return false; 12207 12208 while (Loc.isMacroID()) { 12209 if (SM.isMacroBodyExpansion(Loc)) 12210 return true; 12211 Loc = SM.getImmediateMacroCallerLoc(Loc); 12212 } 12213 12214 return false; 12215 } 12216 12217 /// Diagnose pointers that are always non-null. 12218 /// \param E the expression containing the pointer 12219 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12220 /// compared to a null pointer 12221 /// \param IsEqual True when the comparison is equal to a null pointer 12222 /// \param Range Extra SourceRange to highlight in the diagnostic 12223 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12224 Expr::NullPointerConstantKind NullKind, 12225 bool IsEqual, SourceRange Range) { 12226 if (!E) 12227 return; 12228 12229 // Don't warn inside macros. 12230 if (E->getExprLoc().isMacroID()) { 12231 const SourceManager &SM = getSourceManager(); 12232 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12233 IsInAnyMacroBody(SM, Range.getBegin())) 12234 return; 12235 } 12236 E = E->IgnoreImpCasts(); 12237 12238 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12239 12240 if (isa<CXXThisExpr>(E)) { 12241 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12242 : diag::warn_this_bool_conversion; 12243 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12244 return; 12245 } 12246 12247 bool IsAddressOf = false; 12248 12249 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12250 if (UO->getOpcode() != UO_AddrOf) 12251 return; 12252 IsAddressOf = true; 12253 E = UO->getSubExpr(); 12254 } 12255 12256 if (IsAddressOf) { 12257 unsigned DiagID = IsCompare 12258 ? diag::warn_address_of_reference_null_compare 12259 : diag::warn_address_of_reference_bool_conversion; 12260 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12261 << IsEqual; 12262 if (CheckForReference(*this, E, PD)) { 12263 return; 12264 } 12265 } 12266 12267 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12268 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12269 std::string Str; 12270 llvm::raw_string_ostream S(Str); 12271 E->printPretty(S, nullptr, getPrintingPolicy()); 12272 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12273 : diag::warn_cast_nonnull_to_bool; 12274 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12275 << E->getSourceRange() << Range << IsEqual; 12276 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12277 }; 12278 12279 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12280 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12281 if (auto *Callee = Call->getDirectCallee()) { 12282 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12283 ComplainAboutNonnullParamOrCall(A); 12284 return; 12285 } 12286 } 12287 } 12288 12289 // Expect to find a single Decl. Skip anything more complicated. 12290 ValueDecl *D = nullptr; 12291 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12292 D = R->getDecl(); 12293 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12294 D = M->getMemberDecl(); 12295 } 12296 12297 // Weak Decls can be null. 12298 if (!D || D->isWeak()) 12299 return; 12300 12301 // Check for parameter decl with nonnull attribute 12302 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12303 if (getCurFunction() && 12304 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12305 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12306 ComplainAboutNonnullParamOrCall(A); 12307 return; 12308 } 12309 12310 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12311 // Skip function template not specialized yet. 12312 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12313 return; 12314 auto ParamIter = llvm::find(FD->parameters(), PV); 12315 assert(ParamIter != FD->param_end()); 12316 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12317 12318 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12319 if (!NonNull->args_size()) { 12320 ComplainAboutNonnullParamOrCall(NonNull); 12321 return; 12322 } 12323 12324 for (const ParamIdx &ArgNo : NonNull->args()) { 12325 if (ArgNo.getASTIndex() == ParamNo) { 12326 ComplainAboutNonnullParamOrCall(NonNull); 12327 return; 12328 } 12329 } 12330 } 12331 } 12332 } 12333 } 12334 12335 QualType T = D->getType(); 12336 const bool IsArray = T->isArrayType(); 12337 const bool IsFunction = T->isFunctionType(); 12338 12339 // Address of function is used to silence the function warning. 12340 if (IsAddressOf && IsFunction) { 12341 return; 12342 } 12343 12344 // Found nothing. 12345 if (!IsAddressOf && !IsFunction && !IsArray) 12346 return; 12347 12348 // Pretty print the expression for the diagnostic. 12349 std::string Str; 12350 llvm::raw_string_ostream S(Str); 12351 E->printPretty(S, nullptr, getPrintingPolicy()); 12352 12353 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12354 : diag::warn_impcast_pointer_to_bool; 12355 enum { 12356 AddressOf, 12357 FunctionPointer, 12358 ArrayPointer 12359 } DiagType; 12360 if (IsAddressOf) 12361 DiagType = AddressOf; 12362 else if (IsFunction) 12363 DiagType = FunctionPointer; 12364 else if (IsArray) 12365 DiagType = ArrayPointer; 12366 else 12367 llvm_unreachable("Could not determine diagnostic."); 12368 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12369 << Range << IsEqual; 12370 12371 if (!IsFunction) 12372 return; 12373 12374 // Suggest '&' to silence the function warning. 12375 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12376 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12377 12378 // Check to see if '()' fixit should be emitted. 12379 QualType ReturnType; 12380 UnresolvedSet<4> NonTemplateOverloads; 12381 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12382 if (ReturnType.isNull()) 12383 return; 12384 12385 if (IsCompare) { 12386 // There are two cases here. If there is null constant, the only suggest 12387 // for a pointer return type. If the null is 0, then suggest if the return 12388 // type is a pointer or an integer type. 12389 if (!ReturnType->isPointerType()) { 12390 if (NullKind == Expr::NPCK_ZeroExpression || 12391 NullKind == Expr::NPCK_ZeroLiteral) { 12392 if (!ReturnType->isIntegerType()) 12393 return; 12394 } else { 12395 return; 12396 } 12397 } 12398 } else { // !IsCompare 12399 // For function to bool, only suggest if the function pointer has bool 12400 // return type. 12401 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12402 return; 12403 } 12404 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12405 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12406 } 12407 12408 /// Diagnoses "dangerous" implicit conversions within the given 12409 /// expression (which is a full expression). Implements -Wconversion 12410 /// and -Wsign-compare. 12411 /// 12412 /// \param CC the "context" location of the implicit conversion, i.e. 12413 /// the most location of the syntactic entity requiring the implicit 12414 /// conversion 12415 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12416 // Don't diagnose in unevaluated contexts. 12417 if (isUnevaluatedContext()) 12418 return; 12419 12420 // Don't diagnose for value- or type-dependent expressions. 12421 if (E->isTypeDependent() || E->isValueDependent()) 12422 return; 12423 12424 // Check for array bounds violations in cases where the check isn't triggered 12425 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12426 // ArraySubscriptExpr is on the RHS of a variable initialization. 12427 CheckArrayAccess(E); 12428 12429 // This is not the right CC for (e.g.) a variable initialization. 12430 AnalyzeImplicitConversions(*this, E, CC); 12431 } 12432 12433 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12434 /// Input argument E is a logical expression. 12435 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12436 ::CheckBoolLikeConversion(*this, E, CC); 12437 } 12438 12439 /// Diagnose when expression is an integer constant expression and its evaluation 12440 /// results in integer overflow 12441 void Sema::CheckForIntOverflow (Expr *E) { 12442 // Use a work list to deal with nested struct initializers. 12443 SmallVector<Expr *, 2> Exprs(1, E); 12444 12445 do { 12446 Expr *OriginalE = Exprs.pop_back_val(); 12447 Expr *E = OriginalE->IgnoreParenCasts(); 12448 12449 if (isa<BinaryOperator>(E)) { 12450 E->EvaluateForOverflow(Context); 12451 continue; 12452 } 12453 12454 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12455 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12456 else if (isa<ObjCBoxedExpr>(OriginalE)) 12457 E->EvaluateForOverflow(Context); 12458 else if (auto Call = dyn_cast<CallExpr>(E)) 12459 Exprs.append(Call->arg_begin(), Call->arg_end()); 12460 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12461 Exprs.append(Message->arg_begin(), Message->arg_end()); 12462 } while (!Exprs.empty()); 12463 } 12464 12465 namespace { 12466 12467 /// Visitor for expressions which looks for unsequenced operations on the 12468 /// same object. 12469 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12470 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12471 12472 /// A tree of sequenced regions within an expression. Two regions are 12473 /// unsequenced if one is an ancestor or a descendent of the other. When we 12474 /// finish processing an expression with sequencing, such as a comma 12475 /// expression, we fold its tree nodes into its parent, since they are 12476 /// unsequenced with respect to nodes we will visit later. 12477 class SequenceTree { 12478 struct Value { 12479 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12480 unsigned Parent : 31; 12481 unsigned Merged : 1; 12482 }; 12483 SmallVector<Value, 8> Values; 12484 12485 public: 12486 /// A region within an expression which may be sequenced with respect 12487 /// to some other region. 12488 class Seq { 12489 friend class SequenceTree; 12490 12491 unsigned Index; 12492 12493 explicit Seq(unsigned N) : Index(N) {} 12494 12495 public: 12496 Seq() : Index(0) {} 12497 }; 12498 12499 SequenceTree() { Values.push_back(Value(0)); } 12500 Seq root() const { return Seq(0); } 12501 12502 /// Create a new sequence of operations, which is an unsequenced 12503 /// subset of \p Parent. This sequence of operations is sequenced with 12504 /// respect to other children of \p Parent. 12505 Seq allocate(Seq Parent) { 12506 Values.push_back(Value(Parent.Index)); 12507 return Seq(Values.size() - 1); 12508 } 12509 12510 /// Merge a sequence of operations into its parent. 12511 void merge(Seq S) { 12512 Values[S.Index].Merged = true; 12513 } 12514 12515 /// Determine whether two operations are unsequenced. This operation 12516 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12517 /// should have been merged into its parent as appropriate. 12518 bool isUnsequenced(Seq Cur, Seq Old) { 12519 unsigned C = representative(Cur.Index); 12520 unsigned Target = representative(Old.Index); 12521 while (C >= Target) { 12522 if (C == Target) 12523 return true; 12524 C = Values[C].Parent; 12525 } 12526 return false; 12527 } 12528 12529 private: 12530 /// Pick a representative for a sequence. 12531 unsigned representative(unsigned K) { 12532 if (Values[K].Merged) 12533 // Perform path compression as we go. 12534 return Values[K].Parent = representative(Values[K].Parent); 12535 return K; 12536 } 12537 }; 12538 12539 /// An object for which we can track unsequenced uses. 12540 using Object = const NamedDecl *; 12541 12542 /// Different flavors of object usage which we track. We only track the 12543 /// least-sequenced usage of each kind. 12544 enum UsageKind { 12545 /// A read of an object. Multiple unsequenced reads are OK. 12546 UK_Use, 12547 12548 /// A modification of an object which is sequenced before the value 12549 /// computation of the expression, such as ++n in C++. 12550 UK_ModAsValue, 12551 12552 /// A modification of an object which is not sequenced before the value 12553 /// computation of the expression, such as n++. 12554 UK_ModAsSideEffect, 12555 12556 UK_Count = UK_ModAsSideEffect + 1 12557 }; 12558 12559 /// Bundle together a sequencing region and the expression corresponding 12560 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12561 struct Usage { 12562 const Expr *UsageExpr; 12563 SequenceTree::Seq Seq; 12564 12565 Usage() : UsageExpr(nullptr), Seq() {} 12566 }; 12567 12568 struct UsageInfo { 12569 Usage Uses[UK_Count]; 12570 12571 /// Have we issued a diagnostic for this object already? 12572 bool Diagnosed; 12573 12574 UsageInfo() : Uses(), Diagnosed(false) {} 12575 }; 12576 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12577 12578 Sema &SemaRef; 12579 12580 /// Sequenced regions within the expression. 12581 SequenceTree Tree; 12582 12583 /// Declaration modifications and references which we have seen. 12584 UsageInfoMap UsageMap; 12585 12586 /// The region we are currently within. 12587 SequenceTree::Seq Region; 12588 12589 /// Filled in with declarations which were modified as a side-effect 12590 /// (that is, post-increment operations). 12591 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12592 12593 /// Expressions to check later. We defer checking these to reduce 12594 /// stack usage. 12595 SmallVectorImpl<const Expr *> &WorkList; 12596 12597 /// RAII object wrapping the visitation of a sequenced subexpression of an 12598 /// expression. At the end of this process, the side-effects of the evaluation 12599 /// become sequenced with respect to the value computation of the result, so 12600 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12601 /// UK_ModAsValue. 12602 struct SequencedSubexpression { 12603 SequencedSubexpression(SequenceChecker &Self) 12604 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12605 Self.ModAsSideEffect = &ModAsSideEffect; 12606 } 12607 12608 ~SequencedSubexpression() { 12609 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12610 // Add a new usage with usage kind UK_ModAsValue, and then restore 12611 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12612 // the previous one was empty). 12613 UsageInfo &UI = Self.UsageMap[M.first]; 12614 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12615 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12616 SideEffectUsage = M.second; 12617 } 12618 Self.ModAsSideEffect = OldModAsSideEffect; 12619 } 12620 12621 SequenceChecker &Self; 12622 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12623 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12624 }; 12625 12626 /// RAII object wrapping the visitation of a subexpression which we might 12627 /// choose to evaluate as a constant. If any subexpression is evaluated and 12628 /// found to be non-constant, this allows us to suppress the evaluation of 12629 /// the outer expression. 12630 class EvaluationTracker { 12631 public: 12632 EvaluationTracker(SequenceChecker &Self) 12633 : Self(Self), Prev(Self.EvalTracker) { 12634 Self.EvalTracker = this; 12635 } 12636 12637 ~EvaluationTracker() { 12638 Self.EvalTracker = Prev; 12639 if (Prev) 12640 Prev->EvalOK &= EvalOK; 12641 } 12642 12643 bool evaluate(const Expr *E, bool &Result) { 12644 if (!EvalOK || E->isValueDependent()) 12645 return false; 12646 EvalOK = E->EvaluateAsBooleanCondition( 12647 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12648 return EvalOK; 12649 } 12650 12651 private: 12652 SequenceChecker &Self; 12653 EvaluationTracker *Prev; 12654 bool EvalOK = true; 12655 } *EvalTracker = nullptr; 12656 12657 /// Find the object which is produced by the specified expression, 12658 /// if any. 12659 Object getObject(const Expr *E, bool Mod) const { 12660 E = E->IgnoreParenCasts(); 12661 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12662 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12663 return getObject(UO->getSubExpr(), Mod); 12664 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12665 if (BO->getOpcode() == BO_Comma) 12666 return getObject(BO->getRHS(), Mod); 12667 if (Mod && BO->isAssignmentOp()) 12668 return getObject(BO->getLHS(), Mod); 12669 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12670 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12671 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12672 return ME->getMemberDecl(); 12673 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12674 // FIXME: If this is a reference, map through to its value. 12675 return DRE->getDecl(); 12676 return nullptr; 12677 } 12678 12679 /// Note that an object \p O was modified or used by an expression 12680 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12681 /// the object \p O as obtained via the \p UsageMap. 12682 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12683 // Get the old usage for the given object and usage kind. 12684 Usage &U = UI.Uses[UK]; 12685 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12686 // If we have a modification as side effect and are in a sequenced 12687 // subexpression, save the old Usage so that we can restore it later 12688 // in SequencedSubexpression::~SequencedSubexpression. 12689 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12690 ModAsSideEffect->push_back(std::make_pair(O, U)); 12691 // Then record the new usage with the current sequencing region. 12692 U.UsageExpr = UsageExpr; 12693 U.Seq = Region; 12694 } 12695 } 12696 12697 /// Check whether a modification or use of an object \p O in an expression 12698 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12699 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12700 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12701 /// usage and false we are checking for a mod-use unsequenced usage. 12702 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12703 UsageKind OtherKind, bool IsModMod) { 12704 if (UI.Diagnosed) 12705 return; 12706 12707 const Usage &U = UI.Uses[OtherKind]; 12708 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12709 return; 12710 12711 const Expr *Mod = U.UsageExpr; 12712 const Expr *ModOrUse = UsageExpr; 12713 if (OtherKind == UK_Use) 12714 std::swap(Mod, ModOrUse); 12715 12716 SemaRef.DiagRuntimeBehavior( 12717 Mod->getExprLoc(), {Mod, ModOrUse}, 12718 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12719 : diag::warn_unsequenced_mod_use) 12720 << O << SourceRange(ModOrUse->getExprLoc())); 12721 UI.Diagnosed = true; 12722 } 12723 12724 // A note on note{Pre, Post}{Use, Mod}: 12725 // 12726 // (It helps to follow the algorithm with an expression such as 12727 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12728 // operations before C++17 and both are well-defined in C++17). 12729 // 12730 // When visiting a node which uses/modify an object we first call notePreUse 12731 // or notePreMod before visiting its sub-expression(s). At this point the 12732 // children of the current node have not yet been visited and so the eventual 12733 // uses/modifications resulting from the children of the current node have not 12734 // been recorded yet. 12735 // 12736 // We then visit the children of the current node. After that notePostUse or 12737 // notePostMod is called. These will 1) detect an unsequenced modification 12738 // as side effect (as in "k++ + k") and 2) add a new usage with the 12739 // appropriate usage kind. 12740 // 12741 // We also have to be careful that some operation sequences modification as 12742 // side effect as well (for example: || or ,). To account for this we wrap 12743 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12744 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12745 // which record usages which are modifications as side effect, and then 12746 // downgrade them (or more accurately restore the previous usage which was a 12747 // modification as side effect) when exiting the scope of the sequenced 12748 // subexpression. 12749 12750 void notePreUse(Object O, const Expr *UseExpr) { 12751 UsageInfo &UI = UsageMap[O]; 12752 // Uses conflict with other modifications. 12753 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12754 } 12755 12756 void notePostUse(Object O, const Expr *UseExpr) { 12757 UsageInfo &UI = UsageMap[O]; 12758 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12759 /*IsModMod=*/false); 12760 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12761 } 12762 12763 void notePreMod(Object O, const Expr *ModExpr) { 12764 UsageInfo &UI = UsageMap[O]; 12765 // Modifications conflict with other modifications and with uses. 12766 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12767 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12768 } 12769 12770 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12771 UsageInfo &UI = UsageMap[O]; 12772 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12773 /*IsModMod=*/true); 12774 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12775 } 12776 12777 public: 12778 SequenceChecker(Sema &S, const Expr *E, 12779 SmallVectorImpl<const Expr *> &WorkList) 12780 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12781 Visit(E); 12782 // Silence a -Wunused-private-field since WorkList is now unused. 12783 // TODO: Evaluate if it can be used, and if not remove it. 12784 (void)this->WorkList; 12785 } 12786 12787 void VisitStmt(const Stmt *S) { 12788 // Skip all statements which aren't expressions for now. 12789 } 12790 12791 void VisitExpr(const Expr *E) { 12792 // By default, just recurse to evaluated subexpressions. 12793 Base::VisitStmt(E); 12794 } 12795 12796 void VisitCastExpr(const CastExpr *E) { 12797 Object O = Object(); 12798 if (E->getCastKind() == CK_LValueToRValue) 12799 O = getObject(E->getSubExpr(), false); 12800 12801 if (O) 12802 notePreUse(O, E); 12803 VisitExpr(E); 12804 if (O) 12805 notePostUse(O, E); 12806 } 12807 12808 void VisitSequencedExpressions(const Expr *SequencedBefore, 12809 const Expr *SequencedAfter) { 12810 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12811 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12812 SequenceTree::Seq OldRegion = Region; 12813 12814 { 12815 SequencedSubexpression SeqBefore(*this); 12816 Region = BeforeRegion; 12817 Visit(SequencedBefore); 12818 } 12819 12820 Region = AfterRegion; 12821 Visit(SequencedAfter); 12822 12823 Region = OldRegion; 12824 12825 Tree.merge(BeforeRegion); 12826 Tree.merge(AfterRegion); 12827 } 12828 12829 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12830 // C++17 [expr.sub]p1: 12831 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12832 // expression E1 is sequenced before the expression E2. 12833 if (SemaRef.getLangOpts().CPlusPlus17) 12834 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12835 else { 12836 Visit(ASE->getLHS()); 12837 Visit(ASE->getRHS()); 12838 } 12839 } 12840 12841 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12842 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12843 void VisitBinPtrMem(const BinaryOperator *BO) { 12844 // C++17 [expr.mptr.oper]p4: 12845 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12846 // the expression E1 is sequenced before the expression E2. 12847 if (SemaRef.getLangOpts().CPlusPlus17) 12848 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12849 else { 12850 Visit(BO->getLHS()); 12851 Visit(BO->getRHS()); 12852 } 12853 } 12854 12855 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12856 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12857 void VisitBinShlShr(const BinaryOperator *BO) { 12858 // C++17 [expr.shift]p4: 12859 // The expression E1 is sequenced before the expression E2. 12860 if (SemaRef.getLangOpts().CPlusPlus17) 12861 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12862 else { 12863 Visit(BO->getLHS()); 12864 Visit(BO->getRHS()); 12865 } 12866 } 12867 12868 void VisitBinComma(const BinaryOperator *BO) { 12869 // C++11 [expr.comma]p1: 12870 // Every value computation and side effect associated with the left 12871 // expression is sequenced before every value computation and side 12872 // effect associated with the right expression. 12873 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12874 } 12875 12876 void VisitBinAssign(const BinaryOperator *BO) { 12877 SequenceTree::Seq RHSRegion; 12878 SequenceTree::Seq LHSRegion; 12879 if (SemaRef.getLangOpts().CPlusPlus17) { 12880 RHSRegion = Tree.allocate(Region); 12881 LHSRegion = Tree.allocate(Region); 12882 } else { 12883 RHSRegion = Region; 12884 LHSRegion = Region; 12885 } 12886 SequenceTree::Seq OldRegion = Region; 12887 12888 // C++11 [expr.ass]p1: 12889 // [...] the assignment is sequenced after the value computation 12890 // of the right and left operands, [...] 12891 // 12892 // so check it before inspecting the operands and update the 12893 // map afterwards. 12894 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12895 if (O) 12896 notePreMod(O, BO); 12897 12898 if (SemaRef.getLangOpts().CPlusPlus17) { 12899 // C++17 [expr.ass]p1: 12900 // [...] The right operand is sequenced before the left operand. [...] 12901 { 12902 SequencedSubexpression SeqBefore(*this); 12903 Region = RHSRegion; 12904 Visit(BO->getRHS()); 12905 } 12906 12907 Region = LHSRegion; 12908 Visit(BO->getLHS()); 12909 12910 if (O && isa<CompoundAssignOperator>(BO)) 12911 notePostUse(O, BO); 12912 12913 } else { 12914 // C++11 does not specify any sequencing between the LHS and RHS. 12915 Region = LHSRegion; 12916 Visit(BO->getLHS()); 12917 12918 if (O && isa<CompoundAssignOperator>(BO)) 12919 notePostUse(O, BO); 12920 12921 Region = RHSRegion; 12922 Visit(BO->getRHS()); 12923 } 12924 12925 // C++11 [expr.ass]p1: 12926 // the assignment is sequenced [...] before the value computation of the 12927 // assignment expression. 12928 // C11 6.5.16/3 has no such rule. 12929 Region = OldRegion; 12930 if (O) 12931 notePostMod(O, BO, 12932 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12933 : UK_ModAsSideEffect); 12934 if (SemaRef.getLangOpts().CPlusPlus17) { 12935 Tree.merge(RHSRegion); 12936 Tree.merge(LHSRegion); 12937 } 12938 } 12939 12940 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12941 VisitBinAssign(CAO); 12942 } 12943 12944 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12945 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12946 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12947 Object O = getObject(UO->getSubExpr(), true); 12948 if (!O) 12949 return VisitExpr(UO); 12950 12951 notePreMod(O, UO); 12952 Visit(UO->getSubExpr()); 12953 // C++11 [expr.pre.incr]p1: 12954 // the expression ++x is equivalent to x+=1 12955 notePostMod(O, UO, 12956 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12957 : UK_ModAsSideEffect); 12958 } 12959 12960 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12961 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12962 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12963 Object O = getObject(UO->getSubExpr(), true); 12964 if (!O) 12965 return VisitExpr(UO); 12966 12967 notePreMod(O, UO); 12968 Visit(UO->getSubExpr()); 12969 notePostMod(O, UO, UK_ModAsSideEffect); 12970 } 12971 12972 void VisitBinLOr(const BinaryOperator *BO) { 12973 // C++11 [expr.log.or]p2: 12974 // If the second expression is evaluated, every value computation and 12975 // side effect associated with the first expression is sequenced before 12976 // every value computation and side effect associated with the 12977 // second expression. 12978 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12979 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12980 SequenceTree::Seq OldRegion = Region; 12981 12982 EvaluationTracker Eval(*this); 12983 { 12984 SequencedSubexpression Sequenced(*this); 12985 Region = LHSRegion; 12986 Visit(BO->getLHS()); 12987 } 12988 12989 // C++11 [expr.log.or]p1: 12990 // [...] the second operand is not evaluated if the first operand 12991 // evaluates to true. 12992 bool EvalResult = false; 12993 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12994 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12995 if (ShouldVisitRHS) { 12996 Region = RHSRegion; 12997 Visit(BO->getRHS()); 12998 } 12999 13000 Region = OldRegion; 13001 Tree.merge(LHSRegion); 13002 Tree.merge(RHSRegion); 13003 } 13004 13005 void VisitBinLAnd(const BinaryOperator *BO) { 13006 // C++11 [expr.log.and]p2: 13007 // If the second expression is evaluated, every value computation and 13008 // side effect associated with the first expression is sequenced before 13009 // every value computation and side effect associated with the 13010 // second expression. 13011 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13012 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13013 SequenceTree::Seq OldRegion = Region; 13014 13015 EvaluationTracker Eval(*this); 13016 { 13017 SequencedSubexpression Sequenced(*this); 13018 Region = LHSRegion; 13019 Visit(BO->getLHS()); 13020 } 13021 13022 // C++11 [expr.log.and]p1: 13023 // [...] the second operand is not evaluated if the first operand is false. 13024 bool EvalResult = false; 13025 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13026 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13027 if (ShouldVisitRHS) { 13028 Region = RHSRegion; 13029 Visit(BO->getRHS()); 13030 } 13031 13032 Region = OldRegion; 13033 Tree.merge(LHSRegion); 13034 Tree.merge(RHSRegion); 13035 } 13036 13037 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13038 // C++11 [expr.cond]p1: 13039 // [...] Every value computation and side effect associated with the first 13040 // expression is sequenced before every value computation and side effect 13041 // associated with the second or third expression. 13042 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13043 13044 // No sequencing is specified between the true and false expression. 13045 // However since exactly one of both is going to be evaluated we can 13046 // consider them to be sequenced. This is needed to avoid warning on 13047 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13048 // both the true and false expressions because we can't evaluate x. 13049 // This will still allow us to detect an expression like (pre C++17) 13050 // "(x ? y += 1 : y += 2) = y". 13051 // 13052 // We don't wrap the visitation of the true and false expression with 13053 // SequencedSubexpression because we don't want to downgrade modifications 13054 // as side effect in the true and false expressions after the visition 13055 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13056 // not warn between the two "y++", but we should warn between the "y++" 13057 // and the "y". 13058 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13059 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13060 SequenceTree::Seq OldRegion = Region; 13061 13062 EvaluationTracker Eval(*this); 13063 { 13064 SequencedSubexpression Sequenced(*this); 13065 Region = ConditionRegion; 13066 Visit(CO->getCond()); 13067 } 13068 13069 // C++11 [expr.cond]p1: 13070 // [...] The first expression is contextually converted to bool (Clause 4). 13071 // It is evaluated and if it is true, the result of the conditional 13072 // expression is the value of the second expression, otherwise that of the 13073 // third expression. Only one of the second and third expressions is 13074 // evaluated. [...] 13075 bool EvalResult = false; 13076 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13077 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13078 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13079 if (ShouldVisitTrueExpr) { 13080 Region = TrueRegion; 13081 Visit(CO->getTrueExpr()); 13082 } 13083 if (ShouldVisitFalseExpr) { 13084 Region = FalseRegion; 13085 Visit(CO->getFalseExpr()); 13086 } 13087 13088 Region = OldRegion; 13089 Tree.merge(ConditionRegion); 13090 Tree.merge(TrueRegion); 13091 Tree.merge(FalseRegion); 13092 } 13093 13094 void VisitCallExpr(const CallExpr *CE) { 13095 // C++11 [intro.execution]p15: 13096 // When calling a function [...], every value computation and side effect 13097 // associated with any argument expression, or with the postfix expression 13098 // designating the called function, is sequenced before execution of every 13099 // expression or statement in the body of the function [and thus before 13100 // the value computation of its result]. 13101 SequencedSubexpression Sequenced(*this); 13102 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 13103 [&] { Base::VisitCallExpr(CE); }); 13104 13105 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13106 } 13107 13108 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13109 // This is a call, so all subexpressions are sequenced before the result. 13110 SequencedSubexpression Sequenced(*this); 13111 13112 if (!CCE->isListInitialization()) 13113 return VisitExpr(CCE); 13114 13115 // In C++11, list initializations are sequenced. 13116 SmallVector<SequenceTree::Seq, 32> Elts; 13117 SequenceTree::Seq Parent = Region; 13118 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13119 E = CCE->arg_end(); 13120 I != E; ++I) { 13121 Region = Tree.allocate(Parent); 13122 Elts.push_back(Region); 13123 Visit(*I); 13124 } 13125 13126 // Forget that the initializers are sequenced. 13127 Region = Parent; 13128 for (unsigned I = 0; I < Elts.size(); ++I) 13129 Tree.merge(Elts[I]); 13130 } 13131 13132 void VisitInitListExpr(const InitListExpr *ILE) { 13133 if (!SemaRef.getLangOpts().CPlusPlus11) 13134 return VisitExpr(ILE); 13135 13136 // In C++11, list initializations are sequenced. 13137 SmallVector<SequenceTree::Seq, 32> Elts; 13138 SequenceTree::Seq Parent = Region; 13139 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13140 const Expr *E = ILE->getInit(I); 13141 if (!E) 13142 continue; 13143 Region = Tree.allocate(Parent); 13144 Elts.push_back(Region); 13145 Visit(E); 13146 } 13147 13148 // Forget that the initializers are sequenced. 13149 Region = Parent; 13150 for (unsigned I = 0; I < Elts.size(); ++I) 13151 Tree.merge(Elts[I]); 13152 } 13153 }; 13154 13155 } // namespace 13156 13157 void Sema::CheckUnsequencedOperations(const Expr *E) { 13158 SmallVector<const Expr *, 8> WorkList; 13159 WorkList.push_back(E); 13160 while (!WorkList.empty()) { 13161 const Expr *Item = WorkList.pop_back_val(); 13162 SequenceChecker(*this, Item, WorkList); 13163 } 13164 } 13165 13166 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13167 bool IsConstexpr) { 13168 llvm::SaveAndRestore<bool> ConstantContext( 13169 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13170 CheckImplicitConversions(E, CheckLoc); 13171 if (!E->isInstantiationDependent()) 13172 CheckUnsequencedOperations(E); 13173 if (!IsConstexpr && !E->isValueDependent()) 13174 CheckForIntOverflow(E); 13175 DiagnoseMisalignedMembers(); 13176 } 13177 13178 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13179 FieldDecl *BitField, 13180 Expr *Init) { 13181 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13182 } 13183 13184 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13185 SourceLocation Loc) { 13186 if (!PType->isVariablyModifiedType()) 13187 return; 13188 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13189 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13190 return; 13191 } 13192 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13193 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13194 return; 13195 } 13196 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13197 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13198 return; 13199 } 13200 13201 const ArrayType *AT = S.Context.getAsArrayType(PType); 13202 if (!AT) 13203 return; 13204 13205 if (AT->getSizeModifier() != ArrayType::Star) { 13206 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13207 return; 13208 } 13209 13210 S.Diag(Loc, diag::err_array_star_in_function_definition); 13211 } 13212 13213 /// CheckParmsForFunctionDef - Check that the parameters of the given 13214 /// function are appropriate for the definition of a function. This 13215 /// takes care of any checks that cannot be performed on the 13216 /// declaration itself, e.g., that the types of each of the function 13217 /// parameters are complete. 13218 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13219 bool CheckParameterNames) { 13220 bool HasInvalidParm = false; 13221 for (ParmVarDecl *Param : Parameters) { 13222 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13223 // function declarator that is part of a function definition of 13224 // that function shall not have incomplete type. 13225 // 13226 // This is also C++ [dcl.fct]p6. 13227 if (!Param->isInvalidDecl() && 13228 RequireCompleteType(Param->getLocation(), Param->getType(), 13229 diag::err_typecheck_decl_incomplete_type)) { 13230 Param->setInvalidDecl(); 13231 HasInvalidParm = true; 13232 } 13233 13234 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13235 // declaration of each parameter shall include an identifier. 13236 if (CheckParameterNames && 13237 Param->getIdentifier() == nullptr && 13238 !Param->isImplicit() && 13239 !getLangOpts().CPlusPlus) 13240 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13241 13242 // C99 6.7.5.3p12: 13243 // If the function declarator is not part of a definition of that 13244 // function, parameters may have incomplete type and may use the [*] 13245 // notation in their sequences of declarator specifiers to specify 13246 // variable length array types. 13247 QualType PType = Param->getOriginalType(); 13248 // FIXME: This diagnostic should point the '[*]' if source-location 13249 // information is added for it. 13250 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13251 13252 // If the parameter is a c++ class type and it has to be destructed in the 13253 // callee function, declare the destructor so that it can be called by the 13254 // callee function. Do not perform any direct access check on the dtor here. 13255 if (!Param->isInvalidDecl()) { 13256 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13257 if (!ClassDecl->isInvalidDecl() && 13258 !ClassDecl->hasIrrelevantDestructor() && 13259 !ClassDecl->isDependentContext() && 13260 ClassDecl->isParamDestroyedInCallee()) { 13261 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13262 MarkFunctionReferenced(Param->getLocation(), Destructor); 13263 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13264 } 13265 } 13266 } 13267 13268 // Parameters with the pass_object_size attribute only need to be marked 13269 // constant at function definitions. Because we lack information about 13270 // whether we're on a declaration or definition when we're instantiating the 13271 // attribute, we need to check for constness here. 13272 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13273 if (!Param->getType().isConstQualified()) 13274 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13275 << Attr->getSpelling() << 1; 13276 13277 // Check for parameter names shadowing fields from the class. 13278 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13279 // The owning context for the parameter should be the function, but we 13280 // want to see if this function's declaration context is a record. 13281 DeclContext *DC = Param->getDeclContext(); 13282 if (DC && DC->isFunctionOrMethod()) { 13283 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13284 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13285 RD, /*DeclIsField*/ false); 13286 } 13287 } 13288 } 13289 13290 return HasInvalidParm; 13291 } 13292 13293 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 13294 /// or MemberExpr. 13295 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 13296 ASTContext &Context) { 13297 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 13298 return Context.getDeclAlign(DRE->getDecl()); 13299 13300 if (const auto *ME = dyn_cast<MemberExpr>(E)) 13301 return Context.getDeclAlign(ME->getMemberDecl()); 13302 13303 return TypeAlign; 13304 } 13305 13306 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13307 /// pointer cast increases the alignment requirements. 13308 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13309 // This is actually a lot of work to potentially be doing on every 13310 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13311 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13312 return; 13313 13314 // Ignore dependent types. 13315 if (T->isDependentType() || Op->getType()->isDependentType()) 13316 return; 13317 13318 // Require that the destination be a pointer type. 13319 const PointerType *DestPtr = T->getAs<PointerType>(); 13320 if (!DestPtr) return; 13321 13322 // If the destination has alignment 1, we're done. 13323 QualType DestPointee = DestPtr->getPointeeType(); 13324 if (DestPointee->isIncompleteType()) return; 13325 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13326 if (DestAlign.isOne()) return; 13327 13328 // Require that the source be a pointer type. 13329 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13330 if (!SrcPtr) return; 13331 QualType SrcPointee = SrcPtr->getPointeeType(); 13332 13333 // Whitelist casts from cv void*. We already implicitly 13334 // whitelisted casts to cv void*, since they have alignment 1. 13335 // Also whitelist casts involving incomplete types, which implicitly 13336 // includes 'void'. 13337 if (SrcPointee->isIncompleteType()) return; 13338 13339 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 13340 13341 if (auto *CE = dyn_cast<CastExpr>(Op)) { 13342 if (CE->getCastKind() == CK_ArrayToPointerDecay) 13343 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 13344 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 13345 if (UO->getOpcode() == UO_AddrOf) 13346 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 13347 } 13348 13349 if (SrcAlign >= DestAlign) return; 13350 13351 Diag(TRange.getBegin(), diag::warn_cast_align) 13352 << Op->getType() << T 13353 << static_cast<unsigned>(SrcAlign.getQuantity()) 13354 << static_cast<unsigned>(DestAlign.getQuantity()) 13355 << TRange << Op->getSourceRange(); 13356 } 13357 13358 /// Check whether this array fits the idiom of a size-one tail padded 13359 /// array member of a struct. 13360 /// 13361 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13362 /// commonly used to emulate flexible arrays in C89 code. 13363 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13364 const NamedDecl *ND) { 13365 if (Size != 1 || !ND) return false; 13366 13367 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13368 if (!FD) return false; 13369 13370 // Don't consider sizes resulting from macro expansions or template argument 13371 // substitution to form C89 tail-padded arrays. 13372 13373 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13374 while (TInfo) { 13375 TypeLoc TL = TInfo->getTypeLoc(); 13376 // Look through typedefs. 13377 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13378 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13379 TInfo = TDL->getTypeSourceInfo(); 13380 continue; 13381 } 13382 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13383 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13384 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13385 return false; 13386 } 13387 break; 13388 } 13389 13390 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13391 if (!RD) return false; 13392 if (RD->isUnion()) return false; 13393 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13394 if (!CRD->isStandardLayout()) return false; 13395 } 13396 13397 // See if this is the last field decl in the record. 13398 const Decl *D = FD; 13399 while ((D = D->getNextDeclInContext())) 13400 if (isa<FieldDecl>(D)) 13401 return false; 13402 return true; 13403 } 13404 13405 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13406 const ArraySubscriptExpr *ASE, 13407 bool AllowOnePastEnd, bool IndexNegated) { 13408 // Already diagnosed by the constant evaluator. 13409 if (isConstantEvaluated()) 13410 return; 13411 13412 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13413 if (IndexExpr->isValueDependent()) 13414 return; 13415 13416 const Type *EffectiveType = 13417 BaseExpr->getType()->getPointeeOrArrayElementType(); 13418 BaseExpr = BaseExpr->IgnoreParenCasts(); 13419 const ConstantArrayType *ArrayTy = 13420 Context.getAsConstantArrayType(BaseExpr->getType()); 13421 13422 if (!ArrayTy) 13423 return; 13424 13425 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13426 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13427 return; 13428 13429 Expr::EvalResult Result; 13430 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13431 return; 13432 13433 llvm::APSInt index = Result.Val.getInt(); 13434 if (IndexNegated) 13435 index = -index; 13436 13437 const NamedDecl *ND = nullptr; 13438 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13439 ND = DRE->getDecl(); 13440 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13441 ND = ME->getMemberDecl(); 13442 13443 if (index.isUnsigned() || !index.isNegative()) { 13444 // It is possible that the type of the base expression after 13445 // IgnoreParenCasts is incomplete, even though the type of the base 13446 // expression before IgnoreParenCasts is complete (see PR39746 for an 13447 // example). In this case we have no information about whether the array 13448 // access exceeds the array bounds. However we can still diagnose an array 13449 // access which precedes the array bounds. 13450 if (BaseType->isIncompleteType()) 13451 return; 13452 13453 llvm::APInt size = ArrayTy->getSize(); 13454 if (!size.isStrictlyPositive()) 13455 return; 13456 13457 if (BaseType != EffectiveType) { 13458 // Make sure we're comparing apples to apples when comparing index to size 13459 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13460 uint64_t array_typesize = Context.getTypeSize(BaseType); 13461 // Handle ptrarith_typesize being zero, such as when casting to void* 13462 if (!ptrarith_typesize) ptrarith_typesize = 1; 13463 if (ptrarith_typesize != array_typesize) { 13464 // There's a cast to a different size type involved 13465 uint64_t ratio = array_typesize / ptrarith_typesize; 13466 // TODO: Be smarter about handling cases where array_typesize is not a 13467 // multiple of ptrarith_typesize 13468 if (ptrarith_typesize * ratio == array_typesize) 13469 size *= llvm::APInt(size.getBitWidth(), ratio); 13470 } 13471 } 13472 13473 if (size.getBitWidth() > index.getBitWidth()) 13474 index = index.zext(size.getBitWidth()); 13475 else if (size.getBitWidth() < index.getBitWidth()) 13476 size = size.zext(index.getBitWidth()); 13477 13478 // For array subscripting the index must be less than size, but for pointer 13479 // arithmetic also allow the index (offset) to be equal to size since 13480 // computing the next address after the end of the array is legal and 13481 // commonly done e.g. in C++ iterators and range-based for loops. 13482 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13483 return; 13484 13485 // Also don't warn for arrays of size 1 which are members of some 13486 // structure. These are often used to approximate flexible arrays in C89 13487 // code. 13488 if (IsTailPaddedMemberArray(*this, size, ND)) 13489 return; 13490 13491 // Suppress the warning if the subscript expression (as identified by the 13492 // ']' location) and the index expression are both from macro expansions 13493 // within a system header. 13494 if (ASE) { 13495 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13496 ASE->getRBracketLoc()); 13497 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13498 SourceLocation IndexLoc = 13499 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13500 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13501 return; 13502 } 13503 } 13504 13505 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13506 if (ASE) 13507 DiagID = diag::warn_array_index_exceeds_bounds; 13508 13509 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13510 PDiag(DiagID) << index.toString(10, true) 13511 << size.toString(10, true) 13512 << (unsigned)size.getLimitedValue(~0U) 13513 << IndexExpr->getSourceRange()); 13514 } else { 13515 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13516 if (!ASE) { 13517 DiagID = diag::warn_ptr_arith_precedes_bounds; 13518 if (index.isNegative()) index = -index; 13519 } 13520 13521 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13522 PDiag(DiagID) << index.toString(10, true) 13523 << IndexExpr->getSourceRange()); 13524 } 13525 13526 if (!ND) { 13527 // Try harder to find a NamedDecl to point at in the note. 13528 while (const ArraySubscriptExpr *ASE = 13529 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13530 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13531 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13532 ND = DRE->getDecl(); 13533 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13534 ND = ME->getMemberDecl(); 13535 } 13536 13537 if (ND) 13538 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13539 PDiag(diag::note_array_declared_here) 13540 << ND->getDeclName()); 13541 } 13542 13543 void Sema::CheckArrayAccess(const Expr *expr) { 13544 int AllowOnePastEnd = 0; 13545 while (expr) { 13546 expr = expr->IgnoreParenImpCasts(); 13547 switch (expr->getStmtClass()) { 13548 case Stmt::ArraySubscriptExprClass: { 13549 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13550 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13551 AllowOnePastEnd > 0); 13552 expr = ASE->getBase(); 13553 break; 13554 } 13555 case Stmt::MemberExprClass: { 13556 expr = cast<MemberExpr>(expr)->getBase(); 13557 break; 13558 } 13559 case Stmt::OMPArraySectionExprClass: { 13560 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13561 if (ASE->getLowerBound()) 13562 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13563 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13564 return; 13565 } 13566 case Stmt::UnaryOperatorClass: { 13567 // Only unwrap the * and & unary operators 13568 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13569 expr = UO->getSubExpr(); 13570 switch (UO->getOpcode()) { 13571 case UO_AddrOf: 13572 AllowOnePastEnd++; 13573 break; 13574 case UO_Deref: 13575 AllowOnePastEnd--; 13576 break; 13577 default: 13578 return; 13579 } 13580 break; 13581 } 13582 case Stmt::ConditionalOperatorClass: { 13583 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13584 if (const Expr *lhs = cond->getLHS()) 13585 CheckArrayAccess(lhs); 13586 if (const Expr *rhs = cond->getRHS()) 13587 CheckArrayAccess(rhs); 13588 return; 13589 } 13590 case Stmt::CXXOperatorCallExprClass: { 13591 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13592 for (const auto *Arg : OCE->arguments()) 13593 CheckArrayAccess(Arg); 13594 return; 13595 } 13596 default: 13597 return; 13598 } 13599 } 13600 } 13601 13602 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13603 13604 namespace { 13605 13606 struct RetainCycleOwner { 13607 VarDecl *Variable = nullptr; 13608 SourceRange Range; 13609 SourceLocation Loc; 13610 bool Indirect = false; 13611 13612 RetainCycleOwner() = default; 13613 13614 void setLocsFrom(Expr *e) { 13615 Loc = e->getExprLoc(); 13616 Range = e->getSourceRange(); 13617 } 13618 }; 13619 13620 } // namespace 13621 13622 /// Consider whether capturing the given variable can possibly lead to 13623 /// a retain cycle. 13624 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13625 // In ARC, it's captured strongly iff the variable has __strong 13626 // lifetime. In MRR, it's captured strongly if the variable is 13627 // __block and has an appropriate type. 13628 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13629 return false; 13630 13631 owner.Variable = var; 13632 if (ref) 13633 owner.setLocsFrom(ref); 13634 return true; 13635 } 13636 13637 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13638 while (true) { 13639 e = e->IgnoreParens(); 13640 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13641 switch (cast->getCastKind()) { 13642 case CK_BitCast: 13643 case CK_LValueBitCast: 13644 case CK_LValueToRValue: 13645 case CK_ARCReclaimReturnedObject: 13646 e = cast->getSubExpr(); 13647 continue; 13648 13649 default: 13650 return false; 13651 } 13652 } 13653 13654 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13655 ObjCIvarDecl *ivar = ref->getDecl(); 13656 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13657 return false; 13658 13659 // Try to find a retain cycle in the base. 13660 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13661 return false; 13662 13663 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13664 owner.Indirect = true; 13665 return true; 13666 } 13667 13668 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13669 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13670 if (!var) return false; 13671 return considerVariable(var, ref, owner); 13672 } 13673 13674 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13675 if (member->isArrow()) return false; 13676 13677 // Don't count this as an indirect ownership. 13678 e = member->getBase(); 13679 continue; 13680 } 13681 13682 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13683 // Only pay attention to pseudo-objects on property references. 13684 ObjCPropertyRefExpr *pre 13685 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13686 ->IgnoreParens()); 13687 if (!pre) return false; 13688 if (pre->isImplicitProperty()) return false; 13689 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13690 if (!property->isRetaining() && 13691 !(property->getPropertyIvarDecl() && 13692 property->getPropertyIvarDecl()->getType() 13693 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13694 return false; 13695 13696 owner.Indirect = true; 13697 if (pre->isSuperReceiver()) { 13698 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13699 if (!owner.Variable) 13700 return false; 13701 owner.Loc = pre->getLocation(); 13702 owner.Range = pre->getSourceRange(); 13703 return true; 13704 } 13705 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13706 ->getSourceExpr()); 13707 continue; 13708 } 13709 13710 // Array ivars? 13711 13712 return false; 13713 } 13714 } 13715 13716 namespace { 13717 13718 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13719 ASTContext &Context; 13720 VarDecl *Variable; 13721 Expr *Capturer = nullptr; 13722 bool VarWillBeReased = false; 13723 13724 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13725 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13726 Context(Context), Variable(variable) {} 13727 13728 void VisitDeclRefExpr(DeclRefExpr *ref) { 13729 if (ref->getDecl() == Variable && !Capturer) 13730 Capturer = ref; 13731 } 13732 13733 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13734 if (Capturer) return; 13735 Visit(ref->getBase()); 13736 if (Capturer && ref->isFreeIvar()) 13737 Capturer = ref; 13738 } 13739 13740 void VisitBlockExpr(BlockExpr *block) { 13741 // Look inside nested blocks 13742 if (block->getBlockDecl()->capturesVariable(Variable)) 13743 Visit(block->getBlockDecl()->getBody()); 13744 } 13745 13746 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13747 if (Capturer) return; 13748 if (OVE->getSourceExpr()) 13749 Visit(OVE->getSourceExpr()); 13750 } 13751 13752 void VisitBinaryOperator(BinaryOperator *BinOp) { 13753 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13754 return; 13755 Expr *LHS = BinOp->getLHS(); 13756 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13757 if (DRE->getDecl() != Variable) 13758 return; 13759 if (Expr *RHS = BinOp->getRHS()) { 13760 RHS = RHS->IgnoreParenCasts(); 13761 llvm::APSInt Value; 13762 VarWillBeReased = 13763 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13764 } 13765 } 13766 } 13767 }; 13768 13769 } // namespace 13770 13771 /// Check whether the given argument is a block which captures a 13772 /// variable. 13773 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13774 assert(owner.Variable && owner.Loc.isValid()); 13775 13776 e = e->IgnoreParenCasts(); 13777 13778 // Look through [^{...} copy] and Block_copy(^{...}). 13779 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13780 Selector Cmd = ME->getSelector(); 13781 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13782 e = ME->getInstanceReceiver(); 13783 if (!e) 13784 return nullptr; 13785 e = e->IgnoreParenCasts(); 13786 } 13787 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13788 if (CE->getNumArgs() == 1) { 13789 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13790 if (Fn) { 13791 const IdentifierInfo *FnI = Fn->getIdentifier(); 13792 if (FnI && FnI->isStr("_Block_copy")) { 13793 e = CE->getArg(0)->IgnoreParenCasts(); 13794 } 13795 } 13796 } 13797 } 13798 13799 BlockExpr *block = dyn_cast<BlockExpr>(e); 13800 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13801 return nullptr; 13802 13803 FindCaptureVisitor visitor(S.Context, owner.Variable); 13804 visitor.Visit(block->getBlockDecl()->getBody()); 13805 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13806 } 13807 13808 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13809 RetainCycleOwner &owner) { 13810 assert(capturer); 13811 assert(owner.Variable && owner.Loc.isValid()); 13812 13813 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13814 << owner.Variable << capturer->getSourceRange(); 13815 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13816 << owner.Indirect << owner.Range; 13817 } 13818 13819 /// Check for a keyword selector that starts with the word 'add' or 13820 /// 'set'. 13821 static bool isSetterLikeSelector(Selector sel) { 13822 if (sel.isUnarySelector()) return false; 13823 13824 StringRef str = sel.getNameForSlot(0); 13825 while (!str.empty() && str.front() == '_') str = str.substr(1); 13826 if (str.startswith("set")) 13827 str = str.substr(3); 13828 else if (str.startswith("add")) { 13829 // Specially whitelist 'addOperationWithBlock:'. 13830 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13831 return false; 13832 str = str.substr(3); 13833 } 13834 else 13835 return false; 13836 13837 if (str.empty()) return true; 13838 return !isLowercase(str.front()); 13839 } 13840 13841 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13842 ObjCMessageExpr *Message) { 13843 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13844 Message->getReceiverInterface(), 13845 NSAPI::ClassId_NSMutableArray); 13846 if (!IsMutableArray) { 13847 return None; 13848 } 13849 13850 Selector Sel = Message->getSelector(); 13851 13852 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13853 S.NSAPIObj->getNSArrayMethodKind(Sel); 13854 if (!MKOpt) { 13855 return None; 13856 } 13857 13858 NSAPI::NSArrayMethodKind MK = *MKOpt; 13859 13860 switch (MK) { 13861 case NSAPI::NSMutableArr_addObject: 13862 case NSAPI::NSMutableArr_insertObjectAtIndex: 13863 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13864 return 0; 13865 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13866 return 1; 13867 13868 default: 13869 return None; 13870 } 13871 13872 return None; 13873 } 13874 13875 static 13876 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13877 ObjCMessageExpr *Message) { 13878 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13879 Message->getReceiverInterface(), 13880 NSAPI::ClassId_NSMutableDictionary); 13881 if (!IsMutableDictionary) { 13882 return None; 13883 } 13884 13885 Selector Sel = Message->getSelector(); 13886 13887 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13888 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13889 if (!MKOpt) { 13890 return None; 13891 } 13892 13893 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13894 13895 switch (MK) { 13896 case NSAPI::NSMutableDict_setObjectForKey: 13897 case NSAPI::NSMutableDict_setValueForKey: 13898 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13899 return 0; 13900 13901 default: 13902 return None; 13903 } 13904 13905 return None; 13906 } 13907 13908 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13909 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13910 Message->getReceiverInterface(), 13911 NSAPI::ClassId_NSMutableSet); 13912 13913 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13914 Message->getReceiverInterface(), 13915 NSAPI::ClassId_NSMutableOrderedSet); 13916 if (!IsMutableSet && !IsMutableOrderedSet) { 13917 return None; 13918 } 13919 13920 Selector Sel = Message->getSelector(); 13921 13922 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13923 if (!MKOpt) { 13924 return None; 13925 } 13926 13927 NSAPI::NSSetMethodKind MK = *MKOpt; 13928 13929 switch (MK) { 13930 case NSAPI::NSMutableSet_addObject: 13931 case NSAPI::NSOrderedSet_setObjectAtIndex: 13932 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13933 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13934 return 0; 13935 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13936 return 1; 13937 } 13938 13939 return None; 13940 } 13941 13942 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13943 if (!Message->isInstanceMessage()) { 13944 return; 13945 } 13946 13947 Optional<int> ArgOpt; 13948 13949 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13950 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13951 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13952 return; 13953 } 13954 13955 int ArgIndex = *ArgOpt; 13956 13957 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13958 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13959 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13960 } 13961 13962 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13963 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13964 if (ArgRE->isObjCSelfExpr()) { 13965 Diag(Message->getSourceRange().getBegin(), 13966 diag::warn_objc_circular_container) 13967 << ArgRE->getDecl() << StringRef("'super'"); 13968 } 13969 } 13970 } else { 13971 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13972 13973 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13974 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13975 } 13976 13977 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13978 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13979 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13980 ValueDecl *Decl = ReceiverRE->getDecl(); 13981 Diag(Message->getSourceRange().getBegin(), 13982 diag::warn_objc_circular_container) 13983 << Decl << Decl; 13984 if (!ArgRE->isObjCSelfExpr()) { 13985 Diag(Decl->getLocation(), 13986 diag::note_objc_circular_container_declared_here) 13987 << Decl; 13988 } 13989 } 13990 } 13991 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13992 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13993 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13994 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13995 Diag(Message->getSourceRange().getBegin(), 13996 diag::warn_objc_circular_container) 13997 << Decl << Decl; 13998 Diag(Decl->getLocation(), 13999 diag::note_objc_circular_container_declared_here) 14000 << Decl; 14001 } 14002 } 14003 } 14004 } 14005 } 14006 14007 /// Check a message send to see if it's likely to cause a retain cycle. 14008 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14009 // Only check instance methods whose selector looks like a setter. 14010 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14011 return; 14012 14013 // Try to find a variable that the receiver is strongly owned by. 14014 RetainCycleOwner owner; 14015 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14016 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14017 return; 14018 } else { 14019 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14020 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14021 owner.Loc = msg->getSuperLoc(); 14022 owner.Range = msg->getSuperLoc(); 14023 } 14024 14025 // Check whether the receiver is captured by any of the arguments. 14026 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14027 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14028 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14029 // noescape blocks should not be retained by the method. 14030 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14031 continue; 14032 return diagnoseRetainCycle(*this, capturer, owner); 14033 } 14034 } 14035 } 14036 14037 /// Check a property assign to see if it's likely to cause a retain cycle. 14038 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14039 RetainCycleOwner owner; 14040 if (!findRetainCycleOwner(*this, receiver, owner)) 14041 return; 14042 14043 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14044 diagnoseRetainCycle(*this, capturer, owner); 14045 } 14046 14047 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14048 RetainCycleOwner Owner; 14049 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14050 return; 14051 14052 // Because we don't have an expression for the variable, we have to set the 14053 // location explicitly here. 14054 Owner.Loc = Var->getLocation(); 14055 Owner.Range = Var->getSourceRange(); 14056 14057 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14058 diagnoseRetainCycle(*this, Capturer, Owner); 14059 } 14060 14061 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14062 Expr *RHS, bool isProperty) { 14063 // Check if RHS is an Objective-C object literal, which also can get 14064 // immediately zapped in a weak reference. Note that we explicitly 14065 // allow ObjCStringLiterals, since those are designed to never really die. 14066 RHS = RHS->IgnoreParenImpCasts(); 14067 14068 // This enum needs to match with the 'select' in 14069 // warn_objc_arc_literal_assign (off-by-1). 14070 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14071 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14072 return false; 14073 14074 S.Diag(Loc, diag::warn_arc_literal_assign) 14075 << (unsigned) Kind 14076 << (isProperty ? 0 : 1) 14077 << RHS->getSourceRange(); 14078 14079 return true; 14080 } 14081 14082 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14083 Qualifiers::ObjCLifetime LT, 14084 Expr *RHS, bool isProperty) { 14085 // Strip off any implicit cast added to get to the one ARC-specific. 14086 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14087 if (cast->getCastKind() == CK_ARCConsumeObject) { 14088 S.Diag(Loc, diag::warn_arc_retained_assign) 14089 << (LT == Qualifiers::OCL_ExplicitNone) 14090 << (isProperty ? 0 : 1) 14091 << RHS->getSourceRange(); 14092 return true; 14093 } 14094 RHS = cast->getSubExpr(); 14095 } 14096 14097 if (LT == Qualifiers::OCL_Weak && 14098 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14099 return true; 14100 14101 return false; 14102 } 14103 14104 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14105 QualType LHS, Expr *RHS) { 14106 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14107 14108 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14109 return false; 14110 14111 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14112 return true; 14113 14114 return false; 14115 } 14116 14117 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14118 Expr *LHS, Expr *RHS) { 14119 QualType LHSType; 14120 // PropertyRef on LHS type need be directly obtained from 14121 // its declaration as it has a PseudoType. 14122 ObjCPropertyRefExpr *PRE 14123 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14124 if (PRE && !PRE->isImplicitProperty()) { 14125 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14126 if (PD) 14127 LHSType = PD->getType(); 14128 } 14129 14130 if (LHSType.isNull()) 14131 LHSType = LHS->getType(); 14132 14133 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14134 14135 if (LT == Qualifiers::OCL_Weak) { 14136 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14137 getCurFunction()->markSafeWeakUse(LHS); 14138 } 14139 14140 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14141 return; 14142 14143 // FIXME. Check for other life times. 14144 if (LT != Qualifiers::OCL_None) 14145 return; 14146 14147 if (PRE) { 14148 if (PRE->isImplicitProperty()) 14149 return; 14150 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14151 if (!PD) 14152 return; 14153 14154 unsigned Attributes = PD->getPropertyAttributes(); 14155 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 14156 // when 'assign' attribute was not explicitly specified 14157 // by user, ignore it and rely on property type itself 14158 // for lifetime info. 14159 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14160 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 14161 LHSType->isObjCRetainableType()) 14162 return; 14163 14164 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14165 if (cast->getCastKind() == CK_ARCConsumeObject) { 14166 Diag(Loc, diag::warn_arc_retained_property_assign) 14167 << RHS->getSourceRange(); 14168 return; 14169 } 14170 RHS = cast->getSubExpr(); 14171 } 14172 } 14173 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 14174 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14175 return; 14176 } 14177 } 14178 } 14179 14180 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14181 14182 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14183 SourceLocation StmtLoc, 14184 const NullStmt *Body) { 14185 // Do not warn if the body is a macro that expands to nothing, e.g: 14186 // 14187 // #define CALL(x) 14188 // if (condition) 14189 // CALL(0); 14190 if (Body->hasLeadingEmptyMacro()) 14191 return false; 14192 14193 // Get line numbers of statement and body. 14194 bool StmtLineInvalid; 14195 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14196 &StmtLineInvalid); 14197 if (StmtLineInvalid) 14198 return false; 14199 14200 bool BodyLineInvalid; 14201 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14202 &BodyLineInvalid); 14203 if (BodyLineInvalid) 14204 return false; 14205 14206 // Warn if null statement and body are on the same line. 14207 if (StmtLine != BodyLine) 14208 return false; 14209 14210 return true; 14211 } 14212 14213 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14214 const Stmt *Body, 14215 unsigned DiagID) { 14216 // Since this is a syntactic check, don't emit diagnostic for template 14217 // instantiations, this just adds noise. 14218 if (CurrentInstantiationScope) 14219 return; 14220 14221 // The body should be a null statement. 14222 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14223 if (!NBody) 14224 return; 14225 14226 // Do the usual checks. 14227 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14228 return; 14229 14230 Diag(NBody->getSemiLoc(), DiagID); 14231 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14232 } 14233 14234 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14235 const Stmt *PossibleBody) { 14236 assert(!CurrentInstantiationScope); // Ensured by caller 14237 14238 SourceLocation StmtLoc; 14239 const Stmt *Body; 14240 unsigned DiagID; 14241 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14242 StmtLoc = FS->getRParenLoc(); 14243 Body = FS->getBody(); 14244 DiagID = diag::warn_empty_for_body; 14245 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14246 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14247 Body = WS->getBody(); 14248 DiagID = diag::warn_empty_while_body; 14249 } else 14250 return; // Neither `for' nor `while'. 14251 14252 // The body should be a null statement. 14253 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14254 if (!NBody) 14255 return; 14256 14257 // Skip expensive checks if diagnostic is disabled. 14258 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14259 return; 14260 14261 // Do the usual checks. 14262 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14263 return; 14264 14265 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14266 // noise level low, emit diagnostics only if for/while is followed by a 14267 // CompoundStmt, e.g.: 14268 // for (int i = 0; i < n; i++); 14269 // { 14270 // a(i); 14271 // } 14272 // or if for/while is followed by a statement with more indentation 14273 // than for/while itself: 14274 // for (int i = 0; i < n; i++); 14275 // a(i); 14276 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14277 if (!ProbableTypo) { 14278 bool BodyColInvalid; 14279 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14280 PossibleBody->getBeginLoc(), &BodyColInvalid); 14281 if (BodyColInvalid) 14282 return; 14283 14284 bool StmtColInvalid; 14285 unsigned StmtCol = 14286 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14287 if (StmtColInvalid) 14288 return; 14289 14290 if (BodyCol > StmtCol) 14291 ProbableTypo = true; 14292 } 14293 14294 if (ProbableTypo) { 14295 Diag(NBody->getSemiLoc(), DiagID); 14296 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14297 } 14298 } 14299 14300 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14301 14302 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14303 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14304 SourceLocation OpLoc) { 14305 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14306 return; 14307 14308 if (inTemplateInstantiation()) 14309 return; 14310 14311 // Strip parens and casts away. 14312 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14313 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14314 14315 // Check for a call expression 14316 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14317 if (!CE || CE->getNumArgs() != 1) 14318 return; 14319 14320 // Check for a call to std::move 14321 if (!CE->isCallToStdMove()) 14322 return; 14323 14324 // Get argument from std::move 14325 RHSExpr = CE->getArg(0); 14326 14327 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14328 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14329 14330 // Two DeclRefExpr's, check that the decls are the same. 14331 if (LHSDeclRef && RHSDeclRef) { 14332 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14333 return; 14334 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14335 RHSDeclRef->getDecl()->getCanonicalDecl()) 14336 return; 14337 14338 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14339 << LHSExpr->getSourceRange() 14340 << RHSExpr->getSourceRange(); 14341 return; 14342 } 14343 14344 // Member variables require a different approach to check for self moves. 14345 // MemberExpr's are the same if every nested MemberExpr refers to the same 14346 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14347 // the base Expr's are CXXThisExpr's. 14348 const Expr *LHSBase = LHSExpr; 14349 const Expr *RHSBase = RHSExpr; 14350 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14351 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14352 if (!LHSME || !RHSME) 14353 return; 14354 14355 while (LHSME && RHSME) { 14356 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14357 RHSME->getMemberDecl()->getCanonicalDecl()) 14358 return; 14359 14360 LHSBase = LHSME->getBase(); 14361 RHSBase = RHSME->getBase(); 14362 LHSME = dyn_cast<MemberExpr>(LHSBase); 14363 RHSME = dyn_cast<MemberExpr>(RHSBase); 14364 } 14365 14366 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14367 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14368 if (LHSDeclRef && RHSDeclRef) { 14369 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14370 return; 14371 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14372 RHSDeclRef->getDecl()->getCanonicalDecl()) 14373 return; 14374 14375 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14376 << LHSExpr->getSourceRange() 14377 << RHSExpr->getSourceRange(); 14378 return; 14379 } 14380 14381 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14382 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14383 << LHSExpr->getSourceRange() 14384 << RHSExpr->getSourceRange(); 14385 } 14386 14387 //===--- Layout compatibility ----------------------------------------------// 14388 14389 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14390 14391 /// Check if two enumeration types are layout-compatible. 14392 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14393 // C++11 [dcl.enum] p8: 14394 // Two enumeration types are layout-compatible if they have the same 14395 // underlying type. 14396 return ED1->isComplete() && ED2->isComplete() && 14397 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14398 } 14399 14400 /// Check if two fields are layout-compatible. 14401 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14402 FieldDecl *Field2) { 14403 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14404 return false; 14405 14406 if (Field1->isBitField() != Field2->isBitField()) 14407 return false; 14408 14409 if (Field1->isBitField()) { 14410 // Make sure that the bit-fields are the same length. 14411 unsigned Bits1 = Field1->getBitWidthValue(C); 14412 unsigned Bits2 = Field2->getBitWidthValue(C); 14413 14414 if (Bits1 != Bits2) 14415 return false; 14416 } 14417 14418 return true; 14419 } 14420 14421 /// Check if two standard-layout structs are layout-compatible. 14422 /// (C++11 [class.mem] p17) 14423 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14424 RecordDecl *RD2) { 14425 // If both records are C++ classes, check that base classes match. 14426 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14427 // If one of records is a CXXRecordDecl we are in C++ mode, 14428 // thus the other one is a CXXRecordDecl, too. 14429 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14430 // Check number of base classes. 14431 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14432 return false; 14433 14434 // Check the base classes. 14435 for (CXXRecordDecl::base_class_const_iterator 14436 Base1 = D1CXX->bases_begin(), 14437 BaseEnd1 = D1CXX->bases_end(), 14438 Base2 = D2CXX->bases_begin(); 14439 Base1 != BaseEnd1; 14440 ++Base1, ++Base2) { 14441 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14442 return false; 14443 } 14444 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14445 // If only RD2 is a C++ class, it should have zero base classes. 14446 if (D2CXX->getNumBases() > 0) 14447 return false; 14448 } 14449 14450 // Check the fields. 14451 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14452 Field2End = RD2->field_end(), 14453 Field1 = RD1->field_begin(), 14454 Field1End = RD1->field_end(); 14455 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14456 if (!isLayoutCompatible(C, *Field1, *Field2)) 14457 return false; 14458 } 14459 if (Field1 != Field1End || Field2 != Field2End) 14460 return false; 14461 14462 return true; 14463 } 14464 14465 /// Check if two standard-layout unions are layout-compatible. 14466 /// (C++11 [class.mem] p18) 14467 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14468 RecordDecl *RD2) { 14469 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14470 for (auto *Field2 : RD2->fields()) 14471 UnmatchedFields.insert(Field2); 14472 14473 for (auto *Field1 : RD1->fields()) { 14474 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14475 I = UnmatchedFields.begin(), 14476 E = UnmatchedFields.end(); 14477 14478 for ( ; I != E; ++I) { 14479 if (isLayoutCompatible(C, Field1, *I)) { 14480 bool Result = UnmatchedFields.erase(*I); 14481 (void) Result; 14482 assert(Result); 14483 break; 14484 } 14485 } 14486 if (I == E) 14487 return false; 14488 } 14489 14490 return UnmatchedFields.empty(); 14491 } 14492 14493 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14494 RecordDecl *RD2) { 14495 if (RD1->isUnion() != RD2->isUnion()) 14496 return false; 14497 14498 if (RD1->isUnion()) 14499 return isLayoutCompatibleUnion(C, RD1, RD2); 14500 else 14501 return isLayoutCompatibleStruct(C, RD1, RD2); 14502 } 14503 14504 /// Check if two types are layout-compatible in C++11 sense. 14505 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14506 if (T1.isNull() || T2.isNull()) 14507 return false; 14508 14509 // C++11 [basic.types] p11: 14510 // If two types T1 and T2 are the same type, then T1 and T2 are 14511 // layout-compatible types. 14512 if (C.hasSameType(T1, T2)) 14513 return true; 14514 14515 T1 = T1.getCanonicalType().getUnqualifiedType(); 14516 T2 = T2.getCanonicalType().getUnqualifiedType(); 14517 14518 const Type::TypeClass TC1 = T1->getTypeClass(); 14519 const Type::TypeClass TC2 = T2->getTypeClass(); 14520 14521 if (TC1 != TC2) 14522 return false; 14523 14524 if (TC1 == Type::Enum) { 14525 return isLayoutCompatible(C, 14526 cast<EnumType>(T1)->getDecl(), 14527 cast<EnumType>(T2)->getDecl()); 14528 } else if (TC1 == Type::Record) { 14529 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14530 return false; 14531 14532 return isLayoutCompatible(C, 14533 cast<RecordType>(T1)->getDecl(), 14534 cast<RecordType>(T2)->getDecl()); 14535 } 14536 14537 return false; 14538 } 14539 14540 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14541 14542 /// Given a type tag expression find the type tag itself. 14543 /// 14544 /// \param TypeExpr Type tag expression, as it appears in user's code. 14545 /// 14546 /// \param VD Declaration of an identifier that appears in a type tag. 14547 /// 14548 /// \param MagicValue Type tag magic value. 14549 /// 14550 /// \param isConstantEvaluated wether the evalaution should be performed in 14551 14552 /// constant context. 14553 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14554 const ValueDecl **VD, uint64_t *MagicValue, 14555 bool isConstantEvaluated) { 14556 while(true) { 14557 if (!TypeExpr) 14558 return false; 14559 14560 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14561 14562 switch (TypeExpr->getStmtClass()) { 14563 case Stmt::UnaryOperatorClass: { 14564 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14565 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14566 TypeExpr = UO->getSubExpr(); 14567 continue; 14568 } 14569 return false; 14570 } 14571 14572 case Stmt::DeclRefExprClass: { 14573 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14574 *VD = DRE->getDecl(); 14575 return true; 14576 } 14577 14578 case Stmt::IntegerLiteralClass: { 14579 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14580 llvm::APInt MagicValueAPInt = IL->getValue(); 14581 if (MagicValueAPInt.getActiveBits() <= 64) { 14582 *MagicValue = MagicValueAPInt.getZExtValue(); 14583 return true; 14584 } else 14585 return false; 14586 } 14587 14588 case Stmt::BinaryConditionalOperatorClass: 14589 case Stmt::ConditionalOperatorClass: { 14590 const AbstractConditionalOperator *ACO = 14591 cast<AbstractConditionalOperator>(TypeExpr); 14592 bool Result; 14593 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14594 isConstantEvaluated)) { 14595 if (Result) 14596 TypeExpr = ACO->getTrueExpr(); 14597 else 14598 TypeExpr = ACO->getFalseExpr(); 14599 continue; 14600 } 14601 return false; 14602 } 14603 14604 case Stmt::BinaryOperatorClass: { 14605 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14606 if (BO->getOpcode() == BO_Comma) { 14607 TypeExpr = BO->getRHS(); 14608 continue; 14609 } 14610 return false; 14611 } 14612 14613 default: 14614 return false; 14615 } 14616 } 14617 } 14618 14619 /// Retrieve the C type corresponding to type tag TypeExpr. 14620 /// 14621 /// \param TypeExpr Expression that specifies a type tag. 14622 /// 14623 /// \param MagicValues Registered magic values. 14624 /// 14625 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14626 /// kind. 14627 /// 14628 /// \param TypeInfo Information about the corresponding C type. 14629 /// 14630 /// \param isConstantEvaluated wether the evalaution should be performed in 14631 /// constant context. 14632 /// 14633 /// \returns true if the corresponding C type was found. 14634 static bool GetMatchingCType( 14635 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14636 const ASTContext &Ctx, 14637 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14638 *MagicValues, 14639 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14640 bool isConstantEvaluated) { 14641 FoundWrongKind = false; 14642 14643 // Variable declaration that has type_tag_for_datatype attribute. 14644 const ValueDecl *VD = nullptr; 14645 14646 uint64_t MagicValue; 14647 14648 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14649 return false; 14650 14651 if (VD) { 14652 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14653 if (I->getArgumentKind() != ArgumentKind) { 14654 FoundWrongKind = true; 14655 return false; 14656 } 14657 TypeInfo.Type = I->getMatchingCType(); 14658 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14659 TypeInfo.MustBeNull = I->getMustBeNull(); 14660 return true; 14661 } 14662 return false; 14663 } 14664 14665 if (!MagicValues) 14666 return false; 14667 14668 llvm::DenseMap<Sema::TypeTagMagicValue, 14669 Sema::TypeTagData>::const_iterator I = 14670 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14671 if (I == MagicValues->end()) 14672 return false; 14673 14674 TypeInfo = I->second; 14675 return true; 14676 } 14677 14678 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14679 uint64_t MagicValue, QualType Type, 14680 bool LayoutCompatible, 14681 bool MustBeNull) { 14682 if (!TypeTagForDatatypeMagicValues) 14683 TypeTagForDatatypeMagicValues.reset( 14684 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14685 14686 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14687 (*TypeTagForDatatypeMagicValues)[Magic] = 14688 TypeTagData(Type, LayoutCompatible, MustBeNull); 14689 } 14690 14691 static bool IsSameCharType(QualType T1, QualType T2) { 14692 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14693 if (!BT1) 14694 return false; 14695 14696 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14697 if (!BT2) 14698 return false; 14699 14700 BuiltinType::Kind T1Kind = BT1->getKind(); 14701 BuiltinType::Kind T2Kind = BT2->getKind(); 14702 14703 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14704 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14705 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14706 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14707 } 14708 14709 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14710 const ArrayRef<const Expr *> ExprArgs, 14711 SourceLocation CallSiteLoc) { 14712 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14713 bool IsPointerAttr = Attr->getIsPointer(); 14714 14715 // Retrieve the argument representing the 'type_tag'. 14716 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14717 if (TypeTagIdxAST >= ExprArgs.size()) { 14718 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14719 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14720 return; 14721 } 14722 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14723 bool FoundWrongKind; 14724 TypeTagData TypeInfo; 14725 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14726 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14727 TypeInfo, isConstantEvaluated())) { 14728 if (FoundWrongKind) 14729 Diag(TypeTagExpr->getExprLoc(), 14730 diag::warn_type_tag_for_datatype_wrong_kind) 14731 << TypeTagExpr->getSourceRange(); 14732 return; 14733 } 14734 14735 // Retrieve the argument representing the 'arg_idx'. 14736 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14737 if (ArgumentIdxAST >= ExprArgs.size()) { 14738 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14739 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14740 return; 14741 } 14742 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14743 if (IsPointerAttr) { 14744 // Skip implicit cast of pointer to `void *' (as a function argument). 14745 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14746 if (ICE->getType()->isVoidPointerType() && 14747 ICE->getCastKind() == CK_BitCast) 14748 ArgumentExpr = ICE->getSubExpr(); 14749 } 14750 QualType ArgumentType = ArgumentExpr->getType(); 14751 14752 // Passing a `void*' pointer shouldn't trigger a warning. 14753 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14754 return; 14755 14756 if (TypeInfo.MustBeNull) { 14757 // Type tag with matching void type requires a null pointer. 14758 if (!ArgumentExpr->isNullPointerConstant(Context, 14759 Expr::NPC_ValueDependentIsNotNull)) { 14760 Diag(ArgumentExpr->getExprLoc(), 14761 diag::warn_type_safety_null_pointer_required) 14762 << ArgumentKind->getName() 14763 << ArgumentExpr->getSourceRange() 14764 << TypeTagExpr->getSourceRange(); 14765 } 14766 return; 14767 } 14768 14769 QualType RequiredType = TypeInfo.Type; 14770 if (IsPointerAttr) 14771 RequiredType = Context.getPointerType(RequiredType); 14772 14773 bool mismatch = false; 14774 if (!TypeInfo.LayoutCompatible) { 14775 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14776 14777 // C++11 [basic.fundamental] p1: 14778 // Plain char, signed char, and unsigned char are three distinct types. 14779 // 14780 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14781 // char' depending on the current char signedness mode. 14782 if (mismatch) 14783 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14784 RequiredType->getPointeeType())) || 14785 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14786 mismatch = false; 14787 } else 14788 if (IsPointerAttr) 14789 mismatch = !isLayoutCompatible(Context, 14790 ArgumentType->getPointeeType(), 14791 RequiredType->getPointeeType()); 14792 else 14793 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14794 14795 if (mismatch) 14796 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14797 << ArgumentType << ArgumentKind 14798 << TypeInfo.LayoutCompatible << RequiredType 14799 << ArgumentExpr->getSourceRange() 14800 << TypeTagExpr->getSourceRange(); 14801 } 14802 14803 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14804 CharUnits Alignment) { 14805 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14806 } 14807 14808 void Sema::DiagnoseMisalignedMembers() { 14809 for (MisalignedMember &m : MisalignedMembers) { 14810 const NamedDecl *ND = m.RD; 14811 if (ND->getName().empty()) { 14812 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14813 ND = TD; 14814 } 14815 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14816 << m.MD << ND << m.E->getSourceRange(); 14817 } 14818 MisalignedMembers.clear(); 14819 } 14820 14821 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14822 E = E->IgnoreParens(); 14823 if (!T->isPointerType() && !T->isIntegerType()) 14824 return; 14825 if (isa<UnaryOperator>(E) && 14826 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14827 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14828 if (isa<MemberExpr>(Op)) { 14829 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14830 if (MA != MisalignedMembers.end() && 14831 (T->isIntegerType() || 14832 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14833 Context.getTypeAlignInChars( 14834 T->getPointeeType()) <= MA->Alignment)))) 14835 MisalignedMembers.erase(MA); 14836 } 14837 } 14838 } 14839 14840 void Sema::RefersToMemberWithReducedAlignment( 14841 Expr *E, 14842 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14843 Action) { 14844 const auto *ME = dyn_cast<MemberExpr>(E); 14845 if (!ME) 14846 return; 14847 14848 // No need to check expressions with an __unaligned-qualified type. 14849 if (E->getType().getQualifiers().hasUnaligned()) 14850 return; 14851 14852 // For a chain of MemberExpr like "a.b.c.d" this list 14853 // will keep FieldDecl's like [d, c, b]. 14854 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14855 const MemberExpr *TopME = nullptr; 14856 bool AnyIsPacked = false; 14857 do { 14858 QualType BaseType = ME->getBase()->getType(); 14859 if (BaseType->isDependentType()) 14860 return; 14861 if (ME->isArrow()) 14862 BaseType = BaseType->getPointeeType(); 14863 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14864 if (RD->isInvalidDecl()) 14865 return; 14866 14867 ValueDecl *MD = ME->getMemberDecl(); 14868 auto *FD = dyn_cast<FieldDecl>(MD); 14869 // We do not care about non-data members. 14870 if (!FD || FD->isInvalidDecl()) 14871 return; 14872 14873 AnyIsPacked = 14874 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14875 ReverseMemberChain.push_back(FD); 14876 14877 TopME = ME; 14878 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14879 } while (ME); 14880 assert(TopME && "We did not compute a topmost MemberExpr!"); 14881 14882 // Not the scope of this diagnostic. 14883 if (!AnyIsPacked) 14884 return; 14885 14886 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14887 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14888 // TODO: The innermost base of the member expression may be too complicated. 14889 // For now, just disregard these cases. This is left for future 14890 // improvement. 14891 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14892 return; 14893 14894 // Alignment expected by the whole expression. 14895 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14896 14897 // No need to do anything else with this case. 14898 if (ExpectedAlignment.isOne()) 14899 return; 14900 14901 // Synthesize offset of the whole access. 14902 CharUnits Offset; 14903 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14904 I++) { 14905 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14906 } 14907 14908 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14909 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14910 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14911 14912 // The base expression of the innermost MemberExpr may give 14913 // stronger guarantees than the class containing the member. 14914 if (DRE && !TopME->isArrow()) { 14915 const ValueDecl *VD = DRE->getDecl(); 14916 if (!VD->getType()->isReferenceType()) 14917 CompleteObjectAlignment = 14918 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14919 } 14920 14921 // Check if the synthesized offset fulfills the alignment. 14922 if (Offset % ExpectedAlignment != 0 || 14923 // It may fulfill the offset it but the effective alignment may still be 14924 // lower than the expected expression alignment. 14925 CompleteObjectAlignment < ExpectedAlignment) { 14926 // If this happens, we want to determine a sensible culprit of this. 14927 // Intuitively, watching the chain of member expressions from right to 14928 // left, we start with the required alignment (as required by the field 14929 // type) but some packed attribute in that chain has reduced the alignment. 14930 // It may happen that another packed structure increases it again. But if 14931 // we are here such increase has not been enough. So pointing the first 14932 // FieldDecl that either is packed or else its RecordDecl is, 14933 // seems reasonable. 14934 FieldDecl *FD = nullptr; 14935 CharUnits Alignment; 14936 for (FieldDecl *FDI : ReverseMemberChain) { 14937 if (FDI->hasAttr<PackedAttr>() || 14938 FDI->getParent()->hasAttr<PackedAttr>()) { 14939 FD = FDI; 14940 Alignment = std::min( 14941 Context.getTypeAlignInChars(FD->getType()), 14942 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14943 break; 14944 } 14945 } 14946 assert(FD && "We did not find a packed FieldDecl!"); 14947 Action(E, FD->getParent(), FD, Alignment); 14948 } 14949 } 14950 14951 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14952 using namespace std::placeholders; 14953 14954 RefersToMemberWithReducedAlignment( 14955 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14956 _2, _3, _4)); 14957 } 14958