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__opencl_atomic_fetch_min: 4646 case AtomicExpr::AO__opencl_atomic_fetch_max: 4647 case AtomicExpr::AO__atomic_fetch_add: 4648 case AtomicExpr::AO__atomic_fetch_sub: 4649 case AtomicExpr::AO__atomic_add_fetch: 4650 case AtomicExpr::AO__atomic_sub_fetch: 4651 IsAddSub = true; 4652 LLVM_FALLTHROUGH; 4653 case AtomicExpr::AO__c11_atomic_fetch_and: 4654 case AtomicExpr::AO__c11_atomic_fetch_or: 4655 case AtomicExpr::AO__c11_atomic_fetch_xor: 4656 case AtomicExpr::AO__opencl_atomic_fetch_and: 4657 case AtomicExpr::AO__opencl_atomic_fetch_or: 4658 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4659 case AtomicExpr::AO__atomic_fetch_and: 4660 case AtomicExpr::AO__atomic_fetch_or: 4661 case AtomicExpr::AO__atomic_fetch_xor: 4662 case AtomicExpr::AO__atomic_fetch_nand: 4663 case AtomicExpr::AO__atomic_and_fetch: 4664 case AtomicExpr::AO__atomic_or_fetch: 4665 case AtomicExpr::AO__atomic_xor_fetch: 4666 case AtomicExpr::AO__atomic_nand_fetch: 4667 case AtomicExpr::AO__c11_atomic_fetch_min: 4668 case AtomicExpr::AO__c11_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(OrigArg0, OrigArg1, false); 5760 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5761 return true; 5762 5763 // Make sure any conversions are pushed back into the call; this is 5764 // type safe since unordered compare builtins are declared as "_Bool 5765 // foo(...)". 5766 TheCall->setArg(0, OrigArg0.get()); 5767 TheCall->setArg(1, OrigArg1.get()); 5768 5769 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5770 return false; 5771 5772 // If the common type isn't a real floating type, then the arguments were 5773 // invalid for this operation. 5774 if (Res.isNull() || !Res->isRealFloatingType()) 5775 return Diag(OrigArg0.get()->getBeginLoc(), 5776 diag::err_typecheck_call_invalid_ordered_compare) 5777 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5778 << SourceRange(OrigArg0.get()->getBeginLoc(), 5779 OrigArg1.get()->getEndLoc()); 5780 5781 return false; 5782 } 5783 5784 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5785 /// __builtin_isnan and friends. This is declared to take (...), so we have 5786 /// to check everything. We expect the last argument to be a floating point 5787 /// value. 5788 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5789 if (TheCall->getNumArgs() < NumArgs) 5790 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5791 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5792 if (TheCall->getNumArgs() > NumArgs) 5793 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5794 diag::err_typecheck_call_too_many_args) 5795 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5796 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5797 (*(TheCall->arg_end() - 1))->getEndLoc()); 5798 5799 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5800 5801 if (OrigArg->isTypeDependent()) 5802 return false; 5803 5804 // This operation requires a non-_Complex floating-point number. 5805 if (!OrigArg->getType()->isRealFloatingType()) 5806 return Diag(OrigArg->getBeginLoc(), 5807 diag::err_typecheck_call_invalid_unary_fp) 5808 << OrigArg->getType() << OrigArg->getSourceRange(); 5809 5810 // If this is an implicit conversion from float -> float, double, or 5811 // long double, or half -> half, float, double, or long double, remove it. 5812 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5813 // Only remove standard FloatCasts, leaving other casts inplace 5814 if (Cast->getCastKind() == CK_FloatingCast) { 5815 bool IgnoreCast = false; 5816 Expr *CastArg = Cast->getSubExpr(); 5817 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5818 assert( 5819 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5820 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5821 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5822 "promotion from float to either float, double, or long double is " 5823 "the only expected cast here"); 5824 IgnoreCast = true; 5825 } else if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Half)) { 5826 assert( 5827 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5828 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5829 Cast->getType()->isSpecificBuiltinType(BuiltinType::Half) || 5830 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5831 "promotion from half to either half, float, double, or long double " 5832 "is the only expected cast here"); 5833 IgnoreCast = true; 5834 } 5835 5836 if (IgnoreCast) { 5837 Cast->setSubExpr(nullptr); 5838 TheCall->setArg(NumArgs-1, CastArg); 5839 } 5840 } 5841 } 5842 5843 return false; 5844 } 5845 5846 // Customized Sema Checking for VSX builtins that have the following signature: 5847 // vector [...] builtinName(vector [...], vector [...], const int); 5848 // Which takes the same type of vectors (any legal vector type) for the first 5849 // two arguments and takes compile time constant for the third argument. 5850 // Example builtins are : 5851 // vector double vec_xxpermdi(vector double, vector double, int); 5852 // vector short vec_xxsldwi(vector short, vector short, int); 5853 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5854 unsigned ExpectedNumArgs = 3; 5855 if (TheCall->getNumArgs() < ExpectedNumArgs) 5856 return Diag(TheCall->getEndLoc(), 5857 diag::err_typecheck_call_too_few_args_at_least) 5858 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5859 << TheCall->getSourceRange(); 5860 5861 if (TheCall->getNumArgs() > ExpectedNumArgs) 5862 return Diag(TheCall->getEndLoc(), 5863 diag::err_typecheck_call_too_many_args_at_most) 5864 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5865 << TheCall->getSourceRange(); 5866 5867 // Check the third argument is a compile time constant 5868 llvm::APSInt Value; 5869 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5870 return Diag(TheCall->getBeginLoc(), 5871 diag::err_vsx_builtin_nonconstant_argument) 5872 << 3 /* argument index */ << TheCall->getDirectCallee() 5873 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5874 TheCall->getArg(2)->getEndLoc()); 5875 5876 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5877 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5878 5879 // Check the type of argument 1 and argument 2 are vectors. 5880 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5881 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5882 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5883 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5884 << TheCall->getDirectCallee() 5885 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5886 TheCall->getArg(1)->getEndLoc()); 5887 } 5888 5889 // Check the first two arguments are the same type. 5890 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5891 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5892 << TheCall->getDirectCallee() 5893 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5894 TheCall->getArg(1)->getEndLoc()); 5895 } 5896 5897 // When default clang type checking is turned off and the customized type 5898 // checking is used, the returning type of the function must be explicitly 5899 // set. Otherwise it is _Bool by default. 5900 TheCall->setType(Arg1Ty); 5901 5902 return false; 5903 } 5904 5905 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5906 // This is declared to take (...), so we have to check everything. 5907 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5908 if (TheCall->getNumArgs() < 2) 5909 return ExprError(Diag(TheCall->getEndLoc(), 5910 diag::err_typecheck_call_too_few_args_at_least) 5911 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5912 << TheCall->getSourceRange()); 5913 5914 // Determine which of the following types of shufflevector we're checking: 5915 // 1) unary, vector mask: (lhs, mask) 5916 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5917 QualType resType = TheCall->getArg(0)->getType(); 5918 unsigned numElements = 0; 5919 5920 if (!TheCall->getArg(0)->isTypeDependent() && 5921 !TheCall->getArg(1)->isTypeDependent()) { 5922 QualType LHSType = TheCall->getArg(0)->getType(); 5923 QualType RHSType = TheCall->getArg(1)->getType(); 5924 5925 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5926 return ExprError( 5927 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5928 << TheCall->getDirectCallee() 5929 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5930 TheCall->getArg(1)->getEndLoc())); 5931 5932 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5933 unsigned numResElements = TheCall->getNumArgs() - 2; 5934 5935 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5936 // with mask. If so, verify that RHS is an integer vector type with the 5937 // same number of elts as lhs. 5938 if (TheCall->getNumArgs() == 2) { 5939 if (!RHSType->hasIntegerRepresentation() || 5940 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5941 return ExprError(Diag(TheCall->getBeginLoc(), 5942 diag::err_vec_builtin_incompatible_vector) 5943 << TheCall->getDirectCallee() 5944 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5945 TheCall->getArg(1)->getEndLoc())); 5946 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5947 return ExprError(Diag(TheCall->getBeginLoc(), 5948 diag::err_vec_builtin_incompatible_vector) 5949 << TheCall->getDirectCallee() 5950 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5951 TheCall->getArg(1)->getEndLoc())); 5952 } else if (numElements != numResElements) { 5953 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5954 resType = Context.getVectorType(eltType, numResElements, 5955 VectorType::GenericVector); 5956 } 5957 } 5958 5959 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5960 if (TheCall->getArg(i)->isTypeDependent() || 5961 TheCall->getArg(i)->isValueDependent()) 5962 continue; 5963 5964 llvm::APSInt Result(32); 5965 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5966 return ExprError(Diag(TheCall->getBeginLoc(), 5967 diag::err_shufflevector_nonconstant_argument) 5968 << TheCall->getArg(i)->getSourceRange()); 5969 5970 // Allow -1 which will be translated to undef in the IR. 5971 if (Result.isSigned() && Result.isAllOnesValue()) 5972 continue; 5973 5974 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5975 return ExprError(Diag(TheCall->getBeginLoc(), 5976 diag::err_shufflevector_argument_too_large) 5977 << TheCall->getArg(i)->getSourceRange()); 5978 } 5979 5980 SmallVector<Expr*, 32> exprs; 5981 5982 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5983 exprs.push_back(TheCall->getArg(i)); 5984 TheCall->setArg(i, nullptr); 5985 } 5986 5987 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5988 TheCall->getCallee()->getBeginLoc(), 5989 TheCall->getRParenLoc()); 5990 } 5991 5992 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5993 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5994 SourceLocation BuiltinLoc, 5995 SourceLocation RParenLoc) { 5996 ExprValueKind VK = VK_RValue; 5997 ExprObjectKind OK = OK_Ordinary; 5998 QualType DstTy = TInfo->getType(); 5999 QualType SrcTy = E->getType(); 6000 6001 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6002 return ExprError(Diag(BuiltinLoc, 6003 diag::err_convertvector_non_vector) 6004 << E->getSourceRange()); 6005 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6006 return ExprError(Diag(BuiltinLoc, 6007 diag::err_convertvector_non_vector_type)); 6008 6009 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6010 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6011 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6012 if (SrcElts != DstElts) 6013 return ExprError(Diag(BuiltinLoc, 6014 diag::err_convertvector_incompatible_vector) 6015 << E->getSourceRange()); 6016 } 6017 6018 return new (Context) 6019 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6020 } 6021 6022 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6023 // This is declared to take (const void*, ...) and can take two 6024 // optional constant int args. 6025 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6026 unsigned NumArgs = TheCall->getNumArgs(); 6027 6028 if (NumArgs > 3) 6029 return Diag(TheCall->getEndLoc(), 6030 diag::err_typecheck_call_too_many_args_at_most) 6031 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6032 6033 // Argument 0 is checked for us and the remaining arguments must be 6034 // constant integers. 6035 for (unsigned i = 1; i != NumArgs; ++i) 6036 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6037 return true; 6038 6039 return false; 6040 } 6041 6042 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6043 // __assume does not evaluate its arguments, and should warn if its argument 6044 // has side effects. 6045 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6046 Expr *Arg = TheCall->getArg(0); 6047 if (Arg->isInstantiationDependent()) return false; 6048 6049 if (Arg->HasSideEffects(Context)) 6050 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6051 << Arg->getSourceRange() 6052 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6053 6054 return false; 6055 } 6056 6057 /// Handle __builtin_alloca_with_align. This is declared 6058 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6059 /// than 8. 6060 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6061 // The alignment must be a constant integer. 6062 Expr *Arg = TheCall->getArg(1); 6063 6064 // We can't check the value of a dependent argument. 6065 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6066 if (const auto *UE = 6067 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6068 if (UE->getKind() == UETT_AlignOf || 6069 UE->getKind() == UETT_PreferredAlignOf) 6070 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6071 << Arg->getSourceRange(); 6072 6073 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6074 6075 if (!Result.isPowerOf2()) 6076 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6077 << Arg->getSourceRange(); 6078 6079 if (Result < Context.getCharWidth()) 6080 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6081 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6082 6083 if (Result > std::numeric_limits<int32_t>::max()) 6084 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6085 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6086 } 6087 6088 return false; 6089 } 6090 6091 /// Handle __builtin_assume_aligned. This is declared 6092 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6093 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6094 unsigned NumArgs = TheCall->getNumArgs(); 6095 6096 if (NumArgs > 3) 6097 return Diag(TheCall->getEndLoc(), 6098 diag::err_typecheck_call_too_many_args_at_most) 6099 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6100 6101 // The alignment must be a constant integer. 6102 Expr *Arg = TheCall->getArg(1); 6103 6104 // We can't check the value of a dependent argument. 6105 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6106 llvm::APSInt Result; 6107 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6108 return true; 6109 6110 if (!Result.isPowerOf2()) 6111 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6112 << Arg->getSourceRange(); 6113 6114 // Alignment calculations can wrap around if it's greater than 2**29. 6115 unsigned MaximumAlignment = 536870912; 6116 if (Result > MaximumAlignment) 6117 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6118 << Arg->getSourceRange() << MaximumAlignment; 6119 } 6120 6121 if (NumArgs > 2) { 6122 ExprResult Arg(TheCall->getArg(2)); 6123 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6124 Context.getSizeType(), false); 6125 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6126 if (Arg.isInvalid()) return true; 6127 TheCall->setArg(2, Arg.get()); 6128 } 6129 6130 return false; 6131 } 6132 6133 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6134 unsigned BuiltinID = 6135 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6136 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6137 6138 unsigned NumArgs = TheCall->getNumArgs(); 6139 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6140 if (NumArgs < NumRequiredArgs) { 6141 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6142 << 0 /* function call */ << NumRequiredArgs << NumArgs 6143 << TheCall->getSourceRange(); 6144 } 6145 if (NumArgs >= NumRequiredArgs + 0x100) { 6146 return Diag(TheCall->getEndLoc(), 6147 diag::err_typecheck_call_too_many_args_at_most) 6148 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6149 << TheCall->getSourceRange(); 6150 } 6151 unsigned i = 0; 6152 6153 // For formatting call, check buffer arg. 6154 if (!IsSizeCall) { 6155 ExprResult Arg(TheCall->getArg(i)); 6156 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6157 Context, Context.VoidPtrTy, false); 6158 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6159 if (Arg.isInvalid()) 6160 return true; 6161 TheCall->setArg(i, Arg.get()); 6162 i++; 6163 } 6164 6165 // Check string literal arg. 6166 unsigned FormatIdx = i; 6167 { 6168 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6169 if (Arg.isInvalid()) 6170 return true; 6171 TheCall->setArg(i, Arg.get()); 6172 i++; 6173 } 6174 6175 // Make sure variadic args are scalar. 6176 unsigned FirstDataArg = i; 6177 while (i < NumArgs) { 6178 ExprResult Arg = DefaultVariadicArgumentPromotion( 6179 TheCall->getArg(i), VariadicFunction, nullptr); 6180 if (Arg.isInvalid()) 6181 return true; 6182 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6183 if (ArgSize.getQuantity() >= 0x100) { 6184 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6185 << i << (int)ArgSize.getQuantity() << 0xff 6186 << TheCall->getSourceRange(); 6187 } 6188 TheCall->setArg(i, Arg.get()); 6189 i++; 6190 } 6191 6192 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6193 // call to avoid duplicate diagnostics. 6194 if (!IsSizeCall) { 6195 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6196 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6197 bool Success = CheckFormatArguments( 6198 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6199 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6200 CheckedVarArgs); 6201 if (!Success) 6202 return true; 6203 } 6204 6205 if (IsSizeCall) { 6206 TheCall->setType(Context.getSizeType()); 6207 } else { 6208 TheCall->setType(Context.VoidPtrTy); 6209 } 6210 return false; 6211 } 6212 6213 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6214 /// TheCall is a constant expression. 6215 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6216 llvm::APSInt &Result) { 6217 Expr *Arg = TheCall->getArg(ArgNum); 6218 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6219 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6220 6221 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6222 6223 if (!Arg->isIntegerConstantExpr(Result, Context)) 6224 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6225 << FDecl->getDeclName() << Arg->getSourceRange(); 6226 6227 return false; 6228 } 6229 6230 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6231 /// TheCall is a constant expression in the range [Low, High]. 6232 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6233 int Low, int High, bool RangeIsError) { 6234 if (isConstantEvaluated()) 6235 return false; 6236 llvm::APSInt Result; 6237 6238 // We can't check the value of a dependent argument. 6239 Expr *Arg = TheCall->getArg(ArgNum); 6240 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6241 return false; 6242 6243 // Check constant-ness first. 6244 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6245 return true; 6246 6247 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6248 if (RangeIsError) 6249 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6250 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6251 else 6252 // Defer the warning until we know if the code will be emitted so that 6253 // dead code can ignore this. 6254 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6255 PDiag(diag::warn_argument_invalid_range) 6256 << Result.toString(10) << Low << High 6257 << Arg->getSourceRange()); 6258 } 6259 6260 return false; 6261 } 6262 6263 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6264 /// TheCall is a constant expression is a multiple of Num.. 6265 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6266 unsigned Num) { 6267 llvm::APSInt Result; 6268 6269 // We can't check the value of a dependent argument. 6270 Expr *Arg = TheCall->getArg(ArgNum); 6271 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6272 return false; 6273 6274 // Check constant-ness first. 6275 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6276 return true; 6277 6278 if (Result.getSExtValue() % Num != 0) 6279 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6280 << Num << Arg->getSourceRange(); 6281 6282 return false; 6283 } 6284 6285 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6286 /// constant expression representing a power of 2. 6287 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6288 llvm::APSInt Result; 6289 6290 // We can't check the value of a dependent argument. 6291 Expr *Arg = TheCall->getArg(ArgNum); 6292 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6293 return false; 6294 6295 // Check constant-ness first. 6296 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6297 return true; 6298 6299 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6300 // and only if x is a power of 2. 6301 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6302 return false; 6303 6304 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6305 << Arg->getSourceRange(); 6306 } 6307 6308 static bool IsShiftedByte(llvm::APSInt Value) { 6309 if (Value.isNegative()) 6310 return false; 6311 6312 // Check if it's a shifted byte, by shifting it down 6313 while (true) { 6314 // If the value fits in the bottom byte, the check passes. 6315 if (Value < 0x100) 6316 return true; 6317 6318 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6319 // fails. 6320 if ((Value & 0xFF) != 0) 6321 return false; 6322 6323 // If the bottom 8 bits are all 0, but something above that is nonzero, 6324 // then shifting the value right by 8 bits won't affect whether it's a 6325 // shifted byte or not. So do that, and go round again. 6326 Value >>= 8; 6327 } 6328 } 6329 6330 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6331 /// a constant expression representing an arbitrary byte value shifted left by 6332 /// a multiple of 8 bits. 6333 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum) { 6334 llvm::APSInt Result; 6335 6336 // We can't check the value of a dependent argument. 6337 Expr *Arg = TheCall->getArg(ArgNum); 6338 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6339 return false; 6340 6341 // Check constant-ness first. 6342 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6343 return true; 6344 6345 if (IsShiftedByte(Result)) 6346 return false; 6347 6348 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6349 << Arg->getSourceRange(); 6350 } 6351 6352 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6353 /// TheCall is a constant expression representing either a shifted byte value, 6354 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6355 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6356 /// Arm MVE intrinsics. 6357 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6358 int ArgNum) { 6359 llvm::APSInt Result; 6360 6361 // We can't check the value of a dependent argument. 6362 Expr *Arg = TheCall->getArg(ArgNum); 6363 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6364 return false; 6365 6366 // Check constant-ness first. 6367 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6368 return true; 6369 6370 // Check to see if it's in either of the required forms. 6371 if (IsShiftedByte(Result) || 6372 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6373 return false; 6374 6375 return Diag(TheCall->getBeginLoc(), 6376 diag::err_argument_not_shifted_byte_or_xxff) 6377 << Arg->getSourceRange(); 6378 } 6379 6380 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6381 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6382 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6383 if (checkArgCount(*this, TheCall, 2)) 6384 return true; 6385 Expr *Arg0 = TheCall->getArg(0); 6386 Expr *Arg1 = TheCall->getArg(1); 6387 6388 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6389 if (FirstArg.isInvalid()) 6390 return true; 6391 QualType FirstArgType = FirstArg.get()->getType(); 6392 if (!FirstArgType->isAnyPointerType()) 6393 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6394 << "first" << FirstArgType << Arg0->getSourceRange(); 6395 TheCall->setArg(0, FirstArg.get()); 6396 6397 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6398 if (SecArg.isInvalid()) 6399 return true; 6400 QualType SecArgType = SecArg.get()->getType(); 6401 if (!SecArgType->isIntegerType()) 6402 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6403 << "second" << SecArgType << Arg1->getSourceRange(); 6404 6405 // Derive the return type from the pointer argument. 6406 TheCall->setType(FirstArgType); 6407 return false; 6408 } 6409 6410 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6411 if (checkArgCount(*this, TheCall, 2)) 6412 return true; 6413 6414 Expr *Arg0 = TheCall->getArg(0); 6415 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6416 if (FirstArg.isInvalid()) 6417 return true; 6418 QualType FirstArgType = FirstArg.get()->getType(); 6419 if (!FirstArgType->isAnyPointerType()) 6420 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6421 << "first" << FirstArgType << Arg0->getSourceRange(); 6422 TheCall->setArg(0, FirstArg.get()); 6423 6424 // Derive the return type from the pointer argument. 6425 TheCall->setType(FirstArgType); 6426 6427 // Second arg must be an constant in range [0,15] 6428 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6429 } 6430 6431 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6432 if (checkArgCount(*this, TheCall, 2)) 6433 return true; 6434 Expr *Arg0 = TheCall->getArg(0); 6435 Expr *Arg1 = TheCall->getArg(1); 6436 6437 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6438 if (FirstArg.isInvalid()) 6439 return true; 6440 QualType FirstArgType = FirstArg.get()->getType(); 6441 if (!FirstArgType->isAnyPointerType()) 6442 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6443 << "first" << FirstArgType << Arg0->getSourceRange(); 6444 6445 QualType SecArgType = Arg1->getType(); 6446 if (!SecArgType->isIntegerType()) 6447 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6448 << "second" << SecArgType << Arg1->getSourceRange(); 6449 TheCall->setType(Context.IntTy); 6450 return false; 6451 } 6452 6453 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6454 BuiltinID == AArch64::BI__builtin_arm_stg) { 6455 if (checkArgCount(*this, TheCall, 1)) 6456 return true; 6457 Expr *Arg0 = TheCall->getArg(0); 6458 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6459 if (FirstArg.isInvalid()) 6460 return true; 6461 6462 QualType FirstArgType = FirstArg.get()->getType(); 6463 if (!FirstArgType->isAnyPointerType()) 6464 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6465 << "first" << FirstArgType << Arg0->getSourceRange(); 6466 TheCall->setArg(0, FirstArg.get()); 6467 6468 // Derive the return type from the pointer argument. 6469 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6470 TheCall->setType(FirstArgType); 6471 return false; 6472 } 6473 6474 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6475 Expr *ArgA = TheCall->getArg(0); 6476 Expr *ArgB = TheCall->getArg(1); 6477 6478 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6479 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6480 6481 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6482 return true; 6483 6484 QualType ArgTypeA = ArgExprA.get()->getType(); 6485 QualType ArgTypeB = ArgExprB.get()->getType(); 6486 6487 auto isNull = [&] (Expr *E) -> bool { 6488 return E->isNullPointerConstant( 6489 Context, Expr::NPC_ValueDependentIsNotNull); }; 6490 6491 // argument should be either a pointer or null 6492 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6493 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6494 << "first" << ArgTypeA << ArgA->getSourceRange(); 6495 6496 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6497 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6498 << "second" << ArgTypeB << ArgB->getSourceRange(); 6499 6500 // Ensure Pointee types are compatible 6501 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6502 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6503 QualType pointeeA = ArgTypeA->getPointeeType(); 6504 QualType pointeeB = ArgTypeB->getPointeeType(); 6505 if (!Context.typesAreCompatible( 6506 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6507 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6508 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6509 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6510 << ArgB->getSourceRange(); 6511 } 6512 } 6513 6514 // at least one argument should be pointer type 6515 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6516 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6517 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6518 6519 if (isNull(ArgA)) // adopt type of the other pointer 6520 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6521 6522 if (isNull(ArgB)) 6523 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6524 6525 TheCall->setArg(0, ArgExprA.get()); 6526 TheCall->setArg(1, ArgExprB.get()); 6527 TheCall->setType(Context.LongLongTy); 6528 return false; 6529 } 6530 assert(false && "Unhandled ARM MTE intrinsic"); 6531 return true; 6532 } 6533 6534 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6535 /// TheCall is an ARM/AArch64 special register string literal. 6536 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6537 int ArgNum, unsigned ExpectedFieldNum, 6538 bool AllowName) { 6539 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6540 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6541 BuiltinID == ARM::BI__builtin_arm_rsr || 6542 BuiltinID == ARM::BI__builtin_arm_rsrp || 6543 BuiltinID == ARM::BI__builtin_arm_wsr || 6544 BuiltinID == ARM::BI__builtin_arm_wsrp; 6545 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6546 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6547 BuiltinID == AArch64::BI__builtin_arm_rsr || 6548 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6549 BuiltinID == AArch64::BI__builtin_arm_wsr || 6550 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6551 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6552 6553 // We can't check the value of a dependent argument. 6554 Expr *Arg = TheCall->getArg(ArgNum); 6555 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6556 return false; 6557 6558 // Check if the argument is a string literal. 6559 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6560 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6561 << Arg->getSourceRange(); 6562 6563 // Check the type of special register given. 6564 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6565 SmallVector<StringRef, 6> Fields; 6566 Reg.split(Fields, ":"); 6567 6568 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6569 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6570 << Arg->getSourceRange(); 6571 6572 // If the string is the name of a register then we cannot check that it is 6573 // valid here but if the string is of one the forms described in ACLE then we 6574 // can check that the supplied fields are integers and within the valid 6575 // ranges. 6576 if (Fields.size() > 1) { 6577 bool FiveFields = Fields.size() == 5; 6578 6579 bool ValidString = true; 6580 if (IsARMBuiltin) { 6581 ValidString &= Fields[0].startswith_lower("cp") || 6582 Fields[0].startswith_lower("p"); 6583 if (ValidString) 6584 Fields[0] = 6585 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6586 6587 ValidString &= Fields[2].startswith_lower("c"); 6588 if (ValidString) 6589 Fields[2] = Fields[2].drop_front(1); 6590 6591 if (FiveFields) { 6592 ValidString &= Fields[3].startswith_lower("c"); 6593 if (ValidString) 6594 Fields[3] = Fields[3].drop_front(1); 6595 } 6596 } 6597 6598 SmallVector<int, 5> Ranges; 6599 if (FiveFields) 6600 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6601 else 6602 Ranges.append({15, 7, 15}); 6603 6604 for (unsigned i=0; i<Fields.size(); ++i) { 6605 int IntField; 6606 ValidString &= !Fields[i].getAsInteger(10, IntField); 6607 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6608 } 6609 6610 if (!ValidString) 6611 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6612 << Arg->getSourceRange(); 6613 } else if (IsAArch64Builtin && Fields.size() == 1) { 6614 // If the register name is one of those that appear in the condition below 6615 // and the special register builtin being used is one of the write builtins, 6616 // then we require that the argument provided for writing to the register 6617 // is an integer constant expression. This is because it will be lowered to 6618 // an MSR (immediate) instruction, so we need to know the immediate at 6619 // compile time. 6620 if (TheCall->getNumArgs() != 2) 6621 return false; 6622 6623 std::string RegLower = Reg.lower(); 6624 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6625 RegLower != "pan" && RegLower != "uao") 6626 return false; 6627 6628 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6629 } 6630 6631 return false; 6632 } 6633 6634 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6635 /// This checks that the target supports __builtin_longjmp and 6636 /// that val is a constant 1. 6637 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6638 if (!Context.getTargetInfo().hasSjLjLowering()) 6639 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6640 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6641 6642 Expr *Arg = TheCall->getArg(1); 6643 llvm::APSInt Result; 6644 6645 // TODO: This is less than ideal. Overload this to take a value. 6646 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6647 return true; 6648 6649 if (Result != 1) 6650 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6651 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6652 6653 return false; 6654 } 6655 6656 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6657 /// This checks that the target supports __builtin_setjmp. 6658 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6659 if (!Context.getTargetInfo().hasSjLjLowering()) 6660 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6661 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6662 return false; 6663 } 6664 6665 namespace { 6666 6667 class UncoveredArgHandler { 6668 enum { Unknown = -1, AllCovered = -2 }; 6669 6670 signed FirstUncoveredArg = Unknown; 6671 SmallVector<const Expr *, 4> DiagnosticExprs; 6672 6673 public: 6674 UncoveredArgHandler() = default; 6675 6676 bool hasUncoveredArg() const { 6677 return (FirstUncoveredArg >= 0); 6678 } 6679 6680 unsigned getUncoveredArg() const { 6681 assert(hasUncoveredArg() && "no uncovered argument"); 6682 return FirstUncoveredArg; 6683 } 6684 6685 void setAllCovered() { 6686 // A string has been found with all arguments covered, so clear out 6687 // the diagnostics. 6688 DiagnosticExprs.clear(); 6689 FirstUncoveredArg = AllCovered; 6690 } 6691 6692 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6693 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6694 6695 // Don't update if a previous string covers all arguments. 6696 if (FirstUncoveredArg == AllCovered) 6697 return; 6698 6699 // UncoveredArgHandler tracks the highest uncovered argument index 6700 // and with it all the strings that match this index. 6701 if (NewFirstUncoveredArg == FirstUncoveredArg) 6702 DiagnosticExprs.push_back(StrExpr); 6703 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6704 DiagnosticExprs.clear(); 6705 DiagnosticExprs.push_back(StrExpr); 6706 FirstUncoveredArg = NewFirstUncoveredArg; 6707 } 6708 } 6709 6710 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6711 }; 6712 6713 enum StringLiteralCheckType { 6714 SLCT_NotALiteral, 6715 SLCT_UncheckedLiteral, 6716 SLCT_CheckedLiteral 6717 }; 6718 6719 } // namespace 6720 6721 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6722 BinaryOperatorKind BinOpKind, 6723 bool AddendIsRight) { 6724 unsigned BitWidth = Offset.getBitWidth(); 6725 unsigned AddendBitWidth = Addend.getBitWidth(); 6726 // There might be negative interim results. 6727 if (Addend.isUnsigned()) { 6728 Addend = Addend.zext(++AddendBitWidth); 6729 Addend.setIsSigned(true); 6730 } 6731 // Adjust the bit width of the APSInts. 6732 if (AddendBitWidth > BitWidth) { 6733 Offset = Offset.sext(AddendBitWidth); 6734 BitWidth = AddendBitWidth; 6735 } else if (BitWidth > AddendBitWidth) { 6736 Addend = Addend.sext(BitWidth); 6737 } 6738 6739 bool Ov = false; 6740 llvm::APSInt ResOffset = Offset; 6741 if (BinOpKind == BO_Add) 6742 ResOffset = Offset.sadd_ov(Addend, Ov); 6743 else { 6744 assert(AddendIsRight && BinOpKind == BO_Sub && 6745 "operator must be add or sub with addend on the right"); 6746 ResOffset = Offset.ssub_ov(Addend, Ov); 6747 } 6748 6749 // We add an offset to a pointer here so we should support an offset as big as 6750 // possible. 6751 if (Ov) { 6752 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6753 "index (intermediate) result too big"); 6754 Offset = Offset.sext(2 * BitWidth); 6755 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6756 return; 6757 } 6758 6759 Offset = ResOffset; 6760 } 6761 6762 namespace { 6763 6764 // This is a wrapper class around StringLiteral to support offsetted string 6765 // literals as format strings. It takes the offset into account when returning 6766 // the string and its length or the source locations to display notes correctly. 6767 class FormatStringLiteral { 6768 const StringLiteral *FExpr; 6769 int64_t Offset; 6770 6771 public: 6772 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6773 : FExpr(fexpr), Offset(Offset) {} 6774 6775 StringRef getString() const { 6776 return FExpr->getString().drop_front(Offset); 6777 } 6778 6779 unsigned getByteLength() const { 6780 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6781 } 6782 6783 unsigned getLength() const { return FExpr->getLength() - Offset; } 6784 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6785 6786 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6787 6788 QualType getType() const { return FExpr->getType(); } 6789 6790 bool isAscii() const { return FExpr->isAscii(); } 6791 bool isWide() const { return FExpr->isWide(); } 6792 bool isUTF8() const { return FExpr->isUTF8(); } 6793 bool isUTF16() const { return FExpr->isUTF16(); } 6794 bool isUTF32() const { return FExpr->isUTF32(); } 6795 bool isPascal() const { return FExpr->isPascal(); } 6796 6797 SourceLocation getLocationOfByte( 6798 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6799 const TargetInfo &Target, unsigned *StartToken = nullptr, 6800 unsigned *StartTokenByteOffset = nullptr) const { 6801 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6802 StartToken, StartTokenByteOffset); 6803 } 6804 6805 SourceLocation getBeginLoc() const LLVM_READONLY { 6806 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6807 } 6808 6809 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6810 }; 6811 6812 } // namespace 6813 6814 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6815 const Expr *OrigFormatExpr, 6816 ArrayRef<const Expr *> Args, 6817 bool HasVAListArg, unsigned format_idx, 6818 unsigned firstDataArg, 6819 Sema::FormatStringType Type, 6820 bool inFunctionCall, 6821 Sema::VariadicCallType CallType, 6822 llvm::SmallBitVector &CheckedVarArgs, 6823 UncoveredArgHandler &UncoveredArg, 6824 bool IgnoreStringsWithoutSpecifiers); 6825 6826 // Determine if an expression is a string literal or constant string. 6827 // If this function returns false on the arguments to a function expecting a 6828 // format string, we will usually need to emit a warning. 6829 // True string literals are then checked by CheckFormatString. 6830 static StringLiteralCheckType 6831 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6832 bool HasVAListArg, unsigned format_idx, 6833 unsigned firstDataArg, Sema::FormatStringType Type, 6834 Sema::VariadicCallType CallType, bool InFunctionCall, 6835 llvm::SmallBitVector &CheckedVarArgs, 6836 UncoveredArgHandler &UncoveredArg, 6837 llvm::APSInt Offset, 6838 bool IgnoreStringsWithoutSpecifiers = false) { 6839 if (S.isConstantEvaluated()) 6840 return SLCT_NotALiteral; 6841 tryAgain: 6842 assert(Offset.isSigned() && "invalid offset"); 6843 6844 if (E->isTypeDependent() || E->isValueDependent()) 6845 return SLCT_NotALiteral; 6846 6847 E = E->IgnoreParenCasts(); 6848 6849 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6850 // Technically -Wformat-nonliteral does not warn about this case. 6851 // The behavior of printf and friends in this case is implementation 6852 // dependent. Ideally if the format string cannot be null then 6853 // it should have a 'nonnull' attribute in the function prototype. 6854 return SLCT_UncheckedLiteral; 6855 6856 switch (E->getStmtClass()) { 6857 case Stmt::BinaryConditionalOperatorClass: 6858 case Stmt::ConditionalOperatorClass: { 6859 // The expression is a literal if both sub-expressions were, and it was 6860 // completely checked only if both sub-expressions were checked. 6861 const AbstractConditionalOperator *C = 6862 cast<AbstractConditionalOperator>(E); 6863 6864 // Determine whether it is necessary to check both sub-expressions, for 6865 // example, because the condition expression is a constant that can be 6866 // evaluated at compile time. 6867 bool CheckLeft = true, CheckRight = true; 6868 6869 bool Cond; 6870 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6871 S.isConstantEvaluated())) { 6872 if (Cond) 6873 CheckRight = false; 6874 else 6875 CheckLeft = false; 6876 } 6877 6878 // We need to maintain the offsets for the right and the left hand side 6879 // separately to check if every possible indexed expression is a valid 6880 // string literal. They might have different offsets for different string 6881 // literals in the end. 6882 StringLiteralCheckType Left; 6883 if (!CheckLeft) 6884 Left = SLCT_UncheckedLiteral; 6885 else { 6886 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6887 HasVAListArg, format_idx, firstDataArg, 6888 Type, CallType, InFunctionCall, 6889 CheckedVarArgs, UncoveredArg, Offset, 6890 IgnoreStringsWithoutSpecifiers); 6891 if (Left == SLCT_NotALiteral || !CheckRight) { 6892 return Left; 6893 } 6894 } 6895 6896 StringLiteralCheckType Right = checkFormatStringExpr( 6897 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6898 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6899 IgnoreStringsWithoutSpecifiers); 6900 6901 return (CheckLeft && Left < Right) ? Left : Right; 6902 } 6903 6904 case Stmt::ImplicitCastExprClass: 6905 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6906 goto tryAgain; 6907 6908 case Stmt::OpaqueValueExprClass: 6909 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6910 E = src; 6911 goto tryAgain; 6912 } 6913 return SLCT_NotALiteral; 6914 6915 case Stmt::PredefinedExprClass: 6916 // While __func__, etc., are technically not string literals, they 6917 // cannot contain format specifiers and thus are not a security 6918 // liability. 6919 return SLCT_UncheckedLiteral; 6920 6921 case Stmt::DeclRefExprClass: { 6922 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6923 6924 // As an exception, do not flag errors for variables binding to 6925 // const string literals. 6926 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6927 bool isConstant = false; 6928 QualType T = DR->getType(); 6929 6930 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6931 isConstant = AT->getElementType().isConstant(S.Context); 6932 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6933 isConstant = T.isConstant(S.Context) && 6934 PT->getPointeeType().isConstant(S.Context); 6935 } else if (T->isObjCObjectPointerType()) { 6936 // In ObjC, there is usually no "const ObjectPointer" type, 6937 // so don't check if the pointee type is constant. 6938 isConstant = T.isConstant(S.Context); 6939 } 6940 6941 if (isConstant) { 6942 if (const Expr *Init = VD->getAnyInitializer()) { 6943 // Look through initializers like const char c[] = { "foo" } 6944 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6945 if (InitList->isStringLiteralInit()) 6946 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6947 } 6948 return checkFormatStringExpr(S, Init, Args, 6949 HasVAListArg, format_idx, 6950 firstDataArg, Type, CallType, 6951 /*InFunctionCall*/ false, CheckedVarArgs, 6952 UncoveredArg, Offset); 6953 } 6954 } 6955 6956 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6957 // special check to see if the format string is a function parameter 6958 // of the function calling the printf function. If the function 6959 // has an attribute indicating it is a printf-like function, then we 6960 // should suppress warnings concerning non-literals being used in a call 6961 // to a vprintf function. For example: 6962 // 6963 // void 6964 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6965 // va_list ap; 6966 // va_start(ap, fmt); 6967 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6968 // ... 6969 // } 6970 if (HasVAListArg) { 6971 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6972 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6973 int PVIndex = PV->getFunctionScopeIndex() + 1; 6974 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6975 // adjust for implicit parameter 6976 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6977 if (MD->isInstance()) 6978 ++PVIndex; 6979 // We also check if the formats are compatible. 6980 // We can't pass a 'scanf' string to a 'printf' function. 6981 if (PVIndex == PVFormat->getFormatIdx() && 6982 Type == S.GetFormatStringType(PVFormat)) 6983 return SLCT_UncheckedLiteral; 6984 } 6985 } 6986 } 6987 } 6988 } 6989 6990 return SLCT_NotALiteral; 6991 } 6992 6993 case Stmt::CallExprClass: 6994 case Stmt::CXXMemberCallExprClass: { 6995 const CallExpr *CE = cast<CallExpr>(E); 6996 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6997 bool IsFirst = true; 6998 StringLiteralCheckType CommonResult; 6999 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7000 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7001 StringLiteralCheckType Result = checkFormatStringExpr( 7002 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7003 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7004 IgnoreStringsWithoutSpecifiers); 7005 if (IsFirst) { 7006 CommonResult = Result; 7007 IsFirst = false; 7008 } 7009 } 7010 if (!IsFirst) 7011 return CommonResult; 7012 7013 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7014 unsigned BuiltinID = FD->getBuiltinID(); 7015 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7016 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7017 const Expr *Arg = CE->getArg(0); 7018 return checkFormatStringExpr(S, Arg, Args, 7019 HasVAListArg, format_idx, 7020 firstDataArg, Type, CallType, 7021 InFunctionCall, CheckedVarArgs, 7022 UncoveredArg, Offset, 7023 IgnoreStringsWithoutSpecifiers); 7024 } 7025 } 7026 } 7027 7028 return SLCT_NotALiteral; 7029 } 7030 case Stmt::ObjCMessageExprClass: { 7031 const auto *ME = cast<ObjCMessageExpr>(E); 7032 if (const auto *MD = ME->getMethodDecl()) { 7033 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7034 // As a special case heuristic, if we're using the method -[NSBundle 7035 // localizedStringForKey:value:table:], ignore any key strings that lack 7036 // format specifiers. The idea is that if the key doesn't have any 7037 // format specifiers then its probably just a key to map to the 7038 // localized strings. If it does have format specifiers though, then its 7039 // likely that the text of the key is the format string in the 7040 // programmer's language, and should be checked. 7041 const ObjCInterfaceDecl *IFace; 7042 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7043 IFace->getIdentifier()->isStr("NSBundle") && 7044 MD->getSelector().isKeywordSelector( 7045 {"localizedStringForKey", "value", "table"})) { 7046 IgnoreStringsWithoutSpecifiers = true; 7047 } 7048 7049 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7050 return checkFormatStringExpr( 7051 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7052 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7053 IgnoreStringsWithoutSpecifiers); 7054 } 7055 } 7056 7057 return SLCT_NotALiteral; 7058 } 7059 case Stmt::ObjCStringLiteralClass: 7060 case Stmt::StringLiteralClass: { 7061 const StringLiteral *StrE = nullptr; 7062 7063 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7064 StrE = ObjCFExpr->getString(); 7065 else 7066 StrE = cast<StringLiteral>(E); 7067 7068 if (StrE) { 7069 if (Offset.isNegative() || Offset > StrE->getLength()) { 7070 // TODO: It would be better to have an explicit warning for out of 7071 // bounds literals. 7072 return SLCT_NotALiteral; 7073 } 7074 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7075 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7076 firstDataArg, Type, InFunctionCall, CallType, 7077 CheckedVarArgs, UncoveredArg, 7078 IgnoreStringsWithoutSpecifiers); 7079 return SLCT_CheckedLiteral; 7080 } 7081 7082 return SLCT_NotALiteral; 7083 } 7084 case Stmt::BinaryOperatorClass: { 7085 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7086 7087 // A string literal + an int offset is still a string literal. 7088 if (BinOp->isAdditiveOp()) { 7089 Expr::EvalResult LResult, RResult; 7090 7091 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7092 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7093 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7094 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7095 7096 if (LIsInt != RIsInt) { 7097 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7098 7099 if (LIsInt) { 7100 if (BinOpKind == BO_Add) { 7101 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7102 E = BinOp->getRHS(); 7103 goto tryAgain; 7104 } 7105 } else { 7106 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7107 E = BinOp->getLHS(); 7108 goto tryAgain; 7109 } 7110 } 7111 } 7112 7113 return SLCT_NotALiteral; 7114 } 7115 case Stmt::UnaryOperatorClass: { 7116 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7117 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7118 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7119 Expr::EvalResult IndexResult; 7120 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7121 Expr::SE_NoSideEffects, 7122 S.isConstantEvaluated())) { 7123 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7124 /*RHS is int*/ true); 7125 E = ASE->getBase(); 7126 goto tryAgain; 7127 } 7128 } 7129 7130 return SLCT_NotALiteral; 7131 } 7132 7133 default: 7134 return SLCT_NotALiteral; 7135 } 7136 } 7137 7138 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7139 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7140 .Case("scanf", FST_Scanf) 7141 .Cases("printf", "printf0", FST_Printf) 7142 .Cases("NSString", "CFString", FST_NSString) 7143 .Case("strftime", FST_Strftime) 7144 .Case("strfmon", FST_Strfmon) 7145 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7146 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7147 .Case("os_trace", FST_OSLog) 7148 .Case("os_log", FST_OSLog) 7149 .Default(FST_Unknown); 7150 } 7151 7152 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7153 /// functions) for correct use of format strings. 7154 /// Returns true if a format string has been fully checked. 7155 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7156 ArrayRef<const Expr *> Args, 7157 bool IsCXXMember, 7158 VariadicCallType CallType, 7159 SourceLocation Loc, SourceRange Range, 7160 llvm::SmallBitVector &CheckedVarArgs) { 7161 FormatStringInfo FSI; 7162 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7163 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7164 FSI.FirstDataArg, GetFormatStringType(Format), 7165 CallType, Loc, Range, CheckedVarArgs); 7166 return false; 7167 } 7168 7169 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7170 bool HasVAListArg, unsigned format_idx, 7171 unsigned firstDataArg, FormatStringType Type, 7172 VariadicCallType CallType, 7173 SourceLocation Loc, SourceRange Range, 7174 llvm::SmallBitVector &CheckedVarArgs) { 7175 // CHECK: printf/scanf-like function is called with no format string. 7176 if (format_idx >= Args.size()) { 7177 Diag(Loc, diag::warn_missing_format_string) << Range; 7178 return false; 7179 } 7180 7181 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7182 7183 // CHECK: format string is not a string literal. 7184 // 7185 // Dynamically generated format strings are difficult to 7186 // automatically vet at compile time. Requiring that format strings 7187 // are string literals: (1) permits the checking of format strings by 7188 // the compiler and thereby (2) can practically remove the source of 7189 // many format string exploits. 7190 7191 // Format string can be either ObjC string (e.g. @"%d") or 7192 // C string (e.g. "%d") 7193 // ObjC string uses the same format specifiers as C string, so we can use 7194 // the same format string checking logic for both ObjC and C strings. 7195 UncoveredArgHandler UncoveredArg; 7196 StringLiteralCheckType CT = 7197 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7198 format_idx, firstDataArg, Type, CallType, 7199 /*IsFunctionCall*/ true, CheckedVarArgs, 7200 UncoveredArg, 7201 /*no string offset*/ llvm::APSInt(64, false) = 0); 7202 7203 // Generate a diagnostic where an uncovered argument is detected. 7204 if (UncoveredArg.hasUncoveredArg()) { 7205 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7206 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7207 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7208 } 7209 7210 if (CT != SLCT_NotALiteral) 7211 // Literal format string found, check done! 7212 return CT == SLCT_CheckedLiteral; 7213 7214 // Strftime is particular as it always uses a single 'time' argument, 7215 // so it is safe to pass a non-literal string. 7216 if (Type == FST_Strftime) 7217 return false; 7218 7219 // Do not emit diag when the string param is a macro expansion and the 7220 // format is either NSString or CFString. This is a hack to prevent 7221 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7222 // which are usually used in place of NS and CF string literals. 7223 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7224 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7225 return false; 7226 7227 // If there are no arguments specified, warn with -Wformat-security, otherwise 7228 // warn only with -Wformat-nonliteral. 7229 if (Args.size() == firstDataArg) { 7230 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7231 << OrigFormatExpr->getSourceRange(); 7232 switch (Type) { 7233 default: 7234 break; 7235 case FST_Kprintf: 7236 case FST_FreeBSDKPrintf: 7237 case FST_Printf: 7238 Diag(FormatLoc, diag::note_format_security_fixit) 7239 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7240 break; 7241 case FST_NSString: 7242 Diag(FormatLoc, diag::note_format_security_fixit) 7243 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7244 break; 7245 } 7246 } else { 7247 Diag(FormatLoc, diag::warn_format_nonliteral) 7248 << OrigFormatExpr->getSourceRange(); 7249 } 7250 return false; 7251 } 7252 7253 namespace { 7254 7255 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7256 protected: 7257 Sema &S; 7258 const FormatStringLiteral *FExpr; 7259 const Expr *OrigFormatExpr; 7260 const Sema::FormatStringType FSType; 7261 const unsigned FirstDataArg; 7262 const unsigned NumDataArgs; 7263 const char *Beg; // Start of format string. 7264 const bool HasVAListArg; 7265 ArrayRef<const Expr *> Args; 7266 unsigned FormatIdx; 7267 llvm::SmallBitVector CoveredArgs; 7268 bool usesPositionalArgs = false; 7269 bool atFirstArg = true; 7270 bool inFunctionCall; 7271 Sema::VariadicCallType CallType; 7272 llvm::SmallBitVector &CheckedVarArgs; 7273 UncoveredArgHandler &UncoveredArg; 7274 7275 public: 7276 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7277 const Expr *origFormatExpr, 7278 const Sema::FormatStringType type, unsigned firstDataArg, 7279 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7280 ArrayRef<const Expr *> Args, unsigned formatIdx, 7281 bool inFunctionCall, Sema::VariadicCallType callType, 7282 llvm::SmallBitVector &CheckedVarArgs, 7283 UncoveredArgHandler &UncoveredArg) 7284 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7285 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7286 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7287 inFunctionCall(inFunctionCall), CallType(callType), 7288 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7289 CoveredArgs.resize(numDataArgs); 7290 CoveredArgs.reset(); 7291 } 7292 7293 void DoneProcessing(); 7294 7295 void HandleIncompleteSpecifier(const char *startSpecifier, 7296 unsigned specifierLen) override; 7297 7298 void HandleInvalidLengthModifier( 7299 const analyze_format_string::FormatSpecifier &FS, 7300 const analyze_format_string::ConversionSpecifier &CS, 7301 const char *startSpecifier, unsigned specifierLen, 7302 unsigned DiagID); 7303 7304 void HandleNonStandardLengthModifier( 7305 const analyze_format_string::FormatSpecifier &FS, 7306 const char *startSpecifier, unsigned specifierLen); 7307 7308 void HandleNonStandardConversionSpecifier( 7309 const analyze_format_string::ConversionSpecifier &CS, 7310 const char *startSpecifier, unsigned specifierLen); 7311 7312 void HandlePosition(const char *startPos, unsigned posLen) override; 7313 7314 void HandleInvalidPosition(const char *startSpecifier, 7315 unsigned specifierLen, 7316 analyze_format_string::PositionContext p) override; 7317 7318 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7319 7320 void HandleNullChar(const char *nullCharacter) override; 7321 7322 template <typename Range> 7323 static void 7324 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7325 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7326 bool IsStringLocation, Range StringRange, 7327 ArrayRef<FixItHint> Fixit = None); 7328 7329 protected: 7330 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7331 const char *startSpec, 7332 unsigned specifierLen, 7333 const char *csStart, unsigned csLen); 7334 7335 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7336 const char *startSpec, 7337 unsigned specifierLen); 7338 7339 SourceRange getFormatStringRange(); 7340 CharSourceRange getSpecifierRange(const char *startSpecifier, 7341 unsigned specifierLen); 7342 SourceLocation getLocationOfByte(const char *x); 7343 7344 const Expr *getDataArg(unsigned i) const; 7345 7346 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7347 const analyze_format_string::ConversionSpecifier &CS, 7348 const char *startSpecifier, unsigned specifierLen, 7349 unsigned argIndex); 7350 7351 template <typename Range> 7352 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7353 bool IsStringLocation, Range StringRange, 7354 ArrayRef<FixItHint> Fixit = None); 7355 }; 7356 7357 } // namespace 7358 7359 SourceRange CheckFormatHandler::getFormatStringRange() { 7360 return OrigFormatExpr->getSourceRange(); 7361 } 7362 7363 CharSourceRange CheckFormatHandler:: 7364 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7365 SourceLocation Start = getLocationOfByte(startSpecifier); 7366 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7367 7368 // Advance the end SourceLocation by one due to half-open ranges. 7369 End = End.getLocWithOffset(1); 7370 7371 return CharSourceRange::getCharRange(Start, End); 7372 } 7373 7374 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7375 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7376 S.getLangOpts(), S.Context.getTargetInfo()); 7377 } 7378 7379 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7380 unsigned specifierLen){ 7381 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7382 getLocationOfByte(startSpecifier), 7383 /*IsStringLocation*/true, 7384 getSpecifierRange(startSpecifier, specifierLen)); 7385 } 7386 7387 void CheckFormatHandler::HandleInvalidLengthModifier( 7388 const analyze_format_string::FormatSpecifier &FS, 7389 const analyze_format_string::ConversionSpecifier &CS, 7390 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7391 using namespace analyze_format_string; 7392 7393 const LengthModifier &LM = FS.getLengthModifier(); 7394 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7395 7396 // See if we know how to fix this length modifier. 7397 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7398 if (FixedLM) { 7399 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7400 getLocationOfByte(LM.getStart()), 7401 /*IsStringLocation*/true, 7402 getSpecifierRange(startSpecifier, specifierLen)); 7403 7404 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7405 << FixedLM->toString() 7406 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7407 7408 } else { 7409 FixItHint Hint; 7410 if (DiagID == diag::warn_format_nonsensical_length) 7411 Hint = FixItHint::CreateRemoval(LMRange); 7412 7413 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7414 getLocationOfByte(LM.getStart()), 7415 /*IsStringLocation*/true, 7416 getSpecifierRange(startSpecifier, specifierLen), 7417 Hint); 7418 } 7419 } 7420 7421 void CheckFormatHandler::HandleNonStandardLengthModifier( 7422 const analyze_format_string::FormatSpecifier &FS, 7423 const char *startSpecifier, unsigned specifierLen) { 7424 using namespace analyze_format_string; 7425 7426 const LengthModifier &LM = FS.getLengthModifier(); 7427 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7428 7429 // See if we know how to fix this length modifier. 7430 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7431 if (FixedLM) { 7432 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7433 << LM.toString() << 0, 7434 getLocationOfByte(LM.getStart()), 7435 /*IsStringLocation*/true, 7436 getSpecifierRange(startSpecifier, specifierLen)); 7437 7438 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7439 << FixedLM->toString() 7440 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7441 7442 } else { 7443 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7444 << LM.toString() << 0, 7445 getLocationOfByte(LM.getStart()), 7446 /*IsStringLocation*/true, 7447 getSpecifierRange(startSpecifier, specifierLen)); 7448 } 7449 } 7450 7451 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7452 const analyze_format_string::ConversionSpecifier &CS, 7453 const char *startSpecifier, unsigned specifierLen) { 7454 using namespace analyze_format_string; 7455 7456 // See if we know how to fix this conversion specifier. 7457 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7458 if (FixedCS) { 7459 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7460 << CS.toString() << /*conversion specifier*/1, 7461 getLocationOfByte(CS.getStart()), 7462 /*IsStringLocation*/true, 7463 getSpecifierRange(startSpecifier, specifierLen)); 7464 7465 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7466 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7467 << FixedCS->toString() 7468 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7469 } else { 7470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7471 << CS.toString() << /*conversion specifier*/1, 7472 getLocationOfByte(CS.getStart()), 7473 /*IsStringLocation*/true, 7474 getSpecifierRange(startSpecifier, specifierLen)); 7475 } 7476 } 7477 7478 void CheckFormatHandler::HandlePosition(const char *startPos, 7479 unsigned posLen) { 7480 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7481 getLocationOfByte(startPos), 7482 /*IsStringLocation*/true, 7483 getSpecifierRange(startPos, posLen)); 7484 } 7485 7486 void 7487 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7488 analyze_format_string::PositionContext p) { 7489 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7490 << (unsigned) p, 7491 getLocationOfByte(startPos), /*IsStringLocation*/true, 7492 getSpecifierRange(startPos, posLen)); 7493 } 7494 7495 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7496 unsigned posLen) { 7497 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7498 getLocationOfByte(startPos), 7499 /*IsStringLocation*/true, 7500 getSpecifierRange(startPos, posLen)); 7501 } 7502 7503 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7504 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7505 // The presence of a null character is likely an error. 7506 EmitFormatDiagnostic( 7507 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7508 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7509 getFormatStringRange()); 7510 } 7511 } 7512 7513 // Note that this may return NULL if there was an error parsing or building 7514 // one of the argument expressions. 7515 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7516 return Args[FirstDataArg + i]; 7517 } 7518 7519 void CheckFormatHandler::DoneProcessing() { 7520 // Does the number of data arguments exceed the number of 7521 // format conversions in the format string? 7522 if (!HasVAListArg) { 7523 // Find any arguments that weren't covered. 7524 CoveredArgs.flip(); 7525 signed notCoveredArg = CoveredArgs.find_first(); 7526 if (notCoveredArg >= 0) { 7527 assert((unsigned)notCoveredArg < NumDataArgs); 7528 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7529 } else { 7530 UncoveredArg.setAllCovered(); 7531 } 7532 } 7533 } 7534 7535 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7536 const Expr *ArgExpr) { 7537 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7538 "Invalid state"); 7539 7540 if (!ArgExpr) 7541 return; 7542 7543 SourceLocation Loc = ArgExpr->getBeginLoc(); 7544 7545 if (S.getSourceManager().isInSystemMacro(Loc)) 7546 return; 7547 7548 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7549 for (auto E : DiagnosticExprs) 7550 PDiag << E->getSourceRange(); 7551 7552 CheckFormatHandler::EmitFormatDiagnostic( 7553 S, IsFunctionCall, DiagnosticExprs[0], 7554 PDiag, Loc, /*IsStringLocation*/false, 7555 DiagnosticExprs[0]->getSourceRange()); 7556 } 7557 7558 bool 7559 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7560 SourceLocation Loc, 7561 const char *startSpec, 7562 unsigned specifierLen, 7563 const char *csStart, 7564 unsigned csLen) { 7565 bool keepGoing = true; 7566 if (argIndex < NumDataArgs) { 7567 // Consider the argument coverered, even though the specifier doesn't 7568 // make sense. 7569 CoveredArgs.set(argIndex); 7570 } 7571 else { 7572 // If argIndex exceeds the number of data arguments we 7573 // don't issue a warning because that is just a cascade of warnings (and 7574 // they may have intended '%%' anyway). We don't want to continue processing 7575 // the format string after this point, however, as we will like just get 7576 // gibberish when trying to match arguments. 7577 keepGoing = false; 7578 } 7579 7580 StringRef Specifier(csStart, csLen); 7581 7582 // If the specifier in non-printable, it could be the first byte of a UTF-8 7583 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7584 // hex value. 7585 std::string CodePointStr; 7586 if (!llvm::sys::locale::isPrint(*csStart)) { 7587 llvm::UTF32 CodePoint; 7588 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7589 const llvm::UTF8 *E = 7590 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7591 llvm::ConversionResult Result = 7592 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7593 7594 if (Result != llvm::conversionOK) { 7595 unsigned char FirstChar = *csStart; 7596 CodePoint = (llvm::UTF32)FirstChar; 7597 } 7598 7599 llvm::raw_string_ostream OS(CodePointStr); 7600 if (CodePoint < 256) 7601 OS << "\\x" << llvm::format("%02x", CodePoint); 7602 else if (CodePoint <= 0xFFFF) 7603 OS << "\\u" << llvm::format("%04x", CodePoint); 7604 else 7605 OS << "\\U" << llvm::format("%08x", CodePoint); 7606 OS.flush(); 7607 Specifier = CodePointStr; 7608 } 7609 7610 EmitFormatDiagnostic( 7611 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7612 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7613 7614 return keepGoing; 7615 } 7616 7617 void 7618 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7619 const char *startSpec, 7620 unsigned specifierLen) { 7621 EmitFormatDiagnostic( 7622 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7623 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7624 } 7625 7626 bool 7627 CheckFormatHandler::CheckNumArgs( 7628 const analyze_format_string::FormatSpecifier &FS, 7629 const analyze_format_string::ConversionSpecifier &CS, 7630 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7631 7632 if (argIndex >= NumDataArgs) { 7633 PartialDiagnostic PDiag = FS.usesPositionalArg() 7634 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7635 << (argIndex+1) << NumDataArgs) 7636 : S.PDiag(diag::warn_printf_insufficient_data_args); 7637 EmitFormatDiagnostic( 7638 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7639 getSpecifierRange(startSpecifier, specifierLen)); 7640 7641 // Since more arguments than conversion tokens are given, by extension 7642 // all arguments are covered, so mark this as so. 7643 UncoveredArg.setAllCovered(); 7644 return false; 7645 } 7646 return true; 7647 } 7648 7649 template<typename Range> 7650 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7651 SourceLocation Loc, 7652 bool IsStringLocation, 7653 Range StringRange, 7654 ArrayRef<FixItHint> FixIt) { 7655 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7656 Loc, IsStringLocation, StringRange, FixIt); 7657 } 7658 7659 /// If the format string is not within the function call, emit a note 7660 /// so that the function call and string are in diagnostic messages. 7661 /// 7662 /// \param InFunctionCall if true, the format string is within the function 7663 /// call and only one diagnostic message will be produced. Otherwise, an 7664 /// extra note will be emitted pointing to location of the format string. 7665 /// 7666 /// \param ArgumentExpr the expression that is passed as the format string 7667 /// argument in the function call. Used for getting locations when two 7668 /// diagnostics are emitted. 7669 /// 7670 /// \param PDiag the callee should already have provided any strings for the 7671 /// diagnostic message. This function only adds locations and fixits 7672 /// to diagnostics. 7673 /// 7674 /// \param Loc primary location for diagnostic. If two diagnostics are 7675 /// required, one will be at Loc and a new SourceLocation will be created for 7676 /// the other one. 7677 /// 7678 /// \param IsStringLocation if true, Loc points to the format string should be 7679 /// used for the note. Otherwise, Loc points to the argument list and will 7680 /// be used with PDiag. 7681 /// 7682 /// \param StringRange some or all of the string to highlight. This is 7683 /// templated so it can accept either a CharSourceRange or a SourceRange. 7684 /// 7685 /// \param FixIt optional fix it hint for the format string. 7686 template <typename Range> 7687 void CheckFormatHandler::EmitFormatDiagnostic( 7688 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7689 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7690 Range StringRange, ArrayRef<FixItHint> FixIt) { 7691 if (InFunctionCall) { 7692 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7693 D << StringRange; 7694 D << FixIt; 7695 } else { 7696 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7697 << ArgumentExpr->getSourceRange(); 7698 7699 const Sema::SemaDiagnosticBuilder &Note = 7700 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7701 diag::note_format_string_defined); 7702 7703 Note << StringRange; 7704 Note << FixIt; 7705 } 7706 } 7707 7708 //===--- CHECK: Printf format string checking ------------------------------===// 7709 7710 namespace { 7711 7712 class CheckPrintfHandler : public CheckFormatHandler { 7713 public: 7714 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7715 const Expr *origFormatExpr, 7716 const Sema::FormatStringType type, unsigned firstDataArg, 7717 unsigned numDataArgs, bool isObjC, const char *beg, 7718 bool hasVAListArg, ArrayRef<const Expr *> Args, 7719 unsigned formatIdx, bool inFunctionCall, 7720 Sema::VariadicCallType CallType, 7721 llvm::SmallBitVector &CheckedVarArgs, 7722 UncoveredArgHandler &UncoveredArg) 7723 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7724 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7725 inFunctionCall, CallType, CheckedVarArgs, 7726 UncoveredArg) {} 7727 7728 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7729 7730 /// Returns true if '%@' specifiers are allowed in the format string. 7731 bool allowsObjCArg() const { 7732 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7733 FSType == Sema::FST_OSTrace; 7734 } 7735 7736 bool HandleInvalidPrintfConversionSpecifier( 7737 const analyze_printf::PrintfSpecifier &FS, 7738 const char *startSpecifier, 7739 unsigned specifierLen) override; 7740 7741 void handleInvalidMaskType(StringRef MaskType) override; 7742 7743 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7744 const char *startSpecifier, 7745 unsigned specifierLen) override; 7746 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7747 const char *StartSpecifier, 7748 unsigned SpecifierLen, 7749 const Expr *E); 7750 7751 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7752 const char *startSpecifier, unsigned specifierLen); 7753 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7754 const analyze_printf::OptionalAmount &Amt, 7755 unsigned type, 7756 const char *startSpecifier, unsigned specifierLen); 7757 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7758 const analyze_printf::OptionalFlag &flag, 7759 const char *startSpecifier, unsigned specifierLen); 7760 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7761 const analyze_printf::OptionalFlag &ignoredFlag, 7762 const analyze_printf::OptionalFlag &flag, 7763 const char *startSpecifier, unsigned specifierLen); 7764 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7765 const Expr *E); 7766 7767 void HandleEmptyObjCModifierFlag(const char *startFlag, 7768 unsigned flagLen) override; 7769 7770 void HandleInvalidObjCModifierFlag(const char *startFlag, 7771 unsigned flagLen) override; 7772 7773 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7774 const char *flagsEnd, 7775 const char *conversionPosition) 7776 override; 7777 }; 7778 7779 } // namespace 7780 7781 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7782 const analyze_printf::PrintfSpecifier &FS, 7783 const char *startSpecifier, 7784 unsigned specifierLen) { 7785 const analyze_printf::PrintfConversionSpecifier &CS = 7786 FS.getConversionSpecifier(); 7787 7788 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7789 getLocationOfByte(CS.getStart()), 7790 startSpecifier, specifierLen, 7791 CS.getStart(), CS.getLength()); 7792 } 7793 7794 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7795 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7796 } 7797 7798 bool CheckPrintfHandler::HandleAmount( 7799 const analyze_format_string::OptionalAmount &Amt, 7800 unsigned k, const char *startSpecifier, 7801 unsigned specifierLen) { 7802 if (Amt.hasDataArgument()) { 7803 if (!HasVAListArg) { 7804 unsigned argIndex = Amt.getArgIndex(); 7805 if (argIndex >= NumDataArgs) { 7806 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7807 << k, 7808 getLocationOfByte(Amt.getStart()), 7809 /*IsStringLocation*/true, 7810 getSpecifierRange(startSpecifier, specifierLen)); 7811 // Don't do any more checking. We will just emit 7812 // spurious errors. 7813 return false; 7814 } 7815 7816 // Type check the data argument. It should be an 'int'. 7817 // Although not in conformance with C99, we also allow the argument to be 7818 // an 'unsigned int' as that is a reasonably safe case. GCC also 7819 // doesn't emit a warning for that case. 7820 CoveredArgs.set(argIndex); 7821 const Expr *Arg = getDataArg(argIndex); 7822 if (!Arg) 7823 return false; 7824 7825 QualType T = Arg->getType(); 7826 7827 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7828 assert(AT.isValid()); 7829 7830 if (!AT.matchesType(S.Context, T)) { 7831 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7832 << k << AT.getRepresentativeTypeName(S.Context) 7833 << T << Arg->getSourceRange(), 7834 getLocationOfByte(Amt.getStart()), 7835 /*IsStringLocation*/true, 7836 getSpecifierRange(startSpecifier, specifierLen)); 7837 // Don't do any more checking. We will just emit 7838 // spurious errors. 7839 return false; 7840 } 7841 } 7842 } 7843 return true; 7844 } 7845 7846 void CheckPrintfHandler::HandleInvalidAmount( 7847 const analyze_printf::PrintfSpecifier &FS, 7848 const analyze_printf::OptionalAmount &Amt, 7849 unsigned type, 7850 const char *startSpecifier, 7851 unsigned specifierLen) { 7852 const analyze_printf::PrintfConversionSpecifier &CS = 7853 FS.getConversionSpecifier(); 7854 7855 FixItHint fixit = 7856 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7857 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7858 Amt.getConstantLength())) 7859 : FixItHint(); 7860 7861 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7862 << type << CS.toString(), 7863 getLocationOfByte(Amt.getStart()), 7864 /*IsStringLocation*/true, 7865 getSpecifierRange(startSpecifier, specifierLen), 7866 fixit); 7867 } 7868 7869 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7870 const analyze_printf::OptionalFlag &flag, 7871 const char *startSpecifier, 7872 unsigned specifierLen) { 7873 // Warn about pointless flag with a fixit removal. 7874 const analyze_printf::PrintfConversionSpecifier &CS = 7875 FS.getConversionSpecifier(); 7876 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7877 << flag.toString() << CS.toString(), 7878 getLocationOfByte(flag.getPosition()), 7879 /*IsStringLocation*/true, 7880 getSpecifierRange(startSpecifier, specifierLen), 7881 FixItHint::CreateRemoval( 7882 getSpecifierRange(flag.getPosition(), 1))); 7883 } 7884 7885 void CheckPrintfHandler::HandleIgnoredFlag( 7886 const analyze_printf::PrintfSpecifier &FS, 7887 const analyze_printf::OptionalFlag &ignoredFlag, 7888 const analyze_printf::OptionalFlag &flag, 7889 const char *startSpecifier, 7890 unsigned specifierLen) { 7891 // Warn about ignored flag with a fixit removal. 7892 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7893 << ignoredFlag.toString() << flag.toString(), 7894 getLocationOfByte(ignoredFlag.getPosition()), 7895 /*IsStringLocation*/true, 7896 getSpecifierRange(startSpecifier, specifierLen), 7897 FixItHint::CreateRemoval( 7898 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7899 } 7900 7901 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7902 unsigned flagLen) { 7903 // Warn about an empty flag. 7904 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7905 getLocationOfByte(startFlag), 7906 /*IsStringLocation*/true, 7907 getSpecifierRange(startFlag, flagLen)); 7908 } 7909 7910 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7911 unsigned flagLen) { 7912 // Warn about an invalid flag. 7913 auto Range = getSpecifierRange(startFlag, flagLen); 7914 StringRef flag(startFlag, flagLen); 7915 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7916 getLocationOfByte(startFlag), 7917 /*IsStringLocation*/true, 7918 Range, FixItHint::CreateRemoval(Range)); 7919 } 7920 7921 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7922 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7923 // Warn about using '[...]' without a '@' conversion. 7924 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7925 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7926 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7927 getLocationOfByte(conversionPosition), 7928 /*IsStringLocation*/true, 7929 Range, FixItHint::CreateRemoval(Range)); 7930 } 7931 7932 // Determines if the specified is a C++ class or struct containing 7933 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7934 // "c_str()"). 7935 template<typename MemberKind> 7936 static llvm::SmallPtrSet<MemberKind*, 1> 7937 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7938 const RecordType *RT = Ty->getAs<RecordType>(); 7939 llvm::SmallPtrSet<MemberKind*, 1> Results; 7940 7941 if (!RT) 7942 return Results; 7943 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7944 if (!RD || !RD->getDefinition()) 7945 return Results; 7946 7947 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7948 Sema::LookupMemberName); 7949 R.suppressDiagnostics(); 7950 7951 // We just need to include all members of the right kind turned up by the 7952 // filter, at this point. 7953 if (S.LookupQualifiedName(R, RT->getDecl())) 7954 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7955 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7956 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7957 Results.insert(FK); 7958 } 7959 return Results; 7960 } 7961 7962 /// Check if we could call '.c_str()' on an object. 7963 /// 7964 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7965 /// allow the call, or if it would be ambiguous). 7966 bool Sema::hasCStrMethod(const Expr *E) { 7967 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7968 7969 MethodSet Results = 7970 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7971 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7972 MI != ME; ++MI) 7973 if ((*MI)->getMinRequiredArguments() == 0) 7974 return true; 7975 return false; 7976 } 7977 7978 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7979 // better diagnostic if so. AT is assumed to be valid. 7980 // Returns true when a c_str() conversion method is found. 7981 bool CheckPrintfHandler::checkForCStrMembers( 7982 const analyze_printf::ArgType &AT, const Expr *E) { 7983 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7984 7985 MethodSet Results = 7986 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7987 7988 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7989 MI != ME; ++MI) { 7990 const CXXMethodDecl *Method = *MI; 7991 if (Method->getMinRequiredArguments() == 0 && 7992 AT.matchesType(S.Context, Method->getReturnType())) { 7993 // FIXME: Suggest parens if the expression needs them. 7994 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7995 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7996 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7997 return true; 7998 } 7999 } 8000 8001 return false; 8002 } 8003 8004 bool 8005 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8006 &FS, 8007 const char *startSpecifier, 8008 unsigned specifierLen) { 8009 using namespace analyze_format_string; 8010 using namespace analyze_printf; 8011 8012 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8013 8014 if (FS.consumesDataArgument()) { 8015 if (atFirstArg) { 8016 atFirstArg = false; 8017 usesPositionalArgs = FS.usesPositionalArg(); 8018 } 8019 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8020 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8021 startSpecifier, specifierLen); 8022 return false; 8023 } 8024 } 8025 8026 // First check if the field width, precision, and conversion specifier 8027 // have matching data arguments. 8028 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8029 startSpecifier, specifierLen)) { 8030 return false; 8031 } 8032 8033 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8034 startSpecifier, specifierLen)) { 8035 return false; 8036 } 8037 8038 if (!CS.consumesDataArgument()) { 8039 // FIXME: Technically specifying a precision or field width here 8040 // makes no sense. Worth issuing a warning at some point. 8041 return true; 8042 } 8043 8044 // Consume the argument. 8045 unsigned argIndex = FS.getArgIndex(); 8046 if (argIndex < NumDataArgs) { 8047 // The check to see if the argIndex is valid will come later. 8048 // We set the bit here because we may exit early from this 8049 // function if we encounter some other error. 8050 CoveredArgs.set(argIndex); 8051 } 8052 8053 // FreeBSD kernel extensions. 8054 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8055 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8056 // We need at least two arguments. 8057 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8058 return false; 8059 8060 // Claim the second argument. 8061 CoveredArgs.set(argIndex + 1); 8062 8063 // Type check the first argument (int for %b, pointer for %D) 8064 const Expr *Ex = getDataArg(argIndex); 8065 const analyze_printf::ArgType &AT = 8066 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8067 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8068 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8069 EmitFormatDiagnostic( 8070 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8071 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8072 << false << Ex->getSourceRange(), 8073 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8074 getSpecifierRange(startSpecifier, specifierLen)); 8075 8076 // Type check the second argument (char * for both %b and %D) 8077 Ex = getDataArg(argIndex + 1); 8078 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8079 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8080 EmitFormatDiagnostic( 8081 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8082 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8083 << false << Ex->getSourceRange(), 8084 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8085 getSpecifierRange(startSpecifier, specifierLen)); 8086 8087 return true; 8088 } 8089 8090 // Check for using an Objective-C specific conversion specifier 8091 // in a non-ObjC literal. 8092 if (!allowsObjCArg() && CS.isObjCArg()) { 8093 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8094 specifierLen); 8095 } 8096 8097 // %P can only be used with os_log. 8098 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8099 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8100 specifierLen); 8101 } 8102 8103 // %n is not allowed with os_log. 8104 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8105 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8106 getLocationOfByte(CS.getStart()), 8107 /*IsStringLocation*/ false, 8108 getSpecifierRange(startSpecifier, specifierLen)); 8109 8110 return true; 8111 } 8112 8113 // Only scalars are allowed for os_trace. 8114 if (FSType == Sema::FST_OSTrace && 8115 (CS.getKind() == ConversionSpecifier::PArg || 8116 CS.getKind() == ConversionSpecifier::sArg || 8117 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8118 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8119 specifierLen); 8120 } 8121 8122 // Check for use of public/private annotation outside of os_log(). 8123 if (FSType != Sema::FST_OSLog) { 8124 if (FS.isPublic().isSet()) { 8125 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8126 << "public", 8127 getLocationOfByte(FS.isPublic().getPosition()), 8128 /*IsStringLocation*/ false, 8129 getSpecifierRange(startSpecifier, specifierLen)); 8130 } 8131 if (FS.isPrivate().isSet()) { 8132 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8133 << "private", 8134 getLocationOfByte(FS.isPrivate().getPosition()), 8135 /*IsStringLocation*/ false, 8136 getSpecifierRange(startSpecifier, specifierLen)); 8137 } 8138 } 8139 8140 // Check for invalid use of field width 8141 if (!FS.hasValidFieldWidth()) { 8142 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8143 startSpecifier, specifierLen); 8144 } 8145 8146 // Check for invalid use of precision 8147 if (!FS.hasValidPrecision()) { 8148 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8149 startSpecifier, specifierLen); 8150 } 8151 8152 // Precision is mandatory for %P specifier. 8153 if (CS.getKind() == ConversionSpecifier::PArg && 8154 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8155 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8156 getLocationOfByte(startSpecifier), 8157 /*IsStringLocation*/ false, 8158 getSpecifierRange(startSpecifier, specifierLen)); 8159 } 8160 8161 // Check each flag does not conflict with any other component. 8162 if (!FS.hasValidThousandsGroupingPrefix()) 8163 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8164 if (!FS.hasValidLeadingZeros()) 8165 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8166 if (!FS.hasValidPlusPrefix()) 8167 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8168 if (!FS.hasValidSpacePrefix()) 8169 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8170 if (!FS.hasValidAlternativeForm()) 8171 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8172 if (!FS.hasValidLeftJustified()) 8173 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8174 8175 // Check that flags are not ignored by another flag 8176 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8177 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8178 startSpecifier, specifierLen); 8179 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8180 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8181 startSpecifier, specifierLen); 8182 8183 // Check the length modifier is valid with the given conversion specifier. 8184 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8185 S.getLangOpts())) 8186 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8187 diag::warn_format_nonsensical_length); 8188 else if (!FS.hasStandardLengthModifier()) 8189 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8190 else if (!FS.hasStandardLengthConversionCombination()) 8191 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8192 diag::warn_format_non_standard_conversion_spec); 8193 8194 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8195 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8196 8197 // The remaining checks depend on the data arguments. 8198 if (HasVAListArg) 8199 return true; 8200 8201 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8202 return false; 8203 8204 const Expr *Arg = getDataArg(argIndex); 8205 if (!Arg) 8206 return true; 8207 8208 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8209 } 8210 8211 static bool requiresParensToAddCast(const Expr *E) { 8212 // FIXME: We should have a general way to reason about operator 8213 // precedence and whether parens are actually needed here. 8214 // Take care of a few common cases where they aren't. 8215 const Expr *Inside = E->IgnoreImpCasts(); 8216 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8217 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8218 8219 switch (Inside->getStmtClass()) { 8220 case Stmt::ArraySubscriptExprClass: 8221 case Stmt::CallExprClass: 8222 case Stmt::CharacterLiteralClass: 8223 case Stmt::CXXBoolLiteralExprClass: 8224 case Stmt::DeclRefExprClass: 8225 case Stmt::FloatingLiteralClass: 8226 case Stmt::IntegerLiteralClass: 8227 case Stmt::MemberExprClass: 8228 case Stmt::ObjCArrayLiteralClass: 8229 case Stmt::ObjCBoolLiteralExprClass: 8230 case Stmt::ObjCBoxedExprClass: 8231 case Stmt::ObjCDictionaryLiteralClass: 8232 case Stmt::ObjCEncodeExprClass: 8233 case Stmt::ObjCIvarRefExprClass: 8234 case Stmt::ObjCMessageExprClass: 8235 case Stmt::ObjCPropertyRefExprClass: 8236 case Stmt::ObjCStringLiteralClass: 8237 case Stmt::ObjCSubscriptRefExprClass: 8238 case Stmt::ParenExprClass: 8239 case Stmt::StringLiteralClass: 8240 case Stmt::UnaryOperatorClass: 8241 return false; 8242 default: 8243 return true; 8244 } 8245 } 8246 8247 static std::pair<QualType, StringRef> 8248 shouldNotPrintDirectly(const ASTContext &Context, 8249 QualType IntendedTy, 8250 const Expr *E) { 8251 // Use a 'while' to peel off layers of typedefs. 8252 QualType TyTy = IntendedTy; 8253 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8254 StringRef Name = UserTy->getDecl()->getName(); 8255 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8256 .Case("CFIndex", Context.getNSIntegerType()) 8257 .Case("NSInteger", Context.getNSIntegerType()) 8258 .Case("NSUInteger", Context.getNSUIntegerType()) 8259 .Case("SInt32", Context.IntTy) 8260 .Case("UInt32", Context.UnsignedIntTy) 8261 .Default(QualType()); 8262 8263 if (!CastTy.isNull()) 8264 return std::make_pair(CastTy, Name); 8265 8266 TyTy = UserTy->desugar(); 8267 } 8268 8269 // Strip parens if necessary. 8270 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8271 return shouldNotPrintDirectly(Context, 8272 PE->getSubExpr()->getType(), 8273 PE->getSubExpr()); 8274 8275 // If this is a conditional expression, then its result type is constructed 8276 // via usual arithmetic conversions and thus there might be no necessary 8277 // typedef sugar there. Recurse to operands to check for NSInteger & 8278 // Co. usage condition. 8279 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8280 QualType TrueTy, FalseTy; 8281 StringRef TrueName, FalseName; 8282 8283 std::tie(TrueTy, TrueName) = 8284 shouldNotPrintDirectly(Context, 8285 CO->getTrueExpr()->getType(), 8286 CO->getTrueExpr()); 8287 std::tie(FalseTy, FalseName) = 8288 shouldNotPrintDirectly(Context, 8289 CO->getFalseExpr()->getType(), 8290 CO->getFalseExpr()); 8291 8292 if (TrueTy == FalseTy) 8293 return std::make_pair(TrueTy, TrueName); 8294 else if (TrueTy.isNull()) 8295 return std::make_pair(FalseTy, FalseName); 8296 else if (FalseTy.isNull()) 8297 return std::make_pair(TrueTy, TrueName); 8298 } 8299 8300 return std::make_pair(QualType(), StringRef()); 8301 } 8302 8303 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8304 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8305 /// type do not count. 8306 static bool 8307 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8308 QualType From = ICE->getSubExpr()->getType(); 8309 QualType To = ICE->getType(); 8310 // It's an integer promotion if the destination type is the promoted 8311 // source type. 8312 if (ICE->getCastKind() == CK_IntegralCast && 8313 From->isPromotableIntegerType() && 8314 S.Context.getPromotedIntegerType(From) == To) 8315 return true; 8316 // Look through vector types, since we do default argument promotion for 8317 // those in OpenCL. 8318 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8319 From = VecTy->getElementType(); 8320 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8321 To = VecTy->getElementType(); 8322 // It's a floating promotion if the source type is a lower rank. 8323 return ICE->getCastKind() == CK_FloatingCast && 8324 S.Context.getFloatingTypeOrder(From, To) < 0; 8325 } 8326 8327 bool 8328 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8329 const char *StartSpecifier, 8330 unsigned SpecifierLen, 8331 const Expr *E) { 8332 using namespace analyze_format_string; 8333 using namespace analyze_printf; 8334 8335 // Now type check the data expression that matches the 8336 // format specifier. 8337 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8338 if (!AT.isValid()) 8339 return true; 8340 8341 QualType ExprTy = E->getType(); 8342 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8343 ExprTy = TET->getUnderlyingExpr()->getType(); 8344 } 8345 8346 // Diagnose attempts to print a boolean value as a character. Unlike other 8347 // -Wformat diagnostics, this is fine from a type perspective, but it still 8348 // doesn't make sense. 8349 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8350 E->isKnownToHaveBooleanValue()) { 8351 const CharSourceRange &CSR = 8352 getSpecifierRange(StartSpecifier, SpecifierLen); 8353 SmallString<4> FSString; 8354 llvm::raw_svector_ostream os(FSString); 8355 FS.toString(os); 8356 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8357 << FSString, 8358 E->getExprLoc(), false, CSR); 8359 return true; 8360 } 8361 8362 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8363 if (Match == analyze_printf::ArgType::Match) 8364 return true; 8365 8366 // Look through argument promotions for our error message's reported type. 8367 // This includes the integral and floating promotions, but excludes array 8368 // and function pointer decay (seeing that an argument intended to be a 8369 // string has type 'char [6]' is probably more confusing than 'char *') and 8370 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8371 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8372 if (isArithmeticArgumentPromotion(S, ICE)) { 8373 E = ICE->getSubExpr(); 8374 ExprTy = E->getType(); 8375 8376 // Check if we didn't match because of an implicit cast from a 'char' 8377 // or 'short' to an 'int'. This is done because printf is a varargs 8378 // function. 8379 if (ICE->getType() == S.Context.IntTy || 8380 ICE->getType() == S.Context.UnsignedIntTy) { 8381 // All further checking is done on the subexpression 8382 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8383 AT.matchesType(S.Context, ExprTy); 8384 if (ImplicitMatch == analyze_printf::ArgType::Match) 8385 return true; 8386 if (ImplicitMatch == ArgType::NoMatchPedantic || 8387 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8388 Match = ImplicitMatch; 8389 } 8390 } 8391 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8392 // Special case for 'a', which has type 'int' in C. 8393 // Note, however, that we do /not/ want to treat multibyte constants like 8394 // 'MooV' as characters! This form is deprecated but still exists. 8395 if (ExprTy == S.Context.IntTy) 8396 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8397 ExprTy = S.Context.CharTy; 8398 } 8399 8400 // Look through enums to their underlying type. 8401 bool IsEnum = false; 8402 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8403 ExprTy = EnumTy->getDecl()->getIntegerType(); 8404 IsEnum = true; 8405 } 8406 8407 // %C in an Objective-C context prints a unichar, not a wchar_t. 8408 // If the argument is an integer of some kind, believe the %C and suggest 8409 // a cast instead of changing the conversion specifier. 8410 QualType IntendedTy = ExprTy; 8411 if (isObjCContext() && 8412 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8413 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8414 !ExprTy->isCharType()) { 8415 // 'unichar' is defined as a typedef of unsigned short, but we should 8416 // prefer using the typedef if it is visible. 8417 IntendedTy = S.Context.UnsignedShortTy; 8418 8419 // While we are here, check if the value is an IntegerLiteral that happens 8420 // to be within the valid range. 8421 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8422 const llvm::APInt &V = IL->getValue(); 8423 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8424 return true; 8425 } 8426 8427 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8428 Sema::LookupOrdinaryName); 8429 if (S.LookupName(Result, S.getCurScope())) { 8430 NamedDecl *ND = Result.getFoundDecl(); 8431 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8432 if (TD->getUnderlyingType() == IntendedTy) 8433 IntendedTy = S.Context.getTypedefType(TD); 8434 } 8435 } 8436 } 8437 8438 // Special-case some of Darwin's platform-independence types by suggesting 8439 // casts to primitive types that are known to be large enough. 8440 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8441 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8442 QualType CastTy; 8443 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8444 if (!CastTy.isNull()) { 8445 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8446 // (long in ASTContext). Only complain to pedants. 8447 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8448 (AT.isSizeT() || AT.isPtrdiffT()) && 8449 AT.matchesType(S.Context, CastTy)) 8450 Match = ArgType::NoMatchPedantic; 8451 IntendedTy = CastTy; 8452 ShouldNotPrintDirectly = true; 8453 } 8454 } 8455 8456 // We may be able to offer a FixItHint if it is a supported type. 8457 PrintfSpecifier fixedFS = FS; 8458 bool Success = 8459 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8460 8461 if (Success) { 8462 // Get the fix string from the fixed format specifier 8463 SmallString<16> buf; 8464 llvm::raw_svector_ostream os(buf); 8465 fixedFS.toString(os); 8466 8467 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8468 8469 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8470 unsigned Diag; 8471 switch (Match) { 8472 case ArgType::Match: llvm_unreachable("expected non-matching"); 8473 case ArgType::NoMatchPedantic: 8474 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8475 break; 8476 case ArgType::NoMatchTypeConfusion: 8477 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8478 break; 8479 case ArgType::NoMatch: 8480 Diag = diag::warn_format_conversion_argument_type_mismatch; 8481 break; 8482 } 8483 8484 // In this case, the specifier is wrong and should be changed to match 8485 // the argument. 8486 EmitFormatDiagnostic(S.PDiag(Diag) 8487 << AT.getRepresentativeTypeName(S.Context) 8488 << IntendedTy << IsEnum << E->getSourceRange(), 8489 E->getBeginLoc(), 8490 /*IsStringLocation*/ false, SpecRange, 8491 FixItHint::CreateReplacement(SpecRange, os.str())); 8492 } else { 8493 // The canonical type for formatting this value is different from the 8494 // actual type of the expression. (This occurs, for example, with Darwin's 8495 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8496 // should be printed as 'long' for 64-bit compatibility.) 8497 // Rather than emitting a normal format/argument mismatch, we want to 8498 // add a cast to the recommended type (and correct the format string 8499 // if necessary). 8500 SmallString<16> CastBuf; 8501 llvm::raw_svector_ostream CastFix(CastBuf); 8502 CastFix << "("; 8503 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8504 CastFix << ")"; 8505 8506 SmallVector<FixItHint,4> Hints; 8507 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8508 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8509 8510 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8511 // If there's already a cast present, just replace it. 8512 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8513 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8514 8515 } else if (!requiresParensToAddCast(E)) { 8516 // If the expression has high enough precedence, 8517 // just write the C-style cast. 8518 Hints.push_back( 8519 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8520 } else { 8521 // Otherwise, add parens around the expression as well as the cast. 8522 CastFix << "("; 8523 Hints.push_back( 8524 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8525 8526 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8527 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8528 } 8529 8530 if (ShouldNotPrintDirectly) { 8531 // The expression has a type that should not be printed directly. 8532 // We extract the name from the typedef because we don't want to show 8533 // the underlying type in the diagnostic. 8534 StringRef Name; 8535 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8536 Name = TypedefTy->getDecl()->getName(); 8537 else 8538 Name = CastTyName; 8539 unsigned Diag = Match == ArgType::NoMatchPedantic 8540 ? diag::warn_format_argument_needs_cast_pedantic 8541 : diag::warn_format_argument_needs_cast; 8542 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8543 << E->getSourceRange(), 8544 E->getBeginLoc(), /*IsStringLocation=*/false, 8545 SpecRange, Hints); 8546 } else { 8547 // In this case, the expression could be printed using a different 8548 // specifier, but we've decided that the specifier is probably correct 8549 // and we should cast instead. Just use the normal warning message. 8550 EmitFormatDiagnostic( 8551 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8552 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8553 << E->getSourceRange(), 8554 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8555 } 8556 } 8557 } else { 8558 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8559 SpecifierLen); 8560 // Since the warning for passing non-POD types to variadic functions 8561 // was deferred until now, we emit a warning for non-POD 8562 // arguments here. 8563 switch (S.isValidVarArgType(ExprTy)) { 8564 case Sema::VAK_Valid: 8565 case Sema::VAK_ValidInCXX11: { 8566 unsigned Diag; 8567 switch (Match) { 8568 case ArgType::Match: llvm_unreachable("expected non-matching"); 8569 case ArgType::NoMatchPedantic: 8570 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8571 break; 8572 case ArgType::NoMatchTypeConfusion: 8573 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8574 break; 8575 case ArgType::NoMatch: 8576 Diag = diag::warn_format_conversion_argument_type_mismatch; 8577 break; 8578 } 8579 8580 EmitFormatDiagnostic( 8581 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8582 << IsEnum << CSR << E->getSourceRange(), 8583 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8584 break; 8585 } 8586 case Sema::VAK_Undefined: 8587 case Sema::VAK_MSVCUndefined: 8588 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8589 << S.getLangOpts().CPlusPlus11 << ExprTy 8590 << CallType 8591 << AT.getRepresentativeTypeName(S.Context) << CSR 8592 << E->getSourceRange(), 8593 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8594 checkForCStrMembers(AT, E); 8595 break; 8596 8597 case Sema::VAK_Invalid: 8598 if (ExprTy->isObjCObjectType()) 8599 EmitFormatDiagnostic( 8600 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8601 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8602 << AT.getRepresentativeTypeName(S.Context) << CSR 8603 << E->getSourceRange(), 8604 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8605 else 8606 // FIXME: If this is an initializer list, suggest removing the braces 8607 // or inserting a cast to the target type. 8608 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8609 << isa<InitListExpr>(E) << ExprTy << CallType 8610 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8611 break; 8612 } 8613 8614 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8615 "format string specifier index out of range"); 8616 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8617 } 8618 8619 return true; 8620 } 8621 8622 //===--- CHECK: Scanf format string checking ------------------------------===// 8623 8624 namespace { 8625 8626 class CheckScanfHandler : public CheckFormatHandler { 8627 public: 8628 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8629 const Expr *origFormatExpr, Sema::FormatStringType type, 8630 unsigned firstDataArg, unsigned numDataArgs, 8631 const char *beg, bool hasVAListArg, 8632 ArrayRef<const Expr *> Args, unsigned formatIdx, 8633 bool inFunctionCall, Sema::VariadicCallType CallType, 8634 llvm::SmallBitVector &CheckedVarArgs, 8635 UncoveredArgHandler &UncoveredArg) 8636 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8637 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8638 inFunctionCall, CallType, CheckedVarArgs, 8639 UncoveredArg) {} 8640 8641 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8642 const char *startSpecifier, 8643 unsigned specifierLen) override; 8644 8645 bool HandleInvalidScanfConversionSpecifier( 8646 const analyze_scanf::ScanfSpecifier &FS, 8647 const char *startSpecifier, 8648 unsigned specifierLen) override; 8649 8650 void HandleIncompleteScanList(const char *start, const char *end) override; 8651 }; 8652 8653 } // namespace 8654 8655 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8656 const char *end) { 8657 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8658 getLocationOfByte(end), /*IsStringLocation*/true, 8659 getSpecifierRange(start, end - start)); 8660 } 8661 8662 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8663 const analyze_scanf::ScanfSpecifier &FS, 8664 const char *startSpecifier, 8665 unsigned specifierLen) { 8666 const analyze_scanf::ScanfConversionSpecifier &CS = 8667 FS.getConversionSpecifier(); 8668 8669 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8670 getLocationOfByte(CS.getStart()), 8671 startSpecifier, specifierLen, 8672 CS.getStart(), CS.getLength()); 8673 } 8674 8675 bool CheckScanfHandler::HandleScanfSpecifier( 8676 const analyze_scanf::ScanfSpecifier &FS, 8677 const char *startSpecifier, 8678 unsigned specifierLen) { 8679 using namespace analyze_scanf; 8680 using namespace analyze_format_string; 8681 8682 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8683 8684 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8685 // be used to decide if we are using positional arguments consistently. 8686 if (FS.consumesDataArgument()) { 8687 if (atFirstArg) { 8688 atFirstArg = false; 8689 usesPositionalArgs = FS.usesPositionalArg(); 8690 } 8691 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8692 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8693 startSpecifier, specifierLen); 8694 return false; 8695 } 8696 } 8697 8698 // Check if the field with is non-zero. 8699 const OptionalAmount &Amt = FS.getFieldWidth(); 8700 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8701 if (Amt.getConstantAmount() == 0) { 8702 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8703 Amt.getConstantLength()); 8704 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8705 getLocationOfByte(Amt.getStart()), 8706 /*IsStringLocation*/true, R, 8707 FixItHint::CreateRemoval(R)); 8708 } 8709 } 8710 8711 if (!FS.consumesDataArgument()) { 8712 // FIXME: Technically specifying a precision or field width here 8713 // makes no sense. Worth issuing a warning at some point. 8714 return true; 8715 } 8716 8717 // Consume the argument. 8718 unsigned argIndex = FS.getArgIndex(); 8719 if (argIndex < NumDataArgs) { 8720 // The check to see if the argIndex is valid will come later. 8721 // We set the bit here because we may exit early from this 8722 // function if we encounter some other error. 8723 CoveredArgs.set(argIndex); 8724 } 8725 8726 // Check the length modifier is valid with the given conversion specifier. 8727 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8728 S.getLangOpts())) 8729 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8730 diag::warn_format_nonsensical_length); 8731 else if (!FS.hasStandardLengthModifier()) 8732 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8733 else if (!FS.hasStandardLengthConversionCombination()) 8734 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8735 diag::warn_format_non_standard_conversion_spec); 8736 8737 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8738 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8739 8740 // The remaining checks depend on the data arguments. 8741 if (HasVAListArg) 8742 return true; 8743 8744 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8745 return false; 8746 8747 // Check that the argument type matches the format specifier. 8748 const Expr *Ex = getDataArg(argIndex); 8749 if (!Ex) 8750 return true; 8751 8752 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8753 8754 if (!AT.isValid()) { 8755 return true; 8756 } 8757 8758 analyze_format_string::ArgType::MatchKind Match = 8759 AT.matchesType(S.Context, Ex->getType()); 8760 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8761 if (Match == analyze_format_string::ArgType::Match) 8762 return true; 8763 8764 ScanfSpecifier fixedFS = FS; 8765 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8766 S.getLangOpts(), S.Context); 8767 8768 unsigned Diag = 8769 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8770 : diag::warn_format_conversion_argument_type_mismatch; 8771 8772 if (Success) { 8773 // Get the fix string from the fixed format specifier. 8774 SmallString<128> buf; 8775 llvm::raw_svector_ostream os(buf); 8776 fixedFS.toString(os); 8777 8778 EmitFormatDiagnostic( 8779 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8780 << Ex->getType() << false << Ex->getSourceRange(), 8781 Ex->getBeginLoc(), 8782 /*IsStringLocation*/ false, 8783 getSpecifierRange(startSpecifier, specifierLen), 8784 FixItHint::CreateReplacement( 8785 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8786 } else { 8787 EmitFormatDiagnostic(S.PDiag(Diag) 8788 << AT.getRepresentativeTypeName(S.Context) 8789 << Ex->getType() << false << Ex->getSourceRange(), 8790 Ex->getBeginLoc(), 8791 /*IsStringLocation*/ false, 8792 getSpecifierRange(startSpecifier, specifierLen)); 8793 } 8794 8795 return true; 8796 } 8797 8798 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8799 const Expr *OrigFormatExpr, 8800 ArrayRef<const Expr *> Args, 8801 bool HasVAListArg, unsigned format_idx, 8802 unsigned firstDataArg, 8803 Sema::FormatStringType Type, 8804 bool inFunctionCall, 8805 Sema::VariadicCallType CallType, 8806 llvm::SmallBitVector &CheckedVarArgs, 8807 UncoveredArgHandler &UncoveredArg, 8808 bool IgnoreStringsWithoutSpecifiers) { 8809 // CHECK: is the format string a wide literal? 8810 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8811 CheckFormatHandler::EmitFormatDiagnostic( 8812 S, inFunctionCall, Args[format_idx], 8813 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8814 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8815 return; 8816 } 8817 8818 // Str - The format string. NOTE: this is NOT null-terminated! 8819 StringRef StrRef = FExpr->getString(); 8820 const char *Str = StrRef.data(); 8821 // Account for cases where the string literal is truncated in a declaration. 8822 const ConstantArrayType *T = 8823 S.Context.getAsConstantArrayType(FExpr->getType()); 8824 assert(T && "String literal not of constant array type!"); 8825 size_t TypeSize = T->getSize().getZExtValue(); 8826 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8827 const unsigned numDataArgs = Args.size() - firstDataArg; 8828 8829 if (IgnoreStringsWithoutSpecifiers && 8830 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8831 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8832 return; 8833 8834 // Emit a warning if the string literal is truncated and does not contain an 8835 // embedded null character. 8836 if (TypeSize <= StrRef.size() && 8837 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8838 CheckFormatHandler::EmitFormatDiagnostic( 8839 S, inFunctionCall, Args[format_idx], 8840 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8841 FExpr->getBeginLoc(), 8842 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8843 return; 8844 } 8845 8846 // CHECK: empty format string? 8847 if (StrLen == 0 && numDataArgs > 0) { 8848 CheckFormatHandler::EmitFormatDiagnostic( 8849 S, inFunctionCall, Args[format_idx], 8850 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8851 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8852 return; 8853 } 8854 8855 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8856 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8857 Type == Sema::FST_OSTrace) { 8858 CheckPrintfHandler H( 8859 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8860 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8861 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8862 CheckedVarArgs, UncoveredArg); 8863 8864 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8865 S.getLangOpts(), 8866 S.Context.getTargetInfo(), 8867 Type == Sema::FST_FreeBSDKPrintf)) 8868 H.DoneProcessing(); 8869 } else if (Type == Sema::FST_Scanf) { 8870 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8871 numDataArgs, Str, HasVAListArg, Args, format_idx, 8872 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8873 8874 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8875 S.getLangOpts(), 8876 S.Context.getTargetInfo())) 8877 H.DoneProcessing(); 8878 } // TODO: handle other formats 8879 } 8880 8881 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8882 // Str - The format string. NOTE: this is NOT null-terminated! 8883 StringRef StrRef = FExpr->getString(); 8884 const char *Str = StrRef.data(); 8885 // Account for cases where the string literal is truncated in a declaration. 8886 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8887 assert(T && "String literal not of constant array type!"); 8888 size_t TypeSize = T->getSize().getZExtValue(); 8889 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8890 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8891 getLangOpts(), 8892 Context.getTargetInfo()); 8893 } 8894 8895 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8896 8897 // Returns the related absolute value function that is larger, of 0 if one 8898 // does not exist. 8899 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8900 switch (AbsFunction) { 8901 default: 8902 return 0; 8903 8904 case Builtin::BI__builtin_abs: 8905 return Builtin::BI__builtin_labs; 8906 case Builtin::BI__builtin_labs: 8907 return Builtin::BI__builtin_llabs; 8908 case Builtin::BI__builtin_llabs: 8909 return 0; 8910 8911 case Builtin::BI__builtin_fabsf: 8912 return Builtin::BI__builtin_fabs; 8913 case Builtin::BI__builtin_fabs: 8914 return Builtin::BI__builtin_fabsl; 8915 case Builtin::BI__builtin_fabsl: 8916 return 0; 8917 8918 case Builtin::BI__builtin_cabsf: 8919 return Builtin::BI__builtin_cabs; 8920 case Builtin::BI__builtin_cabs: 8921 return Builtin::BI__builtin_cabsl; 8922 case Builtin::BI__builtin_cabsl: 8923 return 0; 8924 8925 case Builtin::BIabs: 8926 return Builtin::BIlabs; 8927 case Builtin::BIlabs: 8928 return Builtin::BIllabs; 8929 case Builtin::BIllabs: 8930 return 0; 8931 8932 case Builtin::BIfabsf: 8933 return Builtin::BIfabs; 8934 case Builtin::BIfabs: 8935 return Builtin::BIfabsl; 8936 case Builtin::BIfabsl: 8937 return 0; 8938 8939 case Builtin::BIcabsf: 8940 return Builtin::BIcabs; 8941 case Builtin::BIcabs: 8942 return Builtin::BIcabsl; 8943 case Builtin::BIcabsl: 8944 return 0; 8945 } 8946 } 8947 8948 // Returns the argument type of the absolute value function. 8949 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8950 unsigned AbsType) { 8951 if (AbsType == 0) 8952 return QualType(); 8953 8954 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8955 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8956 if (Error != ASTContext::GE_None) 8957 return QualType(); 8958 8959 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8960 if (!FT) 8961 return QualType(); 8962 8963 if (FT->getNumParams() != 1) 8964 return QualType(); 8965 8966 return FT->getParamType(0); 8967 } 8968 8969 // Returns the best absolute value function, or zero, based on type and 8970 // current absolute value function. 8971 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8972 unsigned AbsFunctionKind) { 8973 unsigned BestKind = 0; 8974 uint64_t ArgSize = Context.getTypeSize(ArgType); 8975 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8976 Kind = getLargerAbsoluteValueFunction(Kind)) { 8977 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8978 if (Context.getTypeSize(ParamType) >= ArgSize) { 8979 if (BestKind == 0) 8980 BestKind = Kind; 8981 else if (Context.hasSameType(ParamType, ArgType)) { 8982 BestKind = Kind; 8983 break; 8984 } 8985 } 8986 } 8987 return BestKind; 8988 } 8989 8990 enum AbsoluteValueKind { 8991 AVK_Integer, 8992 AVK_Floating, 8993 AVK_Complex 8994 }; 8995 8996 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8997 if (T->isIntegralOrEnumerationType()) 8998 return AVK_Integer; 8999 if (T->isRealFloatingType()) 9000 return AVK_Floating; 9001 if (T->isAnyComplexType()) 9002 return AVK_Complex; 9003 9004 llvm_unreachable("Type not integer, floating, or complex"); 9005 } 9006 9007 // Changes the absolute value function to a different type. Preserves whether 9008 // the function is a builtin. 9009 static unsigned changeAbsFunction(unsigned AbsKind, 9010 AbsoluteValueKind ValueKind) { 9011 switch (ValueKind) { 9012 case AVK_Integer: 9013 switch (AbsKind) { 9014 default: 9015 return 0; 9016 case Builtin::BI__builtin_fabsf: 9017 case Builtin::BI__builtin_fabs: 9018 case Builtin::BI__builtin_fabsl: 9019 case Builtin::BI__builtin_cabsf: 9020 case Builtin::BI__builtin_cabs: 9021 case Builtin::BI__builtin_cabsl: 9022 return Builtin::BI__builtin_abs; 9023 case Builtin::BIfabsf: 9024 case Builtin::BIfabs: 9025 case Builtin::BIfabsl: 9026 case Builtin::BIcabsf: 9027 case Builtin::BIcabs: 9028 case Builtin::BIcabsl: 9029 return Builtin::BIabs; 9030 } 9031 case AVK_Floating: 9032 switch (AbsKind) { 9033 default: 9034 return 0; 9035 case Builtin::BI__builtin_abs: 9036 case Builtin::BI__builtin_labs: 9037 case Builtin::BI__builtin_llabs: 9038 case Builtin::BI__builtin_cabsf: 9039 case Builtin::BI__builtin_cabs: 9040 case Builtin::BI__builtin_cabsl: 9041 return Builtin::BI__builtin_fabsf; 9042 case Builtin::BIabs: 9043 case Builtin::BIlabs: 9044 case Builtin::BIllabs: 9045 case Builtin::BIcabsf: 9046 case Builtin::BIcabs: 9047 case Builtin::BIcabsl: 9048 return Builtin::BIfabsf; 9049 } 9050 case AVK_Complex: 9051 switch (AbsKind) { 9052 default: 9053 return 0; 9054 case Builtin::BI__builtin_abs: 9055 case Builtin::BI__builtin_labs: 9056 case Builtin::BI__builtin_llabs: 9057 case Builtin::BI__builtin_fabsf: 9058 case Builtin::BI__builtin_fabs: 9059 case Builtin::BI__builtin_fabsl: 9060 return Builtin::BI__builtin_cabsf; 9061 case Builtin::BIabs: 9062 case Builtin::BIlabs: 9063 case Builtin::BIllabs: 9064 case Builtin::BIfabsf: 9065 case Builtin::BIfabs: 9066 case Builtin::BIfabsl: 9067 return Builtin::BIcabsf; 9068 } 9069 } 9070 llvm_unreachable("Unable to convert function"); 9071 } 9072 9073 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9074 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9075 if (!FnInfo) 9076 return 0; 9077 9078 switch (FDecl->getBuiltinID()) { 9079 default: 9080 return 0; 9081 case Builtin::BI__builtin_abs: 9082 case Builtin::BI__builtin_fabs: 9083 case Builtin::BI__builtin_fabsf: 9084 case Builtin::BI__builtin_fabsl: 9085 case Builtin::BI__builtin_labs: 9086 case Builtin::BI__builtin_llabs: 9087 case Builtin::BI__builtin_cabs: 9088 case Builtin::BI__builtin_cabsf: 9089 case Builtin::BI__builtin_cabsl: 9090 case Builtin::BIabs: 9091 case Builtin::BIlabs: 9092 case Builtin::BIllabs: 9093 case Builtin::BIfabs: 9094 case Builtin::BIfabsf: 9095 case Builtin::BIfabsl: 9096 case Builtin::BIcabs: 9097 case Builtin::BIcabsf: 9098 case Builtin::BIcabsl: 9099 return FDecl->getBuiltinID(); 9100 } 9101 llvm_unreachable("Unknown Builtin type"); 9102 } 9103 9104 // If the replacement is valid, emit a note with replacement function. 9105 // Additionally, suggest including the proper header if not already included. 9106 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9107 unsigned AbsKind, QualType ArgType) { 9108 bool EmitHeaderHint = true; 9109 const char *HeaderName = nullptr; 9110 const char *FunctionName = nullptr; 9111 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9112 FunctionName = "std::abs"; 9113 if (ArgType->isIntegralOrEnumerationType()) { 9114 HeaderName = "cstdlib"; 9115 } else if (ArgType->isRealFloatingType()) { 9116 HeaderName = "cmath"; 9117 } else { 9118 llvm_unreachable("Invalid Type"); 9119 } 9120 9121 // Lookup all std::abs 9122 if (NamespaceDecl *Std = S.getStdNamespace()) { 9123 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9124 R.suppressDiagnostics(); 9125 S.LookupQualifiedName(R, Std); 9126 9127 for (const auto *I : R) { 9128 const FunctionDecl *FDecl = nullptr; 9129 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9130 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9131 } else { 9132 FDecl = dyn_cast<FunctionDecl>(I); 9133 } 9134 if (!FDecl) 9135 continue; 9136 9137 // Found std::abs(), check that they are the right ones. 9138 if (FDecl->getNumParams() != 1) 9139 continue; 9140 9141 // Check that the parameter type can handle the argument. 9142 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9143 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9144 S.Context.getTypeSize(ArgType) <= 9145 S.Context.getTypeSize(ParamType)) { 9146 // Found a function, don't need the header hint. 9147 EmitHeaderHint = false; 9148 break; 9149 } 9150 } 9151 } 9152 } else { 9153 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9154 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9155 9156 if (HeaderName) { 9157 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9158 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9159 R.suppressDiagnostics(); 9160 S.LookupName(R, S.getCurScope()); 9161 9162 if (R.isSingleResult()) { 9163 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9164 if (FD && FD->getBuiltinID() == AbsKind) { 9165 EmitHeaderHint = false; 9166 } else { 9167 return; 9168 } 9169 } else if (!R.empty()) { 9170 return; 9171 } 9172 } 9173 } 9174 9175 S.Diag(Loc, diag::note_replace_abs_function) 9176 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9177 9178 if (!HeaderName) 9179 return; 9180 9181 if (!EmitHeaderHint) 9182 return; 9183 9184 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9185 << FunctionName; 9186 } 9187 9188 template <std::size_t StrLen> 9189 static bool IsStdFunction(const FunctionDecl *FDecl, 9190 const char (&Str)[StrLen]) { 9191 if (!FDecl) 9192 return false; 9193 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9194 return false; 9195 if (!FDecl->isInStdNamespace()) 9196 return false; 9197 9198 return true; 9199 } 9200 9201 // Warn when using the wrong abs() function. 9202 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9203 const FunctionDecl *FDecl) { 9204 if (Call->getNumArgs() != 1) 9205 return; 9206 9207 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9208 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9209 if (AbsKind == 0 && !IsStdAbs) 9210 return; 9211 9212 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9213 QualType ParamType = Call->getArg(0)->getType(); 9214 9215 // Unsigned types cannot be negative. Suggest removing the absolute value 9216 // function call. 9217 if (ArgType->isUnsignedIntegerType()) { 9218 const char *FunctionName = 9219 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9220 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9221 Diag(Call->getExprLoc(), diag::note_remove_abs) 9222 << FunctionName 9223 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9224 return; 9225 } 9226 9227 // Taking the absolute value of a pointer is very suspicious, they probably 9228 // wanted to index into an array, dereference a pointer, call a function, etc. 9229 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9230 unsigned DiagType = 0; 9231 if (ArgType->isFunctionType()) 9232 DiagType = 1; 9233 else if (ArgType->isArrayType()) 9234 DiagType = 2; 9235 9236 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9237 return; 9238 } 9239 9240 // std::abs has overloads which prevent most of the absolute value problems 9241 // from occurring. 9242 if (IsStdAbs) 9243 return; 9244 9245 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9246 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9247 9248 // The argument and parameter are the same kind. Check if they are the right 9249 // size. 9250 if (ArgValueKind == ParamValueKind) { 9251 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9252 return; 9253 9254 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9255 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9256 << FDecl << ArgType << ParamType; 9257 9258 if (NewAbsKind == 0) 9259 return; 9260 9261 emitReplacement(*this, Call->getExprLoc(), 9262 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9263 return; 9264 } 9265 9266 // ArgValueKind != ParamValueKind 9267 // The wrong type of absolute value function was used. Attempt to find the 9268 // proper one. 9269 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9270 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9271 if (NewAbsKind == 0) 9272 return; 9273 9274 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9275 << FDecl << ParamValueKind << ArgValueKind; 9276 9277 emitReplacement(*this, Call->getExprLoc(), 9278 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9279 } 9280 9281 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9282 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9283 const FunctionDecl *FDecl) { 9284 if (!Call || !FDecl) return; 9285 9286 // Ignore template specializations and macros. 9287 if (inTemplateInstantiation()) return; 9288 if (Call->getExprLoc().isMacroID()) return; 9289 9290 // Only care about the one template argument, two function parameter std::max 9291 if (Call->getNumArgs() != 2) return; 9292 if (!IsStdFunction(FDecl, "max")) return; 9293 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9294 if (!ArgList) return; 9295 if (ArgList->size() != 1) return; 9296 9297 // Check that template type argument is unsigned integer. 9298 const auto& TA = ArgList->get(0); 9299 if (TA.getKind() != TemplateArgument::Type) return; 9300 QualType ArgType = TA.getAsType(); 9301 if (!ArgType->isUnsignedIntegerType()) return; 9302 9303 // See if either argument is a literal zero. 9304 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9305 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9306 if (!MTE) return false; 9307 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9308 if (!Num) return false; 9309 if (Num->getValue() != 0) return false; 9310 return true; 9311 }; 9312 9313 const Expr *FirstArg = Call->getArg(0); 9314 const Expr *SecondArg = Call->getArg(1); 9315 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9316 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9317 9318 // Only warn when exactly one argument is zero. 9319 if (IsFirstArgZero == IsSecondArgZero) return; 9320 9321 SourceRange FirstRange = FirstArg->getSourceRange(); 9322 SourceRange SecondRange = SecondArg->getSourceRange(); 9323 9324 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9325 9326 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9327 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9328 9329 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9330 SourceRange RemovalRange; 9331 if (IsFirstArgZero) { 9332 RemovalRange = SourceRange(FirstRange.getBegin(), 9333 SecondRange.getBegin().getLocWithOffset(-1)); 9334 } else { 9335 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9336 SecondRange.getEnd()); 9337 } 9338 9339 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9340 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9341 << FixItHint::CreateRemoval(RemovalRange); 9342 } 9343 9344 //===--- CHECK: Standard memory functions ---------------------------------===// 9345 9346 /// Takes the expression passed to the size_t parameter of functions 9347 /// such as memcmp, strncat, etc and warns if it's a comparison. 9348 /// 9349 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9350 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9351 IdentifierInfo *FnName, 9352 SourceLocation FnLoc, 9353 SourceLocation RParenLoc) { 9354 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9355 if (!Size) 9356 return false; 9357 9358 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9359 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9360 return false; 9361 9362 SourceRange SizeRange = Size->getSourceRange(); 9363 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9364 << SizeRange << FnName; 9365 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9366 << FnName 9367 << FixItHint::CreateInsertion( 9368 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9369 << FixItHint::CreateRemoval(RParenLoc); 9370 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9371 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9372 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9373 ")"); 9374 9375 return true; 9376 } 9377 9378 /// Determine whether the given type is or contains a dynamic class type 9379 /// (e.g., whether it has a vtable). 9380 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9381 bool &IsContained) { 9382 // Look through array types while ignoring qualifiers. 9383 const Type *Ty = T->getBaseElementTypeUnsafe(); 9384 IsContained = false; 9385 9386 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9387 RD = RD ? RD->getDefinition() : nullptr; 9388 if (!RD || RD->isInvalidDecl()) 9389 return nullptr; 9390 9391 if (RD->isDynamicClass()) 9392 return RD; 9393 9394 // Check all the fields. If any bases were dynamic, the class is dynamic. 9395 // It's impossible for a class to transitively contain itself by value, so 9396 // infinite recursion is impossible. 9397 for (auto *FD : RD->fields()) { 9398 bool SubContained; 9399 if (const CXXRecordDecl *ContainedRD = 9400 getContainedDynamicClass(FD->getType(), SubContained)) { 9401 IsContained = true; 9402 return ContainedRD; 9403 } 9404 } 9405 9406 return nullptr; 9407 } 9408 9409 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9410 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9411 if (Unary->getKind() == UETT_SizeOf) 9412 return Unary; 9413 return nullptr; 9414 } 9415 9416 /// If E is a sizeof expression, returns its argument expression, 9417 /// otherwise returns NULL. 9418 static const Expr *getSizeOfExprArg(const Expr *E) { 9419 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9420 if (!SizeOf->isArgumentType()) 9421 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9422 return nullptr; 9423 } 9424 9425 /// If E is a sizeof expression, returns its argument type. 9426 static QualType getSizeOfArgType(const Expr *E) { 9427 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9428 return SizeOf->getTypeOfArgument(); 9429 return QualType(); 9430 } 9431 9432 namespace { 9433 9434 struct SearchNonTrivialToInitializeField 9435 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9436 using Super = 9437 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9438 9439 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9440 9441 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9442 SourceLocation SL) { 9443 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9444 asDerived().visitArray(PDIK, AT, SL); 9445 return; 9446 } 9447 9448 Super::visitWithKind(PDIK, FT, SL); 9449 } 9450 9451 void visitARCStrong(QualType FT, SourceLocation SL) { 9452 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9453 } 9454 void visitARCWeak(QualType FT, SourceLocation SL) { 9455 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9456 } 9457 void visitStruct(QualType FT, SourceLocation SL) { 9458 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9459 visit(FD->getType(), FD->getLocation()); 9460 } 9461 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9462 const ArrayType *AT, SourceLocation SL) { 9463 visit(getContext().getBaseElementType(AT), SL); 9464 } 9465 void visitTrivial(QualType FT, SourceLocation SL) {} 9466 9467 static void diag(QualType RT, const Expr *E, Sema &S) { 9468 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9469 } 9470 9471 ASTContext &getContext() { return S.getASTContext(); } 9472 9473 const Expr *E; 9474 Sema &S; 9475 }; 9476 9477 struct SearchNonTrivialToCopyField 9478 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9479 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9480 9481 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9482 9483 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9484 SourceLocation SL) { 9485 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9486 asDerived().visitArray(PCK, AT, SL); 9487 return; 9488 } 9489 9490 Super::visitWithKind(PCK, FT, SL); 9491 } 9492 9493 void visitARCStrong(QualType FT, SourceLocation SL) { 9494 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9495 } 9496 void visitARCWeak(QualType FT, SourceLocation SL) { 9497 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9498 } 9499 void visitStruct(QualType FT, SourceLocation SL) { 9500 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9501 visit(FD->getType(), FD->getLocation()); 9502 } 9503 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9504 SourceLocation SL) { 9505 visit(getContext().getBaseElementType(AT), SL); 9506 } 9507 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9508 SourceLocation SL) {} 9509 void visitTrivial(QualType FT, SourceLocation SL) {} 9510 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9511 9512 static void diag(QualType RT, const Expr *E, Sema &S) { 9513 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9514 } 9515 9516 ASTContext &getContext() { return S.getASTContext(); } 9517 9518 const Expr *E; 9519 Sema &S; 9520 }; 9521 9522 } 9523 9524 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9525 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9526 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9527 9528 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9529 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9530 return false; 9531 9532 return doesExprLikelyComputeSize(BO->getLHS()) || 9533 doesExprLikelyComputeSize(BO->getRHS()); 9534 } 9535 9536 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9537 } 9538 9539 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9540 /// 9541 /// \code 9542 /// #define MACRO 0 9543 /// foo(MACRO); 9544 /// foo(0); 9545 /// \endcode 9546 /// 9547 /// This should return true for the first call to foo, but not for the second 9548 /// (regardless of whether foo is a macro or function). 9549 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9550 SourceLocation CallLoc, 9551 SourceLocation ArgLoc) { 9552 if (!CallLoc.isMacroID()) 9553 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9554 9555 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9556 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9557 } 9558 9559 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9560 /// last two arguments transposed. 9561 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9562 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9563 return; 9564 9565 const Expr *SizeArg = 9566 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9567 9568 auto isLiteralZero = [](const Expr *E) { 9569 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9570 }; 9571 9572 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9573 SourceLocation CallLoc = Call->getRParenLoc(); 9574 SourceManager &SM = S.getSourceManager(); 9575 if (isLiteralZero(SizeArg) && 9576 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9577 9578 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9579 9580 // Some platforms #define bzero to __builtin_memset. See if this is the 9581 // case, and if so, emit a better diagnostic. 9582 if (BId == Builtin::BIbzero || 9583 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9584 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9585 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9586 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9587 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9588 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9589 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9590 } 9591 return; 9592 } 9593 9594 // If the second argument to a memset is a sizeof expression and the third 9595 // isn't, this is also likely an error. This should catch 9596 // 'memset(buf, sizeof(buf), 0xff)'. 9597 if (BId == Builtin::BImemset && 9598 doesExprLikelyComputeSize(Call->getArg(1)) && 9599 !doesExprLikelyComputeSize(Call->getArg(2))) { 9600 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9601 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9602 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9603 return; 9604 } 9605 } 9606 9607 /// Check for dangerous or invalid arguments to memset(). 9608 /// 9609 /// This issues warnings on known problematic, dangerous or unspecified 9610 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9611 /// function calls. 9612 /// 9613 /// \param Call The call expression to diagnose. 9614 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9615 unsigned BId, 9616 IdentifierInfo *FnName) { 9617 assert(BId != 0); 9618 9619 // It is possible to have a non-standard definition of memset. Validate 9620 // we have enough arguments, and if not, abort further checking. 9621 unsigned ExpectedNumArgs = 9622 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9623 if (Call->getNumArgs() < ExpectedNumArgs) 9624 return; 9625 9626 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9627 BId == Builtin::BIstrndup ? 1 : 2); 9628 unsigned LenArg = 9629 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9630 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9631 9632 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9633 Call->getBeginLoc(), Call->getRParenLoc())) 9634 return; 9635 9636 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9637 CheckMemaccessSize(*this, BId, Call); 9638 9639 // We have special checking when the length is a sizeof expression. 9640 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9641 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9642 llvm::FoldingSetNodeID SizeOfArgID; 9643 9644 // Although widely used, 'bzero' is not a standard function. Be more strict 9645 // with the argument types before allowing diagnostics and only allow the 9646 // form bzero(ptr, sizeof(...)). 9647 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9648 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9649 return; 9650 9651 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9652 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9653 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9654 9655 QualType DestTy = Dest->getType(); 9656 QualType PointeeTy; 9657 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9658 PointeeTy = DestPtrTy->getPointeeType(); 9659 9660 // Never warn about void type pointers. This can be used to suppress 9661 // false positives. 9662 if (PointeeTy->isVoidType()) 9663 continue; 9664 9665 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9666 // actually comparing the expressions for equality. Because computing the 9667 // expression IDs can be expensive, we only do this if the diagnostic is 9668 // enabled. 9669 if (SizeOfArg && 9670 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9671 SizeOfArg->getExprLoc())) { 9672 // We only compute IDs for expressions if the warning is enabled, and 9673 // cache the sizeof arg's ID. 9674 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9675 SizeOfArg->Profile(SizeOfArgID, Context, true); 9676 llvm::FoldingSetNodeID DestID; 9677 Dest->Profile(DestID, Context, true); 9678 if (DestID == SizeOfArgID) { 9679 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9680 // over sizeof(src) as well. 9681 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9682 StringRef ReadableName = FnName->getName(); 9683 9684 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9685 if (UnaryOp->getOpcode() == UO_AddrOf) 9686 ActionIdx = 1; // If its an address-of operator, just remove it. 9687 if (!PointeeTy->isIncompleteType() && 9688 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9689 ActionIdx = 2; // If the pointee's size is sizeof(char), 9690 // suggest an explicit length. 9691 9692 // If the function is defined as a builtin macro, do not show macro 9693 // expansion. 9694 SourceLocation SL = SizeOfArg->getExprLoc(); 9695 SourceRange DSR = Dest->getSourceRange(); 9696 SourceRange SSR = SizeOfArg->getSourceRange(); 9697 SourceManager &SM = getSourceManager(); 9698 9699 if (SM.isMacroArgExpansion(SL)) { 9700 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9701 SL = SM.getSpellingLoc(SL); 9702 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9703 SM.getSpellingLoc(DSR.getEnd())); 9704 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9705 SM.getSpellingLoc(SSR.getEnd())); 9706 } 9707 9708 DiagRuntimeBehavior(SL, SizeOfArg, 9709 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9710 << ReadableName 9711 << PointeeTy 9712 << DestTy 9713 << DSR 9714 << SSR); 9715 DiagRuntimeBehavior(SL, SizeOfArg, 9716 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9717 << ActionIdx 9718 << SSR); 9719 9720 break; 9721 } 9722 } 9723 9724 // Also check for cases where the sizeof argument is the exact same 9725 // type as the memory argument, and where it points to a user-defined 9726 // record type. 9727 if (SizeOfArgTy != QualType()) { 9728 if (PointeeTy->isRecordType() && 9729 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9730 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9731 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9732 << FnName << SizeOfArgTy << ArgIdx 9733 << PointeeTy << Dest->getSourceRange() 9734 << LenExpr->getSourceRange()); 9735 break; 9736 } 9737 } 9738 } else if (DestTy->isArrayType()) { 9739 PointeeTy = DestTy; 9740 } 9741 9742 if (PointeeTy == QualType()) 9743 continue; 9744 9745 // Always complain about dynamic classes. 9746 bool IsContained; 9747 if (const CXXRecordDecl *ContainedRD = 9748 getContainedDynamicClass(PointeeTy, IsContained)) { 9749 9750 unsigned OperationType = 0; 9751 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9752 // "overwritten" if we're warning about the destination for any call 9753 // but memcmp; otherwise a verb appropriate to the call. 9754 if (ArgIdx != 0 || IsCmp) { 9755 if (BId == Builtin::BImemcpy) 9756 OperationType = 1; 9757 else if(BId == Builtin::BImemmove) 9758 OperationType = 2; 9759 else if (IsCmp) 9760 OperationType = 3; 9761 } 9762 9763 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9764 PDiag(diag::warn_dyn_class_memaccess) 9765 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9766 << IsContained << ContainedRD << OperationType 9767 << Call->getCallee()->getSourceRange()); 9768 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9769 BId != Builtin::BImemset) 9770 DiagRuntimeBehavior( 9771 Dest->getExprLoc(), Dest, 9772 PDiag(diag::warn_arc_object_memaccess) 9773 << ArgIdx << FnName << PointeeTy 9774 << Call->getCallee()->getSourceRange()); 9775 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9776 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9777 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9778 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9779 PDiag(diag::warn_cstruct_memaccess) 9780 << ArgIdx << FnName << PointeeTy << 0); 9781 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9782 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9783 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9784 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9785 PDiag(diag::warn_cstruct_memaccess) 9786 << ArgIdx << FnName << PointeeTy << 1); 9787 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9788 } else { 9789 continue; 9790 } 9791 } else 9792 continue; 9793 9794 DiagRuntimeBehavior( 9795 Dest->getExprLoc(), Dest, 9796 PDiag(diag::note_bad_memaccess_silence) 9797 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9798 break; 9799 } 9800 } 9801 9802 // A little helper routine: ignore addition and subtraction of integer literals. 9803 // This intentionally does not ignore all integer constant expressions because 9804 // we don't want to remove sizeof(). 9805 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9806 Ex = Ex->IgnoreParenCasts(); 9807 9808 while (true) { 9809 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9810 if (!BO || !BO->isAdditiveOp()) 9811 break; 9812 9813 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9814 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9815 9816 if (isa<IntegerLiteral>(RHS)) 9817 Ex = LHS; 9818 else if (isa<IntegerLiteral>(LHS)) 9819 Ex = RHS; 9820 else 9821 break; 9822 } 9823 9824 return Ex; 9825 } 9826 9827 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9828 ASTContext &Context) { 9829 // Only handle constant-sized or VLAs, but not flexible members. 9830 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9831 // Only issue the FIXIT for arrays of size > 1. 9832 if (CAT->getSize().getSExtValue() <= 1) 9833 return false; 9834 } else if (!Ty->isVariableArrayType()) { 9835 return false; 9836 } 9837 return true; 9838 } 9839 9840 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9841 // be the size of the source, instead of the destination. 9842 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9843 IdentifierInfo *FnName) { 9844 9845 // Don't crash if the user has the wrong number of arguments 9846 unsigned NumArgs = Call->getNumArgs(); 9847 if ((NumArgs != 3) && (NumArgs != 4)) 9848 return; 9849 9850 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9851 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9852 const Expr *CompareWithSrc = nullptr; 9853 9854 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9855 Call->getBeginLoc(), Call->getRParenLoc())) 9856 return; 9857 9858 // Look for 'strlcpy(dst, x, sizeof(x))' 9859 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9860 CompareWithSrc = Ex; 9861 else { 9862 // Look for 'strlcpy(dst, x, strlen(x))' 9863 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9864 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9865 SizeCall->getNumArgs() == 1) 9866 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9867 } 9868 } 9869 9870 if (!CompareWithSrc) 9871 return; 9872 9873 // Determine if the argument to sizeof/strlen is equal to the source 9874 // argument. In principle there's all kinds of things you could do 9875 // here, for instance creating an == expression and evaluating it with 9876 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9877 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9878 if (!SrcArgDRE) 9879 return; 9880 9881 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9882 if (!CompareWithSrcDRE || 9883 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9884 return; 9885 9886 const Expr *OriginalSizeArg = Call->getArg(2); 9887 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9888 << OriginalSizeArg->getSourceRange() << FnName; 9889 9890 // Output a FIXIT hint if the destination is an array (rather than a 9891 // pointer to an array). This could be enhanced to handle some 9892 // pointers if we know the actual size, like if DstArg is 'array+2' 9893 // we could say 'sizeof(array)-2'. 9894 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9895 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9896 return; 9897 9898 SmallString<128> sizeString; 9899 llvm::raw_svector_ostream OS(sizeString); 9900 OS << "sizeof("; 9901 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9902 OS << ")"; 9903 9904 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9905 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9906 OS.str()); 9907 } 9908 9909 /// Check if two expressions refer to the same declaration. 9910 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9911 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9912 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9913 return D1->getDecl() == D2->getDecl(); 9914 return false; 9915 } 9916 9917 static const Expr *getStrlenExprArg(const Expr *E) { 9918 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9919 const FunctionDecl *FD = CE->getDirectCallee(); 9920 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9921 return nullptr; 9922 return CE->getArg(0)->IgnoreParenCasts(); 9923 } 9924 return nullptr; 9925 } 9926 9927 // Warn on anti-patterns as the 'size' argument to strncat. 9928 // The correct size argument should look like following: 9929 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9930 void Sema::CheckStrncatArguments(const CallExpr *CE, 9931 IdentifierInfo *FnName) { 9932 // Don't crash if the user has the wrong number of arguments. 9933 if (CE->getNumArgs() < 3) 9934 return; 9935 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9936 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9937 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9938 9939 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9940 CE->getRParenLoc())) 9941 return; 9942 9943 // Identify common expressions, which are wrongly used as the size argument 9944 // to strncat and may lead to buffer overflows. 9945 unsigned PatternType = 0; 9946 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9947 // - sizeof(dst) 9948 if (referToTheSameDecl(SizeOfArg, DstArg)) 9949 PatternType = 1; 9950 // - sizeof(src) 9951 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9952 PatternType = 2; 9953 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9954 if (BE->getOpcode() == BO_Sub) { 9955 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9956 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9957 // - sizeof(dst) - strlen(dst) 9958 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9959 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9960 PatternType = 1; 9961 // - sizeof(src) - (anything) 9962 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9963 PatternType = 2; 9964 } 9965 } 9966 9967 if (PatternType == 0) 9968 return; 9969 9970 // Generate the diagnostic. 9971 SourceLocation SL = LenArg->getBeginLoc(); 9972 SourceRange SR = LenArg->getSourceRange(); 9973 SourceManager &SM = getSourceManager(); 9974 9975 // If the function is defined as a builtin macro, do not show macro expansion. 9976 if (SM.isMacroArgExpansion(SL)) { 9977 SL = SM.getSpellingLoc(SL); 9978 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9979 SM.getSpellingLoc(SR.getEnd())); 9980 } 9981 9982 // Check if the destination is an array (rather than a pointer to an array). 9983 QualType DstTy = DstArg->getType(); 9984 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9985 Context); 9986 if (!isKnownSizeArray) { 9987 if (PatternType == 1) 9988 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9989 else 9990 Diag(SL, diag::warn_strncat_src_size) << SR; 9991 return; 9992 } 9993 9994 if (PatternType == 1) 9995 Diag(SL, diag::warn_strncat_large_size) << SR; 9996 else 9997 Diag(SL, diag::warn_strncat_src_size) << SR; 9998 9999 SmallString<128> sizeString; 10000 llvm::raw_svector_ostream OS(sizeString); 10001 OS << "sizeof("; 10002 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10003 OS << ") - "; 10004 OS << "strlen("; 10005 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10006 OS << ") - 1"; 10007 10008 Diag(SL, diag::note_strncat_wrong_size) 10009 << FixItHint::CreateReplacement(SR, OS.str()); 10010 } 10011 10012 void 10013 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10014 SourceLocation ReturnLoc, 10015 bool isObjCMethod, 10016 const AttrVec *Attrs, 10017 const FunctionDecl *FD) { 10018 // Check if the return value is null but should not be. 10019 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10020 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10021 CheckNonNullExpr(*this, RetValExp)) 10022 Diag(ReturnLoc, diag::warn_null_ret) 10023 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10024 10025 // C++11 [basic.stc.dynamic.allocation]p4: 10026 // If an allocation function declared with a non-throwing 10027 // exception-specification fails to allocate storage, it shall return 10028 // a null pointer. Any other allocation function that fails to allocate 10029 // storage shall indicate failure only by throwing an exception [...] 10030 if (FD) { 10031 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10032 if (Op == OO_New || Op == OO_Array_New) { 10033 const FunctionProtoType *Proto 10034 = FD->getType()->castAs<FunctionProtoType>(); 10035 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10036 CheckNonNullExpr(*this, RetValExp)) 10037 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10038 << FD << getLangOpts().CPlusPlus11; 10039 } 10040 } 10041 } 10042 10043 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10044 10045 /// Check for comparisons of floating point operands using != and ==. 10046 /// Issue a warning if these are no self-comparisons, as they are not likely 10047 /// to do what the programmer intended. 10048 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10049 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10050 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10051 10052 // Special case: check for x == x (which is OK). 10053 // Do not emit warnings for such cases. 10054 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10055 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10056 if (DRL->getDecl() == DRR->getDecl()) 10057 return; 10058 10059 // Special case: check for comparisons against literals that can be exactly 10060 // represented by APFloat. In such cases, do not emit a warning. This 10061 // is a heuristic: often comparison against such literals are used to 10062 // detect if a value in a variable has not changed. This clearly can 10063 // lead to false negatives. 10064 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10065 if (FLL->isExact()) 10066 return; 10067 } else 10068 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10069 if (FLR->isExact()) 10070 return; 10071 10072 // Check for comparisons with builtin types. 10073 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10074 if (CL->getBuiltinCallee()) 10075 return; 10076 10077 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10078 if (CR->getBuiltinCallee()) 10079 return; 10080 10081 // Emit the diagnostic. 10082 Diag(Loc, diag::warn_floatingpoint_eq) 10083 << LHS->getSourceRange() << RHS->getSourceRange(); 10084 } 10085 10086 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10087 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10088 10089 namespace { 10090 10091 /// Structure recording the 'active' range of an integer-valued 10092 /// expression. 10093 struct IntRange { 10094 /// The number of bits active in the int. 10095 unsigned Width; 10096 10097 /// True if the int is known not to have negative values. 10098 bool NonNegative; 10099 10100 IntRange(unsigned Width, bool NonNegative) 10101 : Width(Width), NonNegative(NonNegative) {} 10102 10103 /// Returns the range of the bool type. 10104 static IntRange forBoolType() { 10105 return IntRange(1, true); 10106 } 10107 10108 /// Returns the range of an opaque value of the given integral type. 10109 static IntRange forValueOfType(ASTContext &C, QualType T) { 10110 return forValueOfCanonicalType(C, 10111 T->getCanonicalTypeInternal().getTypePtr()); 10112 } 10113 10114 /// Returns the range of an opaque value of a canonical integral type. 10115 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10116 assert(T->isCanonicalUnqualified()); 10117 10118 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10119 T = VT->getElementType().getTypePtr(); 10120 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10121 T = CT->getElementType().getTypePtr(); 10122 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10123 T = AT->getValueType().getTypePtr(); 10124 10125 if (!C.getLangOpts().CPlusPlus) { 10126 // For enum types in C code, use the underlying datatype. 10127 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10128 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10129 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10130 // For enum types in C++, use the known bit width of the enumerators. 10131 EnumDecl *Enum = ET->getDecl(); 10132 // In C++11, enums can have a fixed underlying type. Use this type to 10133 // compute the range. 10134 if (Enum->isFixed()) { 10135 return IntRange(C.getIntWidth(QualType(T, 0)), 10136 !ET->isSignedIntegerOrEnumerationType()); 10137 } 10138 10139 unsigned NumPositive = Enum->getNumPositiveBits(); 10140 unsigned NumNegative = Enum->getNumNegativeBits(); 10141 10142 if (NumNegative == 0) 10143 return IntRange(NumPositive, true/*NonNegative*/); 10144 else 10145 return IntRange(std::max(NumPositive + 1, NumNegative), 10146 false/*NonNegative*/); 10147 } 10148 10149 const BuiltinType *BT = cast<BuiltinType>(T); 10150 assert(BT->isInteger()); 10151 10152 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10153 } 10154 10155 /// Returns the "target" range of a canonical integral type, i.e. 10156 /// the range of values expressible in the type. 10157 /// 10158 /// This matches forValueOfCanonicalType except that enums have the 10159 /// full range of their type, not the range of their enumerators. 10160 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10161 assert(T->isCanonicalUnqualified()); 10162 10163 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10164 T = VT->getElementType().getTypePtr(); 10165 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10166 T = CT->getElementType().getTypePtr(); 10167 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10168 T = AT->getValueType().getTypePtr(); 10169 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10170 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10171 10172 const BuiltinType *BT = cast<BuiltinType>(T); 10173 assert(BT->isInteger()); 10174 10175 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10176 } 10177 10178 /// Returns the supremum of two ranges: i.e. their conservative merge. 10179 static IntRange join(IntRange L, IntRange R) { 10180 return IntRange(std::max(L.Width, R.Width), 10181 L.NonNegative && R.NonNegative); 10182 } 10183 10184 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10185 static IntRange meet(IntRange L, IntRange R) { 10186 return IntRange(std::min(L.Width, R.Width), 10187 L.NonNegative || R.NonNegative); 10188 } 10189 }; 10190 10191 } // namespace 10192 10193 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10194 unsigned MaxWidth) { 10195 if (value.isSigned() && value.isNegative()) 10196 return IntRange(value.getMinSignedBits(), false); 10197 10198 if (value.getBitWidth() > MaxWidth) 10199 value = value.trunc(MaxWidth); 10200 10201 // isNonNegative() just checks the sign bit without considering 10202 // signedness. 10203 return IntRange(value.getActiveBits(), true); 10204 } 10205 10206 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10207 unsigned MaxWidth) { 10208 if (result.isInt()) 10209 return GetValueRange(C, result.getInt(), MaxWidth); 10210 10211 if (result.isVector()) { 10212 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10213 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10214 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10215 R = IntRange::join(R, El); 10216 } 10217 return R; 10218 } 10219 10220 if (result.isComplexInt()) { 10221 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10222 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10223 return IntRange::join(R, I); 10224 } 10225 10226 // This can happen with lossless casts to intptr_t of "based" lvalues. 10227 // Assume it might use arbitrary bits. 10228 // FIXME: The only reason we need to pass the type in here is to get 10229 // the sign right on this one case. It would be nice if APValue 10230 // preserved this. 10231 assert(result.isLValue() || result.isAddrLabelDiff()); 10232 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10233 } 10234 10235 static QualType GetExprType(const Expr *E) { 10236 QualType Ty = E->getType(); 10237 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10238 Ty = AtomicRHS->getValueType(); 10239 return Ty; 10240 } 10241 10242 /// Pseudo-evaluate the given integer expression, estimating the 10243 /// range of values it might take. 10244 /// 10245 /// \param MaxWidth - the width to which the value will be truncated 10246 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10247 bool InConstantContext) { 10248 E = E->IgnoreParens(); 10249 10250 // Try a full evaluation first. 10251 Expr::EvalResult result; 10252 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10253 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10254 10255 // I think we only want to look through implicit casts here; if the 10256 // user has an explicit widening cast, we should treat the value as 10257 // being of the new, wider type. 10258 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10259 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10260 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10261 10262 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10263 10264 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10265 CE->getCastKind() == CK_BooleanToSignedIntegral; 10266 10267 // Assume that non-integer casts can span the full range of the type. 10268 if (!isIntegerCast) 10269 return OutputTypeRange; 10270 10271 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10272 std::min(MaxWidth, OutputTypeRange.Width), 10273 InConstantContext); 10274 10275 // Bail out if the subexpr's range is as wide as the cast type. 10276 if (SubRange.Width >= OutputTypeRange.Width) 10277 return OutputTypeRange; 10278 10279 // Otherwise, we take the smaller width, and we're non-negative if 10280 // either the output type or the subexpr is. 10281 return IntRange(SubRange.Width, 10282 SubRange.NonNegative || OutputTypeRange.NonNegative); 10283 } 10284 10285 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10286 // If we can fold the condition, just take that operand. 10287 bool CondResult; 10288 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10289 return GetExprRange(C, 10290 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10291 MaxWidth, InConstantContext); 10292 10293 // Otherwise, conservatively merge. 10294 IntRange L = 10295 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10296 IntRange R = 10297 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10298 return IntRange::join(L, R); 10299 } 10300 10301 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10302 switch (BO->getOpcode()) { 10303 case BO_Cmp: 10304 llvm_unreachable("builtin <=> should have class type"); 10305 10306 // Boolean-valued operations are single-bit and positive. 10307 case BO_LAnd: 10308 case BO_LOr: 10309 case BO_LT: 10310 case BO_GT: 10311 case BO_LE: 10312 case BO_GE: 10313 case BO_EQ: 10314 case BO_NE: 10315 return IntRange::forBoolType(); 10316 10317 // The type of the assignments is the type of the LHS, so the RHS 10318 // is not necessarily the same type. 10319 case BO_MulAssign: 10320 case BO_DivAssign: 10321 case BO_RemAssign: 10322 case BO_AddAssign: 10323 case BO_SubAssign: 10324 case BO_XorAssign: 10325 case BO_OrAssign: 10326 // TODO: bitfields? 10327 return IntRange::forValueOfType(C, GetExprType(E)); 10328 10329 // Simple assignments just pass through the RHS, which will have 10330 // been coerced to the LHS type. 10331 case BO_Assign: 10332 // TODO: bitfields? 10333 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10334 10335 // Operations with opaque sources are black-listed. 10336 case BO_PtrMemD: 10337 case BO_PtrMemI: 10338 return IntRange::forValueOfType(C, GetExprType(E)); 10339 10340 // Bitwise-and uses the *infinum* of the two source ranges. 10341 case BO_And: 10342 case BO_AndAssign: 10343 return IntRange::meet( 10344 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10345 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10346 10347 // Left shift gets black-listed based on a judgement call. 10348 case BO_Shl: 10349 // ...except that we want to treat '1 << (blah)' as logically 10350 // positive. It's an important idiom. 10351 if (IntegerLiteral *I 10352 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10353 if (I->getValue() == 1) { 10354 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10355 return IntRange(R.Width, /*NonNegative*/ true); 10356 } 10357 } 10358 LLVM_FALLTHROUGH; 10359 10360 case BO_ShlAssign: 10361 return IntRange::forValueOfType(C, GetExprType(E)); 10362 10363 // Right shift by a constant can narrow its left argument. 10364 case BO_Shr: 10365 case BO_ShrAssign: { 10366 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10367 10368 // If the shift amount is a positive constant, drop the width by 10369 // that much. 10370 llvm::APSInt shift; 10371 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10372 shift.isNonNegative()) { 10373 unsigned zext = shift.getZExtValue(); 10374 if (zext >= L.Width) 10375 L.Width = (L.NonNegative ? 0 : 1); 10376 else 10377 L.Width -= zext; 10378 } 10379 10380 return L; 10381 } 10382 10383 // Comma acts as its right operand. 10384 case BO_Comma: 10385 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10386 10387 // Black-list pointer subtractions. 10388 case BO_Sub: 10389 if (BO->getLHS()->getType()->isPointerType()) 10390 return IntRange::forValueOfType(C, GetExprType(E)); 10391 break; 10392 10393 // The width of a division result is mostly determined by the size 10394 // of the LHS. 10395 case BO_Div: { 10396 // Don't 'pre-truncate' the operands. 10397 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10398 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10399 10400 // If the divisor is constant, use that. 10401 llvm::APSInt divisor; 10402 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10403 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10404 if (log2 >= L.Width) 10405 L.Width = (L.NonNegative ? 0 : 1); 10406 else 10407 L.Width = std::min(L.Width - log2, MaxWidth); 10408 return L; 10409 } 10410 10411 // Otherwise, just use the LHS's width. 10412 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10413 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10414 } 10415 10416 // The result of a remainder can't be larger than the result of 10417 // either side. 10418 case BO_Rem: { 10419 // Don't 'pre-truncate' the operands. 10420 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10421 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10422 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10423 10424 IntRange meet = IntRange::meet(L, R); 10425 meet.Width = std::min(meet.Width, MaxWidth); 10426 return meet; 10427 } 10428 10429 // The default behavior is okay for these. 10430 case BO_Mul: 10431 case BO_Add: 10432 case BO_Xor: 10433 case BO_Or: 10434 break; 10435 } 10436 10437 // The default case is to treat the operation as if it were closed 10438 // on the narrowest type that encompasses both operands. 10439 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10440 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10441 return IntRange::join(L, R); 10442 } 10443 10444 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10445 switch (UO->getOpcode()) { 10446 // Boolean-valued operations are white-listed. 10447 case UO_LNot: 10448 return IntRange::forBoolType(); 10449 10450 // Operations with opaque sources are black-listed. 10451 case UO_Deref: 10452 case UO_AddrOf: // should be impossible 10453 return IntRange::forValueOfType(C, GetExprType(E)); 10454 10455 default: 10456 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10457 } 10458 } 10459 10460 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10461 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10462 10463 if (const auto *BitField = E->getSourceBitField()) 10464 return IntRange(BitField->getBitWidthValue(C), 10465 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10466 10467 return IntRange::forValueOfType(C, GetExprType(E)); 10468 } 10469 10470 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10471 bool InConstantContext) { 10472 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10473 } 10474 10475 /// Checks whether the given value, which currently has the given 10476 /// source semantics, has the same value when coerced through the 10477 /// target semantics. 10478 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10479 const llvm::fltSemantics &Src, 10480 const llvm::fltSemantics &Tgt) { 10481 llvm::APFloat truncated = value; 10482 10483 bool ignored; 10484 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10485 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10486 10487 return truncated.bitwiseIsEqual(value); 10488 } 10489 10490 /// Checks whether the given value, which currently has the given 10491 /// source semantics, has the same value when coerced through the 10492 /// target semantics. 10493 /// 10494 /// The value might be a vector of floats (or a complex number). 10495 static bool IsSameFloatAfterCast(const APValue &value, 10496 const llvm::fltSemantics &Src, 10497 const llvm::fltSemantics &Tgt) { 10498 if (value.isFloat()) 10499 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10500 10501 if (value.isVector()) { 10502 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10503 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10504 return false; 10505 return true; 10506 } 10507 10508 assert(value.isComplexFloat()); 10509 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10510 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10511 } 10512 10513 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10514 bool IsListInit = false); 10515 10516 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10517 // Suppress cases where we are comparing against an enum constant. 10518 if (const DeclRefExpr *DR = 10519 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10520 if (isa<EnumConstantDecl>(DR->getDecl())) 10521 return true; 10522 10523 // Suppress cases where the value is expanded from a macro, unless that macro 10524 // is how a language represents a boolean literal. This is the case in both C 10525 // and Objective-C. 10526 SourceLocation BeginLoc = E->getBeginLoc(); 10527 if (BeginLoc.isMacroID()) { 10528 StringRef MacroName = Lexer::getImmediateMacroName( 10529 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10530 return MacroName != "YES" && MacroName != "NO" && 10531 MacroName != "true" && MacroName != "false"; 10532 } 10533 10534 return false; 10535 } 10536 10537 static bool isKnownToHaveUnsignedValue(Expr *E) { 10538 return E->getType()->isIntegerType() && 10539 (!E->getType()->isSignedIntegerType() || 10540 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10541 } 10542 10543 namespace { 10544 /// The promoted range of values of a type. In general this has the 10545 /// following structure: 10546 /// 10547 /// |-----------| . . . |-----------| 10548 /// ^ ^ ^ ^ 10549 /// Min HoleMin HoleMax Max 10550 /// 10551 /// ... where there is only a hole if a signed type is promoted to unsigned 10552 /// (in which case Min and Max are the smallest and largest representable 10553 /// values). 10554 struct PromotedRange { 10555 // Min, or HoleMax if there is a hole. 10556 llvm::APSInt PromotedMin; 10557 // Max, or HoleMin if there is a hole. 10558 llvm::APSInt PromotedMax; 10559 10560 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10561 if (R.Width == 0) 10562 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10563 else if (R.Width >= BitWidth && !Unsigned) { 10564 // Promotion made the type *narrower*. This happens when promoting 10565 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10566 // Treat all values of 'signed int' as being in range for now. 10567 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10568 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10569 } else { 10570 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10571 .extOrTrunc(BitWidth); 10572 PromotedMin.setIsUnsigned(Unsigned); 10573 10574 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10575 .extOrTrunc(BitWidth); 10576 PromotedMax.setIsUnsigned(Unsigned); 10577 } 10578 } 10579 10580 // Determine whether this range is contiguous (has no hole). 10581 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10582 10583 // Where a constant value is within the range. 10584 enum ComparisonResult { 10585 LT = 0x1, 10586 LE = 0x2, 10587 GT = 0x4, 10588 GE = 0x8, 10589 EQ = 0x10, 10590 NE = 0x20, 10591 InRangeFlag = 0x40, 10592 10593 Less = LE | LT | NE, 10594 Min = LE | InRangeFlag, 10595 InRange = InRangeFlag, 10596 Max = GE | InRangeFlag, 10597 Greater = GE | GT | NE, 10598 10599 OnlyValue = LE | GE | EQ | InRangeFlag, 10600 InHole = NE 10601 }; 10602 10603 ComparisonResult compare(const llvm::APSInt &Value) const { 10604 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10605 Value.isUnsigned() == PromotedMin.isUnsigned()); 10606 if (!isContiguous()) { 10607 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10608 if (Value.isMinValue()) return Min; 10609 if (Value.isMaxValue()) return Max; 10610 if (Value >= PromotedMin) return InRange; 10611 if (Value <= PromotedMax) return InRange; 10612 return InHole; 10613 } 10614 10615 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10616 case -1: return Less; 10617 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10618 case 1: 10619 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10620 case -1: return InRange; 10621 case 0: return Max; 10622 case 1: return Greater; 10623 } 10624 } 10625 10626 llvm_unreachable("impossible compare result"); 10627 } 10628 10629 static llvm::Optional<StringRef> 10630 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10631 if (Op == BO_Cmp) { 10632 ComparisonResult LTFlag = LT, GTFlag = GT; 10633 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10634 10635 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10636 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10637 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10638 return llvm::None; 10639 } 10640 10641 ComparisonResult TrueFlag, FalseFlag; 10642 if (Op == BO_EQ) { 10643 TrueFlag = EQ; 10644 FalseFlag = NE; 10645 } else if (Op == BO_NE) { 10646 TrueFlag = NE; 10647 FalseFlag = EQ; 10648 } else { 10649 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10650 TrueFlag = LT; 10651 FalseFlag = GE; 10652 } else { 10653 TrueFlag = GT; 10654 FalseFlag = LE; 10655 } 10656 if (Op == BO_GE || Op == BO_LE) 10657 std::swap(TrueFlag, FalseFlag); 10658 } 10659 if (R & TrueFlag) 10660 return StringRef("true"); 10661 if (R & FalseFlag) 10662 return StringRef("false"); 10663 return llvm::None; 10664 } 10665 }; 10666 } 10667 10668 static bool HasEnumType(Expr *E) { 10669 // Strip off implicit integral promotions. 10670 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10671 if (ICE->getCastKind() != CK_IntegralCast && 10672 ICE->getCastKind() != CK_NoOp) 10673 break; 10674 E = ICE->getSubExpr(); 10675 } 10676 10677 return E->getType()->isEnumeralType(); 10678 } 10679 10680 static int classifyConstantValue(Expr *Constant) { 10681 // The values of this enumeration are used in the diagnostics 10682 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10683 enum ConstantValueKind { 10684 Miscellaneous = 0, 10685 LiteralTrue, 10686 LiteralFalse 10687 }; 10688 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10689 return BL->getValue() ? ConstantValueKind::LiteralTrue 10690 : ConstantValueKind::LiteralFalse; 10691 return ConstantValueKind::Miscellaneous; 10692 } 10693 10694 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10695 Expr *Constant, Expr *Other, 10696 const llvm::APSInt &Value, 10697 bool RhsConstant) { 10698 if (S.inTemplateInstantiation()) 10699 return false; 10700 10701 Expr *OriginalOther = Other; 10702 10703 Constant = Constant->IgnoreParenImpCasts(); 10704 Other = Other->IgnoreParenImpCasts(); 10705 10706 // Suppress warnings on tautological comparisons between values of the same 10707 // enumeration type. There are only two ways we could warn on this: 10708 // - If the constant is outside the range of representable values of 10709 // the enumeration. In such a case, we should warn about the cast 10710 // to enumeration type, not about the comparison. 10711 // - If the constant is the maximum / minimum in-range value. For an 10712 // enumeratin type, such comparisons can be meaningful and useful. 10713 if (Constant->getType()->isEnumeralType() && 10714 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10715 return false; 10716 10717 // TODO: Investigate using GetExprRange() to get tighter bounds 10718 // on the bit ranges. 10719 QualType OtherT = Other->getType(); 10720 if (const auto *AT = OtherT->getAs<AtomicType>()) 10721 OtherT = AT->getValueType(); 10722 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10723 10724 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10725 // (Namely, macOS). 10726 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10727 S.NSAPIObj->isObjCBOOLType(OtherT) && 10728 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10729 10730 // Whether we're treating Other as being a bool because of the form of 10731 // expression despite it having another type (typically 'int' in C). 10732 bool OtherIsBooleanDespiteType = 10733 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10734 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10735 OtherRange = IntRange::forBoolType(); 10736 10737 // Determine the promoted range of the other type and see if a comparison of 10738 // the constant against that range is tautological. 10739 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10740 Value.isUnsigned()); 10741 auto Cmp = OtherPromotedRange.compare(Value); 10742 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10743 if (!Result) 10744 return false; 10745 10746 // Suppress the diagnostic for an in-range comparison if the constant comes 10747 // from a macro or enumerator. We don't want to diagnose 10748 // 10749 // some_long_value <= INT_MAX 10750 // 10751 // when sizeof(int) == sizeof(long). 10752 bool InRange = Cmp & PromotedRange::InRangeFlag; 10753 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10754 return false; 10755 10756 // If this is a comparison to an enum constant, include that 10757 // constant in the diagnostic. 10758 const EnumConstantDecl *ED = nullptr; 10759 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10760 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10761 10762 // Should be enough for uint128 (39 decimal digits) 10763 SmallString<64> PrettySourceValue; 10764 llvm::raw_svector_ostream OS(PrettySourceValue); 10765 if (ED) { 10766 OS << '\'' << *ED << "' (" << Value << ")"; 10767 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10768 Constant->IgnoreParenImpCasts())) { 10769 OS << (BL->getValue() ? "YES" : "NO"); 10770 } else { 10771 OS << Value; 10772 } 10773 10774 if (IsObjCSignedCharBool) { 10775 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10776 S.PDiag(diag::warn_tautological_compare_objc_bool) 10777 << OS.str() << *Result); 10778 return true; 10779 } 10780 10781 // FIXME: We use a somewhat different formatting for the in-range cases and 10782 // cases involving boolean values for historical reasons. We should pick a 10783 // consistent way of presenting these diagnostics. 10784 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10785 10786 S.DiagRuntimeBehavior( 10787 E->getOperatorLoc(), E, 10788 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10789 : diag::warn_tautological_bool_compare) 10790 << OS.str() << classifyConstantValue(Constant) << OtherT 10791 << OtherIsBooleanDespiteType << *Result 10792 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10793 } else { 10794 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10795 ? (HasEnumType(OriginalOther) 10796 ? diag::warn_unsigned_enum_always_true_comparison 10797 : diag::warn_unsigned_always_true_comparison) 10798 : diag::warn_tautological_constant_compare; 10799 10800 S.Diag(E->getOperatorLoc(), Diag) 10801 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10802 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10803 } 10804 10805 return true; 10806 } 10807 10808 /// Analyze the operands of the given comparison. Implements the 10809 /// fallback case from AnalyzeComparison. 10810 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10811 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10812 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10813 } 10814 10815 /// Implements -Wsign-compare. 10816 /// 10817 /// \param E the binary operator to check for warnings 10818 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10819 // The type the comparison is being performed in. 10820 QualType T = E->getLHS()->getType(); 10821 10822 // Only analyze comparison operators where both sides have been converted to 10823 // the same type. 10824 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10825 return AnalyzeImpConvsInComparison(S, E); 10826 10827 // Don't analyze value-dependent comparisons directly. 10828 if (E->isValueDependent()) 10829 return AnalyzeImpConvsInComparison(S, E); 10830 10831 Expr *LHS = E->getLHS(); 10832 Expr *RHS = E->getRHS(); 10833 10834 if (T->isIntegralType(S.Context)) { 10835 llvm::APSInt RHSValue; 10836 llvm::APSInt LHSValue; 10837 10838 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10839 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10840 10841 // We don't care about expressions whose result is a constant. 10842 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10843 return AnalyzeImpConvsInComparison(S, E); 10844 10845 // We only care about expressions where just one side is literal 10846 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10847 // Is the constant on the RHS or LHS? 10848 const bool RhsConstant = IsRHSIntegralLiteral; 10849 Expr *Const = RhsConstant ? RHS : LHS; 10850 Expr *Other = RhsConstant ? LHS : RHS; 10851 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10852 10853 // Check whether an integer constant comparison results in a value 10854 // of 'true' or 'false'. 10855 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10856 return AnalyzeImpConvsInComparison(S, E); 10857 } 10858 } 10859 10860 if (!T->hasUnsignedIntegerRepresentation()) { 10861 // We don't do anything special if this isn't an unsigned integral 10862 // comparison: we're only interested in integral comparisons, and 10863 // signed comparisons only happen in cases we don't care to warn about. 10864 return AnalyzeImpConvsInComparison(S, E); 10865 } 10866 10867 LHS = LHS->IgnoreParenImpCasts(); 10868 RHS = RHS->IgnoreParenImpCasts(); 10869 10870 if (!S.getLangOpts().CPlusPlus) { 10871 // Avoid warning about comparison of integers with different signs when 10872 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10873 // the type of `E`. 10874 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10875 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10876 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10877 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10878 } 10879 10880 // Check to see if one of the (unmodified) operands is of different 10881 // signedness. 10882 Expr *signedOperand, *unsignedOperand; 10883 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10884 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10885 "unsigned comparison between two signed integer expressions?"); 10886 signedOperand = LHS; 10887 unsignedOperand = RHS; 10888 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10889 signedOperand = RHS; 10890 unsignedOperand = LHS; 10891 } else { 10892 return AnalyzeImpConvsInComparison(S, E); 10893 } 10894 10895 // Otherwise, calculate the effective range of the signed operand. 10896 IntRange signedRange = 10897 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10898 10899 // Go ahead and analyze implicit conversions in the operands. Note 10900 // that we skip the implicit conversions on both sides. 10901 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10902 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10903 10904 // If the signed range is non-negative, -Wsign-compare won't fire. 10905 if (signedRange.NonNegative) 10906 return; 10907 10908 // For (in)equality comparisons, if the unsigned operand is a 10909 // constant which cannot collide with a overflowed signed operand, 10910 // then reinterpreting the signed operand as unsigned will not 10911 // change the result of the comparison. 10912 if (E->isEqualityOp()) { 10913 unsigned comparisonWidth = S.Context.getIntWidth(T); 10914 IntRange unsignedRange = 10915 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10916 10917 // We should never be unable to prove that the unsigned operand is 10918 // non-negative. 10919 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10920 10921 if (unsignedRange.Width < comparisonWidth) 10922 return; 10923 } 10924 10925 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10926 S.PDiag(diag::warn_mixed_sign_comparison) 10927 << LHS->getType() << RHS->getType() 10928 << LHS->getSourceRange() << RHS->getSourceRange()); 10929 } 10930 10931 /// Analyzes an attempt to assign the given value to a bitfield. 10932 /// 10933 /// Returns true if there was something fishy about the attempt. 10934 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10935 SourceLocation InitLoc) { 10936 assert(Bitfield->isBitField()); 10937 if (Bitfield->isInvalidDecl()) 10938 return false; 10939 10940 // White-list bool bitfields. 10941 QualType BitfieldType = Bitfield->getType(); 10942 if (BitfieldType->isBooleanType()) 10943 return false; 10944 10945 if (BitfieldType->isEnumeralType()) { 10946 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10947 // If the underlying enum type was not explicitly specified as an unsigned 10948 // type and the enum contain only positive values, MSVC++ will cause an 10949 // inconsistency by storing this as a signed type. 10950 if (S.getLangOpts().CPlusPlus11 && 10951 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10952 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10953 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10954 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10955 << BitfieldEnumDecl->getNameAsString(); 10956 } 10957 } 10958 10959 if (Bitfield->getType()->isBooleanType()) 10960 return false; 10961 10962 // Ignore value- or type-dependent expressions. 10963 if (Bitfield->getBitWidth()->isValueDependent() || 10964 Bitfield->getBitWidth()->isTypeDependent() || 10965 Init->isValueDependent() || 10966 Init->isTypeDependent()) 10967 return false; 10968 10969 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10970 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10971 10972 Expr::EvalResult Result; 10973 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10974 Expr::SE_AllowSideEffects)) { 10975 // The RHS is not constant. If the RHS has an enum type, make sure the 10976 // bitfield is wide enough to hold all the values of the enum without 10977 // truncation. 10978 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10979 EnumDecl *ED = EnumTy->getDecl(); 10980 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10981 10982 // Enum types are implicitly signed on Windows, so check if there are any 10983 // negative enumerators to see if the enum was intended to be signed or 10984 // not. 10985 bool SignedEnum = ED->getNumNegativeBits() > 0; 10986 10987 // Check for surprising sign changes when assigning enum values to a 10988 // bitfield of different signedness. If the bitfield is signed and we 10989 // have exactly the right number of bits to store this unsigned enum, 10990 // suggest changing the enum to an unsigned type. This typically happens 10991 // on Windows where unfixed enums always use an underlying type of 'int'. 10992 unsigned DiagID = 0; 10993 if (SignedEnum && !SignedBitfield) { 10994 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10995 } else if (SignedBitfield && !SignedEnum && 10996 ED->getNumPositiveBits() == FieldWidth) { 10997 DiagID = diag::warn_signed_bitfield_enum_conversion; 10998 } 10999 11000 if (DiagID) { 11001 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11002 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11003 SourceRange TypeRange = 11004 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11005 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11006 << SignedEnum << TypeRange; 11007 } 11008 11009 // Compute the required bitwidth. If the enum has negative values, we need 11010 // one more bit than the normal number of positive bits to represent the 11011 // sign bit. 11012 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11013 ED->getNumNegativeBits()) 11014 : ED->getNumPositiveBits(); 11015 11016 // Check the bitwidth. 11017 if (BitsNeeded > FieldWidth) { 11018 Expr *WidthExpr = Bitfield->getBitWidth(); 11019 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11020 << Bitfield << ED; 11021 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11022 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11023 } 11024 } 11025 11026 return false; 11027 } 11028 11029 llvm::APSInt Value = Result.Val.getInt(); 11030 11031 unsigned OriginalWidth = Value.getBitWidth(); 11032 11033 if (!Value.isSigned() || Value.isNegative()) 11034 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11035 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11036 OriginalWidth = Value.getMinSignedBits(); 11037 11038 if (OriginalWidth <= FieldWidth) 11039 return false; 11040 11041 // Compute the value which the bitfield will contain. 11042 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11043 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11044 11045 // Check whether the stored value is equal to the original value. 11046 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11047 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11048 return false; 11049 11050 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11051 // therefore don't strictly fit into a signed bitfield of width 1. 11052 if (FieldWidth == 1 && Value == 1) 11053 return false; 11054 11055 std::string PrettyValue = Value.toString(10); 11056 std::string PrettyTrunc = TruncatedValue.toString(10); 11057 11058 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11059 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11060 << Init->getSourceRange(); 11061 11062 return true; 11063 } 11064 11065 /// Analyze the given simple or compound assignment for warning-worthy 11066 /// operations. 11067 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11068 // Just recurse on the LHS. 11069 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11070 11071 // We want to recurse on the RHS as normal unless we're assigning to 11072 // a bitfield. 11073 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11074 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11075 E->getOperatorLoc())) { 11076 // Recurse, ignoring any implicit conversions on the RHS. 11077 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11078 E->getOperatorLoc()); 11079 } 11080 } 11081 11082 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11083 11084 // Diagnose implicitly sequentially-consistent atomic assignment. 11085 if (E->getLHS()->getType()->isAtomicType()) 11086 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11087 } 11088 11089 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11090 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11091 SourceLocation CContext, unsigned diag, 11092 bool pruneControlFlow = false) { 11093 if (pruneControlFlow) { 11094 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11095 S.PDiag(diag) 11096 << SourceType << T << E->getSourceRange() 11097 << SourceRange(CContext)); 11098 return; 11099 } 11100 S.Diag(E->getExprLoc(), diag) 11101 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11102 } 11103 11104 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11105 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11106 SourceLocation CContext, 11107 unsigned diag, bool pruneControlFlow = false) { 11108 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11109 } 11110 11111 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11112 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11113 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11114 } 11115 11116 static void adornObjCBoolConversionDiagWithTernaryFixit( 11117 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11118 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11119 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11120 Ignored = OVE->getSourceExpr(); 11121 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11122 isa<BinaryOperator>(Ignored) || 11123 isa<CXXOperatorCallExpr>(Ignored); 11124 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11125 if (NeedsParens) 11126 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11127 << FixItHint::CreateInsertion(EndLoc, ")"); 11128 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11129 } 11130 11131 /// Diagnose an implicit cast from a floating point value to an integer value. 11132 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11133 SourceLocation CContext) { 11134 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11135 const bool PruneWarnings = S.inTemplateInstantiation(); 11136 11137 Expr *InnerE = E->IgnoreParenImpCasts(); 11138 // We also want to warn on, e.g., "int i = -1.234" 11139 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11140 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11141 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11142 11143 const bool IsLiteral = 11144 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11145 11146 llvm::APFloat Value(0.0); 11147 bool IsConstant = 11148 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11149 if (!IsConstant) { 11150 if (isObjCSignedCharBool(S, T)) { 11151 return adornObjCBoolConversionDiagWithTernaryFixit( 11152 S, E, 11153 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11154 << E->getType()); 11155 } 11156 11157 return DiagnoseImpCast(S, E, T, CContext, 11158 diag::warn_impcast_float_integer, PruneWarnings); 11159 } 11160 11161 bool isExact = false; 11162 11163 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11164 T->hasUnsignedIntegerRepresentation()); 11165 llvm::APFloat::opStatus Result = Value.convertToInteger( 11166 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11167 11168 // FIXME: Force the precision of the source value down so we don't print 11169 // digits which are usually useless (we don't really care here if we 11170 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11171 // would automatically print the shortest representation, but it's a bit 11172 // tricky to implement. 11173 SmallString<16> PrettySourceValue; 11174 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11175 precision = (precision * 59 + 195) / 196; 11176 Value.toString(PrettySourceValue, precision); 11177 11178 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11179 return adornObjCBoolConversionDiagWithTernaryFixit( 11180 S, E, 11181 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11182 << PrettySourceValue); 11183 } 11184 11185 if (Result == llvm::APFloat::opOK && isExact) { 11186 if (IsLiteral) return; 11187 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11188 PruneWarnings); 11189 } 11190 11191 // Conversion of a floating-point value to a non-bool integer where the 11192 // integral part cannot be represented by the integer type is undefined. 11193 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11194 return DiagnoseImpCast( 11195 S, E, T, CContext, 11196 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11197 : diag::warn_impcast_float_to_integer_out_of_range, 11198 PruneWarnings); 11199 11200 unsigned DiagID = 0; 11201 if (IsLiteral) { 11202 // Warn on floating point literal to integer. 11203 DiagID = diag::warn_impcast_literal_float_to_integer; 11204 } else if (IntegerValue == 0) { 11205 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11206 return DiagnoseImpCast(S, E, T, CContext, 11207 diag::warn_impcast_float_integer, PruneWarnings); 11208 } 11209 // Warn on non-zero to zero conversion. 11210 DiagID = diag::warn_impcast_float_to_integer_zero; 11211 } else { 11212 if (IntegerValue.isUnsigned()) { 11213 if (!IntegerValue.isMaxValue()) { 11214 return DiagnoseImpCast(S, E, T, CContext, 11215 diag::warn_impcast_float_integer, PruneWarnings); 11216 } 11217 } else { // IntegerValue.isSigned() 11218 if (!IntegerValue.isMaxSignedValue() && 11219 !IntegerValue.isMinSignedValue()) { 11220 return DiagnoseImpCast(S, E, T, CContext, 11221 diag::warn_impcast_float_integer, PruneWarnings); 11222 } 11223 } 11224 // Warn on evaluatable floating point expression to integer conversion. 11225 DiagID = diag::warn_impcast_float_to_integer; 11226 } 11227 11228 SmallString<16> PrettyTargetValue; 11229 if (IsBool) 11230 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11231 else 11232 IntegerValue.toString(PrettyTargetValue); 11233 11234 if (PruneWarnings) { 11235 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11236 S.PDiag(DiagID) 11237 << E->getType() << T.getUnqualifiedType() 11238 << PrettySourceValue << PrettyTargetValue 11239 << E->getSourceRange() << SourceRange(CContext)); 11240 } else { 11241 S.Diag(E->getExprLoc(), DiagID) 11242 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11243 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11244 } 11245 } 11246 11247 /// Analyze the given compound assignment for the possible losing of 11248 /// floating-point precision. 11249 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11250 assert(isa<CompoundAssignOperator>(E) && 11251 "Must be compound assignment operation"); 11252 // Recurse on the LHS and RHS in here 11253 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11254 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11255 11256 if (E->getLHS()->getType()->isAtomicType()) 11257 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11258 11259 // Now check the outermost expression 11260 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11261 const auto *RBT = cast<CompoundAssignOperator>(E) 11262 ->getComputationResultType() 11263 ->getAs<BuiltinType>(); 11264 11265 // The below checks assume source is floating point. 11266 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11267 11268 // If source is floating point but target is an integer. 11269 if (ResultBT->isInteger()) 11270 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11271 E->getExprLoc(), diag::warn_impcast_float_integer); 11272 11273 if (!ResultBT->isFloatingPoint()) 11274 return; 11275 11276 // If both source and target are floating points, warn about losing precision. 11277 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11278 QualType(ResultBT, 0), QualType(RBT, 0)); 11279 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11280 // warn about dropping FP rank. 11281 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11282 diag::warn_impcast_float_result_precision); 11283 } 11284 11285 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11286 IntRange Range) { 11287 if (!Range.Width) return "0"; 11288 11289 llvm::APSInt ValueInRange = Value; 11290 ValueInRange.setIsSigned(!Range.NonNegative); 11291 ValueInRange = ValueInRange.trunc(Range.Width); 11292 return ValueInRange.toString(10); 11293 } 11294 11295 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11296 if (!isa<ImplicitCastExpr>(Ex)) 11297 return false; 11298 11299 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11300 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11301 const Type *Source = 11302 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11303 if (Target->isDependentType()) 11304 return false; 11305 11306 const BuiltinType *FloatCandidateBT = 11307 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11308 const Type *BoolCandidateType = ToBool ? Target : Source; 11309 11310 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11311 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11312 } 11313 11314 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11315 SourceLocation CC) { 11316 unsigned NumArgs = TheCall->getNumArgs(); 11317 for (unsigned i = 0; i < NumArgs; ++i) { 11318 Expr *CurrA = TheCall->getArg(i); 11319 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11320 continue; 11321 11322 bool IsSwapped = ((i > 0) && 11323 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11324 IsSwapped |= ((i < (NumArgs - 1)) && 11325 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11326 if (IsSwapped) { 11327 // Warn on this floating-point to bool conversion. 11328 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11329 CurrA->getType(), CC, 11330 diag::warn_impcast_floating_point_to_bool); 11331 } 11332 } 11333 } 11334 11335 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11336 SourceLocation CC) { 11337 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11338 E->getExprLoc())) 11339 return; 11340 11341 // Don't warn on functions which have return type nullptr_t. 11342 if (isa<CallExpr>(E)) 11343 return; 11344 11345 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11346 const Expr::NullPointerConstantKind NullKind = 11347 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11348 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11349 return; 11350 11351 // Return if target type is a safe conversion. 11352 if (T->isAnyPointerType() || T->isBlockPointerType() || 11353 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11354 return; 11355 11356 SourceLocation Loc = E->getSourceRange().getBegin(); 11357 11358 // Venture through the macro stacks to get to the source of macro arguments. 11359 // The new location is a better location than the complete location that was 11360 // passed in. 11361 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11362 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11363 11364 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11365 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11366 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11367 Loc, S.SourceMgr, S.getLangOpts()); 11368 if (MacroName == "NULL") 11369 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11370 } 11371 11372 // Only warn if the null and context location are in the same macro expansion. 11373 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11374 return; 11375 11376 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11377 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11378 << FixItHint::CreateReplacement(Loc, 11379 S.getFixItZeroLiteralForType(T, Loc)); 11380 } 11381 11382 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11383 ObjCArrayLiteral *ArrayLiteral); 11384 11385 static void 11386 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11387 ObjCDictionaryLiteral *DictionaryLiteral); 11388 11389 /// Check a single element within a collection literal against the 11390 /// target element type. 11391 static void checkObjCCollectionLiteralElement(Sema &S, 11392 QualType TargetElementType, 11393 Expr *Element, 11394 unsigned ElementKind) { 11395 // Skip a bitcast to 'id' or qualified 'id'. 11396 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11397 if (ICE->getCastKind() == CK_BitCast && 11398 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11399 Element = ICE->getSubExpr(); 11400 } 11401 11402 QualType ElementType = Element->getType(); 11403 ExprResult ElementResult(Element); 11404 if (ElementType->getAs<ObjCObjectPointerType>() && 11405 S.CheckSingleAssignmentConstraints(TargetElementType, 11406 ElementResult, 11407 false, false) 11408 != Sema::Compatible) { 11409 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11410 << ElementType << ElementKind << TargetElementType 11411 << Element->getSourceRange(); 11412 } 11413 11414 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11415 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11416 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11417 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11418 } 11419 11420 /// Check an Objective-C array literal being converted to the given 11421 /// target type. 11422 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11423 ObjCArrayLiteral *ArrayLiteral) { 11424 if (!S.NSArrayDecl) 11425 return; 11426 11427 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11428 if (!TargetObjCPtr) 11429 return; 11430 11431 if (TargetObjCPtr->isUnspecialized() || 11432 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11433 != S.NSArrayDecl->getCanonicalDecl()) 11434 return; 11435 11436 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11437 if (TypeArgs.size() != 1) 11438 return; 11439 11440 QualType TargetElementType = TypeArgs[0]; 11441 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11442 checkObjCCollectionLiteralElement(S, TargetElementType, 11443 ArrayLiteral->getElement(I), 11444 0); 11445 } 11446 } 11447 11448 /// Check an Objective-C dictionary literal being converted to the given 11449 /// target type. 11450 static void 11451 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11452 ObjCDictionaryLiteral *DictionaryLiteral) { 11453 if (!S.NSDictionaryDecl) 11454 return; 11455 11456 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11457 if (!TargetObjCPtr) 11458 return; 11459 11460 if (TargetObjCPtr->isUnspecialized() || 11461 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11462 != S.NSDictionaryDecl->getCanonicalDecl()) 11463 return; 11464 11465 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11466 if (TypeArgs.size() != 2) 11467 return; 11468 11469 QualType TargetKeyType = TypeArgs[0]; 11470 QualType TargetObjectType = TypeArgs[1]; 11471 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11472 auto Element = DictionaryLiteral->getKeyValueElement(I); 11473 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11474 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11475 } 11476 } 11477 11478 // Helper function to filter out cases for constant width constant conversion. 11479 // Don't warn on char array initialization or for non-decimal values. 11480 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11481 SourceLocation CC) { 11482 // If initializing from a constant, and the constant starts with '0', 11483 // then it is a binary, octal, or hexadecimal. Allow these constants 11484 // to fill all the bits, even if there is a sign change. 11485 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11486 const char FirstLiteralCharacter = 11487 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11488 if (FirstLiteralCharacter == '0') 11489 return false; 11490 } 11491 11492 // If the CC location points to a '{', and the type is char, then assume 11493 // assume it is an array initialization. 11494 if (CC.isValid() && T->isCharType()) { 11495 const char FirstContextCharacter = 11496 S.getSourceManager().getCharacterData(CC)[0]; 11497 if (FirstContextCharacter == '{') 11498 return false; 11499 } 11500 11501 return true; 11502 } 11503 11504 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11505 const auto *IL = dyn_cast<IntegerLiteral>(E); 11506 if (!IL) { 11507 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11508 if (UO->getOpcode() == UO_Minus) 11509 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11510 } 11511 } 11512 11513 return IL; 11514 } 11515 11516 static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc, 11517 Expr *LHS, Expr *RHS) { 11518 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 11519 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 11520 11521 const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 11522 if (!LHSEnumType) 11523 return; 11524 const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 11525 if (!RHSEnumType) 11526 return; 11527 11528 // Ignore anonymous enums. 11529 if (!LHSEnumType->getDecl()->hasNameForLinkage()) 11530 return; 11531 if (!RHSEnumType->getDecl()->hasNameForLinkage()) 11532 return; 11533 11534 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 11535 return; 11536 11537 S.Diag(Loc, diag::warn_conditional_mixed_enum_types) 11538 << LHSStrippedType << RHSStrippedType << LHS->getSourceRange() 11539 << RHS->getSourceRange(); 11540 } 11541 11542 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11543 E = E->IgnoreParenImpCasts(); 11544 SourceLocation ExprLoc = E->getExprLoc(); 11545 11546 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11547 BinaryOperator::Opcode Opc = BO->getOpcode(); 11548 Expr::EvalResult Result; 11549 // Do not diagnose unsigned shifts. 11550 if (Opc == BO_Shl) { 11551 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11552 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11553 if (LHS && LHS->getValue() == 0) 11554 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11555 else if (!E->isValueDependent() && LHS && RHS && 11556 RHS->getValue().isNonNegative() && 11557 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11558 S.Diag(ExprLoc, diag::warn_left_shift_always) 11559 << (Result.Val.getInt() != 0); 11560 else if (E->getType()->isSignedIntegerType()) 11561 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11562 } 11563 } 11564 11565 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11566 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11567 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11568 if (!LHS || !RHS) 11569 return; 11570 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11571 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11572 // Do not diagnose common idioms. 11573 return; 11574 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11575 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11576 } 11577 } 11578 11579 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11580 SourceLocation CC, 11581 bool *ICContext = nullptr, 11582 bool IsListInit = false) { 11583 if (E->isTypeDependent() || E->isValueDependent()) return; 11584 11585 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11586 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11587 if (Source == Target) return; 11588 if (Target->isDependentType()) return; 11589 11590 // If the conversion context location is invalid don't complain. We also 11591 // don't want to emit a warning if the issue occurs from the expansion of 11592 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11593 // delay this check as long as possible. Once we detect we are in that 11594 // scenario, we just return. 11595 if (CC.isInvalid()) 11596 return; 11597 11598 if (Source->isAtomicType()) 11599 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11600 11601 // Diagnose implicit casts to bool. 11602 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11603 if (isa<StringLiteral>(E)) 11604 // Warn on string literal to bool. Checks for string literals in logical 11605 // and expressions, for instance, assert(0 && "error here"), are 11606 // prevented by a check in AnalyzeImplicitConversions(). 11607 return DiagnoseImpCast(S, E, T, CC, 11608 diag::warn_impcast_string_literal_to_bool); 11609 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11610 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11611 // This covers the literal expressions that evaluate to Objective-C 11612 // objects. 11613 return DiagnoseImpCast(S, E, T, CC, 11614 diag::warn_impcast_objective_c_literal_to_bool); 11615 } 11616 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11617 // Warn on pointer to bool conversion that is always true. 11618 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11619 SourceRange(CC)); 11620 } 11621 } 11622 11623 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11624 // is a typedef for signed char (macOS), then that constant value has to be 1 11625 // or 0. 11626 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11627 Expr::EvalResult Result; 11628 if (E->EvaluateAsInt(Result, S.getASTContext(), 11629 Expr::SE_AllowSideEffects)) { 11630 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11631 adornObjCBoolConversionDiagWithTernaryFixit( 11632 S, E, 11633 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11634 << Result.Val.getInt().toString(10)); 11635 } 11636 return; 11637 } 11638 } 11639 11640 // Check implicit casts from Objective-C collection literals to specialized 11641 // collection types, e.g., NSArray<NSString *> *. 11642 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11643 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11644 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11645 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11646 11647 // Strip vector types. 11648 if (isa<VectorType>(Source)) { 11649 if (!isa<VectorType>(Target)) { 11650 if (S.SourceMgr.isInSystemMacro(CC)) 11651 return; 11652 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11653 } 11654 11655 // If the vector cast is cast between two vectors of the same size, it is 11656 // a bitcast, not a conversion. 11657 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11658 return; 11659 11660 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11661 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11662 } 11663 if (auto VecTy = dyn_cast<VectorType>(Target)) 11664 Target = VecTy->getElementType().getTypePtr(); 11665 11666 // Strip complex types. 11667 if (isa<ComplexType>(Source)) { 11668 if (!isa<ComplexType>(Target)) { 11669 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11670 return; 11671 11672 return DiagnoseImpCast(S, E, T, CC, 11673 S.getLangOpts().CPlusPlus 11674 ? diag::err_impcast_complex_scalar 11675 : diag::warn_impcast_complex_scalar); 11676 } 11677 11678 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11679 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11680 } 11681 11682 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11683 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11684 11685 // If the source is floating point... 11686 if (SourceBT && SourceBT->isFloatingPoint()) { 11687 // ...and the target is floating point... 11688 if (TargetBT && TargetBT->isFloatingPoint()) { 11689 // ...then warn if we're dropping FP rank. 11690 11691 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11692 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11693 if (Order > 0) { 11694 // Don't warn about float constants that are precisely 11695 // representable in the target type. 11696 Expr::EvalResult result; 11697 if (E->EvaluateAsRValue(result, S.Context)) { 11698 // Value might be a float, a float vector, or a float complex. 11699 if (IsSameFloatAfterCast(result.Val, 11700 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11701 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11702 return; 11703 } 11704 11705 if (S.SourceMgr.isInSystemMacro(CC)) 11706 return; 11707 11708 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11709 } 11710 // ... or possibly if we're increasing rank, too 11711 else if (Order < 0) { 11712 if (S.SourceMgr.isInSystemMacro(CC)) 11713 return; 11714 11715 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11716 } 11717 return; 11718 } 11719 11720 // If the target is integral, always warn. 11721 if (TargetBT && TargetBT->isInteger()) { 11722 if (S.SourceMgr.isInSystemMacro(CC)) 11723 return; 11724 11725 DiagnoseFloatingImpCast(S, E, T, CC); 11726 } 11727 11728 // Detect the case where a call result is converted from floating-point to 11729 // to bool, and the final argument to the call is converted from bool, to 11730 // discover this typo: 11731 // 11732 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11733 // 11734 // FIXME: This is an incredibly special case; is there some more general 11735 // way to detect this class of misplaced-parentheses bug? 11736 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11737 // Check last argument of function call to see if it is an 11738 // implicit cast from a type matching the type the result 11739 // is being cast to. 11740 CallExpr *CEx = cast<CallExpr>(E); 11741 if (unsigned NumArgs = CEx->getNumArgs()) { 11742 Expr *LastA = CEx->getArg(NumArgs - 1); 11743 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11744 if (isa<ImplicitCastExpr>(LastA) && 11745 InnerE->getType()->isBooleanType()) { 11746 // Warn on this floating-point to bool conversion 11747 DiagnoseImpCast(S, E, T, CC, 11748 diag::warn_impcast_floating_point_to_bool); 11749 } 11750 } 11751 } 11752 return; 11753 } 11754 11755 // Valid casts involving fixed point types should be accounted for here. 11756 if (Source->isFixedPointType()) { 11757 if (Target->isUnsaturatedFixedPointType()) { 11758 Expr::EvalResult Result; 11759 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11760 S.isConstantEvaluated())) { 11761 APFixedPoint Value = Result.Val.getFixedPoint(); 11762 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11763 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11764 if (Value > MaxVal || Value < MinVal) { 11765 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11766 S.PDiag(diag::warn_impcast_fixed_point_range) 11767 << Value.toString() << T 11768 << E->getSourceRange() 11769 << clang::SourceRange(CC)); 11770 return; 11771 } 11772 } 11773 } else if (Target->isIntegerType()) { 11774 Expr::EvalResult Result; 11775 if (!S.isConstantEvaluated() && 11776 E->EvaluateAsFixedPoint(Result, S.Context, 11777 Expr::SE_AllowSideEffects)) { 11778 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11779 11780 bool Overflowed; 11781 llvm::APSInt IntResult = FXResult.convertToInt( 11782 S.Context.getIntWidth(T), 11783 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11784 11785 if (Overflowed) { 11786 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11787 S.PDiag(diag::warn_impcast_fixed_point_range) 11788 << FXResult.toString() << T 11789 << E->getSourceRange() 11790 << clang::SourceRange(CC)); 11791 return; 11792 } 11793 } 11794 } 11795 } else if (Target->isUnsaturatedFixedPointType()) { 11796 if (Source->isIntegerType()) { 11797 Expr::EvalResult Result; 11798 if (!S.isConstantEvaluated() && 11799 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11800 llvm::APSInt Value = Result.Val.getInt(); 11801 11802 bool Overflowed; 11803 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11804 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11805 11806 if (Overflowed) { 11807 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11808 S.PDiag(diag::warn_impcast_fixed_point_range) 11809 << Value.toString(/*Radix=*/10) << T 11810 << E->getSourceRange() 11811 << clang::SourceRange(CC)); 11812 return; 11813 } 11814 } 11815 } 11816 } 11817 11818 // If we are casting an integer type to a floating point type without 11819 // initialization-list syntax, we might lose accuracy if the floating 11820 // point type has a narrower significand than the integer type. 11821 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11822 TargetBT->isFloatingType() && !IsListInit) { 11823 // Determine the number of precision bits in the source integer type. 11824 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11825 unsigned int SourcePrecision = SourceRange.Width; 11826 11827 // Determine the number of precision bits in the 11828 // target floating point type. 11829 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11830 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11831 11832 if (SourcePrecision > 0 && TargetPrecision > 0 && 11833 SourcePrecision > TargetPrecision) { 11834 11835 llvm::APSInt SourceInt; 11836 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11837 // If the source integer is a constant, convert it to the target 11838 // floating point type. Issue a warning if the value changes 11839 // during the whole conversion. 11840 llvm::APFloat TargetFloatValue( 11841 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11842 llvm::APFloat::opStatus ConversionStatus = 11843 TargetFloatValue.convertFromAPInt( 11844 SourceInt, SourceBT->isSignedInteger(), 11845 llvm::APFloat::rmNearestTiesToEven); 11846 11847 if (ConversionStatus != llvm::APFloat::opOK) { 11848 std::string PrettySourceValue = SourceInt.toString(10); 11849 SmallString<32> PrettyTargetValue; 11850 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11851 11852 S.DiagRuntimeBehavior( 11853 E->getExprLoc(), E, 11854 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11855 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11856 << E->getSourceRange() << clang::SourceRange(CC)); 11857 } 11858 } else { 11859 // Otherwise, the implicit conversion may lose precision. 11860 DiagnoseImpCast(S, E, T, CC, 11861 diag::warn_impcast_integer_float_precision); 11862 } 11863 } 11864 } 11865 11866 DiagnoseNullConversion(S, E, T, CC); 11867 11868 S.DiscardMisalignedMemberAddress(Target, E); 11869 11870 if (Target->isBooleanType()) 11871 DiagnoseIntInBoolContext(S, E); 11872 11873 if (!Source->isIntegerType() || !Target->isIntegerType()) 11874 return; 11875 11876 // TODO: remove this early return once the false positives for constant->bool 11877 // in templates, macros, etc, are reduced or removed. 11878 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11879 return; 11880 11881 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11882 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11883 return adornObjCBoolConversionDiagWithTernaryFixit( 11884 S, E, 11885 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11886 << E->getType()); 11887 } 11888 11889 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11890 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11891 11892 if (SourceRange.Width > TargetRange.Width) { 11893 // If the source is a constant, use a default-on diagnostic. 11894 // TODO: this should happen for bitfield stores, too. 11895 Expr::EvalResult Result; 11896 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11897 S.isConstantEvaluated())) { 11898 llvm::APSInt Value(32); 11899 Value = Result.Val.getInt(); 11900 11901 if (S.SourceMgr.isInSystemMacro(CC)) 11902 return; 11903 11904 std::string PrettySourceValue = Value.toString(10); 11905 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11906 11907 S.DiagRuntimeBehavior( 11908 E->getExprLoc(), E, 11909 S.PDiag(diag::warn_impcast_integer_precision_constant) 11910 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11911 << E->getSourceRange() << clang::SourceRange(CC)); 11912 return; 11913 } 11914 11915 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11916 if (S.SourceMgr.isInSystemMacro(CC)) 11917 return; 11918 11919 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11920 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11921 /* pruneControlFlow */ true); 11922 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11923 } 11924 11925 if (TargetRange.Width > SourceRange.Width) { 11926 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11927 if (UO->getOpcode() == UO_Minus) 11928 if (Source->isUnsignedIntegerType()) { 11929 if (Target->isUnsignedIntegerType()) 11930 return DiagnoseImpCast(S, E, T, CC, 11931 diag::warn_impcast_high_order_zero_bits); 11932 if (Target->isSignedIntegerType()) 11933 return DiagnoseImpCast(S, E, T, CC, 11934 diag::warn_impcast_nonnegative_result); 11935 } 11936 } 11937 11938 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11939 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11940 // Warn when doing a signed to signed conversion, warn if the positive 11941 // source value is exactly the width of the target type, which will 11942 // cause a negative value to be stored. 11943 11944 Expr::EvalResult Result; 11945 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11946 !S.SourceMgr.isInSystemMacro(CC)) { 11947 llvm::APSInt Value = Result.Val.getInt(); 11948 if (isSameWidthConstantConversion(S, E, T, CC)) { 11949 std::string PrettySourceValue = Value.toString(10); 11950 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11951 11952 S.DiagRuntimeBehavior( 11953 E->getExprLoc(), E, 11954 S.PDiag(diag::warn_impcast_integer_precision_constant) 11955 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11956 << E->getSourceRange() << clang::SourceRange(CC)); 11957 return; 11958 } 11959 } 11960 11961 // Fall through for non-constants to give a sign conversion warning. 11962 } 11963 11964 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11965 (!TargetRange.NonNegative && SourceRange.NonNegative && 11966 SourceRange.Width == TargetRange.Width)) { 11967 if (S.SourceMgr.isInSystemMacro(CC)) 11968 return; 11969 11970 unsigned DiagID = diag::warn_impcast_integer_sign; 11971 11972 // Traditionally, gcc has warned about this under -Wsign-compare. 11973 // We also want to warn about it in -Wconversion. 11974 // So if -Wconversion is off, use a completely identical diagnostic 11975 // in the sign-compare group. 11976 // The conditional-checking code will 11977 if (ICContext) { 11978 DiagID = diag::warn_impcast_integer_sign_conditional; 11979 *ICContext = true; 11980 } 11981 11982 return DiagnoseImpCast(S, E, T, CC, DiagID); 11983 } 11984 11985 // Diagnose conversions between different enumeration types. 11986 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11987 // type, to give us better diagnostics. 11988 QualType SourceType = E->getType(); 11989 if (!S.getLangOpts().CPlusPlus) { 11990 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11991 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11992 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11993 SourceType = S.Context.getTypeDeclType(Enum); 11994 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11995 } 11996 } 11997 11998 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11999 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 12000 if (SourceEnum->getDecl()->hasNameForLinkage() && 12001 TargetEnum->getDecl()->hasNameForLinkage() && 12002 SourceEnum != TargetEnum) { 12003 if (S.SourceMgr.isInSystemMacro(CC)) 12004 return; 12005 12006 return DiagnoseImpCast(S, E, SourceType, T, CC, 12007 diag::warn_impcast_different_enum_types); 12008 } 12009 } 12010 12011 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 12012 SourceLocation CC, QualType T); 12013 12014 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12015 SourceLocation CC, bool &ICContext) { 12016 E = E->IgnoreParenImpCasts(); 12017 12018 if (isa<ConditionalOperator>(E)) 12019 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 12020 12021 AnalyzeImplicitConversions(S, E, CC); 12022 if (E->getType() != T) 12023 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12024 } 12025 12026 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 12027 SourceLocation CC, QualType T) { 12028 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12029 12030 bool Suspicious = false; 12031 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 12032 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12033 CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(), 12034 E->getFalseExpr()); 12035 12036 if (T->isBooleanType()) 12037 DiagnoseIntInBoolContext(S, E); 12038 12039 // If -Wconversion would have warned about either of the candidates 12040 // for a signedness conversion to the context type... 12041 if (!Suspicious) return; 12042 12043 // ...but it's currently ignored... 12044 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12045 return; 12046 12047 // ...then check whether it would have warned about either of the 12048 // candidates for a signedness conversion to the condition type. 12049 if (E->getType() == T) return; 12050 12051 Suspicious = false; 12052 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 12053 E->getType(), CC, &Suspicious); 12054 if (!Suspicious) 12055 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12056 E->getType(), CC, &Suspicious); 12057 } 12058 12059 /// Check conversion of given expression to boolean. 12060 /// Input argument E is a logical expression. 12061 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12062 if (S.getLangOpts().Bool) 12063 return; 12064 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12065 return; 12066 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12067 } 12068 12069 /// AnalyzeImplicitConversions - Find and report any interesting 12070 /// implicit conversions in the given expression. There are a couple 12071 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12072 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12073 bool IsListInit/*= false*/) { 12074 QualType T = OrigE->getType(); 12075 Expr *E = OrigE->IgnoreParenImpCasts(); 12076 12077 // Propagate whether we are in a C++ list initialization expression. 12078 // If so, we do not issue warnings for implicit int-float conversion 12079 // precision loss, because C++11 narrowing already handles it. 12080 IsListInit = 12081 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12082 12083 if (E->isTypeDependent() || E->isValueDependent()) 12084 return; 12085 12086 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 12087 if (UO->getOpcode() == UO_Not && 12088 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12089 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12090 << OrigE->getSourceRange() << T->isBooleanType() 12091 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12092 12093 // For conditional operators, we analyze the arguments as if they 12094 // were being fed directly into the output. 12095 if (isa<ConditionalOperator>(E)) { 12096 ConditionalOperator *CO = cast<ConditionalOperator>(E); 12097 CheckConditionalOperator(S, CO, CC, T); 12098 return; 12099 } 12100 12101 // Check implicit argument conversions for function calls. 12102 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 12103 CheckImplicitArgumentConversions(S, Call, CC); 12104 12105 // Go ahead and check any implicit conversions we might have skipped. 12106 // The non-canonical typecheck is just an optimization; 12107 // CheckImplicitConversion will filter out dead implicit conversions. 12108 if (E->getType() != T) 12109 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit); 12110 12111 // Now continue drilling into this expression. 12112 12113 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12114 // The bound subexpressions in a PseudoObjectExpr are not reachable 12115 // as transitive children. 12116 // FIXME: Use a more uniform representation for this. 12117 for (auto *SE : POE->semantics()) 12118 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12119 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 12120 } 12121 12122 // Skip past explicit casts. 12123 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12124 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12125 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12126 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12127 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 12128 } 12129 12130 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12131 // Do a somewhat different check with comparison operators. 12132 if (BO->isComparisonOp()) 12133 return AnalyzeComparison(S, BO); 12134 12135 // And with simple assignments. 12136 if (BO->getOpcode() == BO_Assign) 12137 return AnalyzeAssignment(S, BO); 12138 // And with compound assignments. 12139 if (BO->isAssignmentOp()) 12140 return AnalyzeCompoundAssignment(S, BO); 12141 } 12142 12143 // These break the otherwise-useful invariant below. Fortunately, 12144 // we don't really need to recurse into them, because any internal 12145 // expressions should have been analyzed already when they were 12146 // built into statements. 12147 if (isa<StmtExpr>(E)) return; 12148 12149 // Don't descend into unevaluated contexts. 12150 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12151 12152 // Now just recurse over the expression's children. 12153 CC = E->getExprLoc(); 12154 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12155 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12156 for (Stmt *SubStmt : E->children()) { 12157 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12158 if (!ChildExpr) 12159 continue; 12160 12161 if (IsLogicalAndOperator && 12162 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12163 // Ignore checking string literals that are in logical and operators. 12164 // This is a common pattern for asserts. 12165 continue; 12166 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 12167 } 12168 12169 if (BO && BO->isLogicalOp()) { 12170 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12171 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12172 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12173 12174 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12175 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12176 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12177 } 12178 12179 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12180 if (U->getOpcode() == UO_LNot) { 12181 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12182 } else if (U->getOpcode() != UO_AddrOf) { 12183 if (U->getSubExpr()->getType()->isAtomicType()) 12184 S.Diag(U->getSubExpr()->getBeginLoc(), 12185 diag::warn_atomic_implicit_seq_cst); 12186 } 12187 } 12188 } 12189 12190 /// Diagnose integer type and any valid implicit conversion to it. 12191 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12192 // Taking into account implicit conversions, 12193 // allow any integer. 12194 if (!E->getType()->isIntegerType()) { 12195 S.Diag(E->getBeginLoc(), 12196 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12197 return true; 12198 } 12199 // Potentially emit standard warnings for implicit conversions if enabled 12200 // using -Wconversion. 12201 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12202 return false; 12203 } 12204 12205 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12206 // Returns true when emitting a warning about taking the address of a reference. 12207 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12208 const PartialDiagnostic &PD) { 12209 E = E->IgnoreParenImpCasts(); 12210 12211 const FunctionDecl *FD = nullptr; 12212 12213 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12214 if (!DRE->getDecl()->getType()->isReferenceType()) 12215 return false; 12216 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12217 if (!M->getMemberDecl()->getType()->isReferenceType()) 12218 return false; 12219 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12220 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12221 return false; 12222 FD = Call->getDirectCallee(); 12223 } else { 12224 return false; 12225 } 12226 12227 SemaRef.Diag(E->getExprLoc(), PD); 12228 12229 // If possible, point to location of function. 12230 if (FD) { 12231 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12232 } 12233 12234 return true; 12235 } 12236 12237 // Returns true if the SourceLocation is expanded from any macro body. 12238 // Returns false if the SourceLocation is invalid, is from not in a macro 12239 // expansion, or is from expanded from a top-level macro argument. 12240 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12241 if (Loc.isInvalid()) 12242 return false; 12243 12244 while (Loc.isMacroID()) { 12245 if (SM.isMacroBodyExpansion(Loc)) 12246 return true; 12247 Loc = SM.getImmediateMacroCallerLoc(Loc); 12248 } 12249 12250 return false; 12251 } 12252 12253 /// Diagnose pointers that are always non-null. 12254 /// \param E the expression containing the pointer 12255 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12256 /// compared to a null pointer 12257 /// \param IsEqual True when the comparison is equal to a null pointer 12258 /// \param Range Extra SourceRange to highlight in the diagnostic 12259 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12260 Expr::NullPointerConstantKind NullKind, 12261 bool IsEqual, SourceRange Range) { 12262 if (!E) 12263 return; 12264 12265 // Don't warn inside macros. 12266 if (E->getExprLoc().isMacroID()) { 12267 const SourceManager &SM = getSourceManager(); 12268 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12269 IsInAnyMacroBody(SM, Range.getBegin())) 12270 return; 12271 } 12272 E = E->IgnoreImpCasts(); 12273 12274 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12275 12276 if (isa<CXXThisExpr>(E)) { 12277 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12278 : diag::warn_this_bool_conversion; 12279 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12280 return; 12281 } 12282 12283 bool IsAddressOf = false; 12284 12285 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12286 if (UO->getOpcode() != UO_AddrOf) 12287 return; 12288 IsAddressOf = true; 12289 E = UO->getSubExpr(); 12290 } 12291 12292 if (IsAddressOf) { 12293 unsigned DiagID = IsCompare 12294 ? diag::warn_address_of_reference_null_compare 12295 : diag::warn_address_of_reference_bool_conversion; 12296 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12297 << IsEqual; 12298 if (CheckForReference(*this, E, PD)) { 12299 return; 12300 } 12301 } 12302 12303 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12304 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12305 std::string Str; 12306 llvm::raw_string_ostream S(Str); 12307 E->printPretty(S, nullptr, getPrintingPolicy()); 12308 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12309 : diag::warn_cast_nonnull_to_bool; 12310 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12311 << E->getSourceRange() << Range << IsEqual; 12312 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12313 }; 12314 12315 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12316 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12317 if (auto *Callee = Call->getDirectCallee()) { 12318 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12319 ComplainAboutNonnullParamOrCall(A); 12320 return; 12321 } 12322 } 12323 } 12324 12325 // Expect to find a single Decl. Skip anything more complicated. 12326 ValueDecl *D = nullptr; 12327 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12328 D = R->getDecl(); 12329 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12330 D = M->getMemberDecl(); 12331 } 12332 12333 // Weak Decls can be null. 12334 if (!D || D->isWeak()) 12335 return; 12336 12337 // Check for parameter decl with nonnull attribute 12338 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12339 if (getCurFunction() && 12340 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12341 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12342 ComplainAboutNonnullParamOrCall(A); 12343 return; 12344 } 12345 12346 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12347 // Skip function template not specialized yet. 12348 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12349 return; 12350 auto ParamIter = llvm::find(FD->parameters(), PV); 12351 assert(ParamIter != FD->param_end()); 12352 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12353 12354 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12355 if (!NonNull->args_size()) { 12356 ComplainAboutNonnullParamOrCall(NonNull); 12357 return; 12358 } 12359 12360 for (const ParamIdx &ArgNo : NonNull->args()) { 12361 if (ArgNo.getASTIndex() == ParamNo) { 12362 ComplainAboutNonnullParamOrCall(NonNull); 12363 return; 12364 } 12365 } 12366 } 12367 } 12368 } 12369 } 12370 12371 QualType T = D->getType(); 12372 const bool IsArray = T->isArrayType(); 12373 const bool IsFunction = T->isFunctionType(); 12374 12375 // Address of function is used to silence the function warning. 12376 if (IsAddressOf && IsFunction) { 12377 return; 12378 } 12379 12380 // Found nothing. 12381 if (!IsAddressOf && !IsFunction && !IsArray) 12382 return; 12383 12384 // Pretty print the expression for the diagnostic. 12385 std::string Str; 12386 llvm::raw_string_ostream S(Str); 12387 E->printPretty(S, nullptr, getPrintingPolicy()); 12388 12389 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12390 : diag::warn_impcast_pointer_to_bool; 12391 enum { 12392 AddressOf, 12393 FunctionPointer, 12394 ArrayPointer 12395 } DiagType; 12396 if (IsAddressOf) 12397 DiagType = AddressOf; 12398 else if (IsFunction) 12399 DiagType = FunctionPointer; 12400 else if (IsArray) 12401 DiagType = ArrayPointer; 12402 else 12403 llvm_unreachable("Could not determine diagnostic."); 12404 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12405 << Range << IsEqual; 12406 12407 if (!IsFunction) 12408 return; 12409 12410 // Suggest '&' to silence the function warning. 12411 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12412 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12413 12414 // Check to see if '()' fixit should be emitted. 12415 QualType ReturnType; 12416 UnresolvedSet<4> NonTemplateOverloads; 12417 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12418 if (ReturnType.isNull()) 12419 return; 12420 12421 if (IsCompare) { 12422 // There are two cases here. If there is null constant, the only suggest 12423 // for a pointer return type. If the null is 0, then suggest if the return 12424 // type is a pointer or an integer type. 12425 if (!ReturnType->isPointerType()) { 12426 if (NullKind == Expr::NPCK_ZeroExpression || 12427 NullKind == Expr::NPCK_ZeroLiteral) { 12428 if (!ReturnType->isIntegerType()) 12429 return; 12430 } else { 12431 return; 12432 } 12433 } 12434 } else { // !IsCompare 12435 // For function to bool, only suggest if the function pointer has bool 12436 // return type. 12437 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12438 return; 12439 } 12440 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12441 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12442 } 12443 12444 /// Diagnoses "dangerous" implicit conversions within the given 12445 /// expression (which is a full expression). Implements -Wconversion 12446 /// and -Wsign-compare. 12447 /// 12448 /// \param CC the "context" location of the implicit conversion, i.e. 12449 /// the most location of the syntactic entity requiring the implicit 12450 /// conversion 12451 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12452 // Don't diagnose in unevaluated contexts. 12453 if (isUnevaluatedContext()) 12454 return; 12455 12456 // Don't diagnose for value- or type-dependent expressions. 12457 if (E->isTypeDependent() || E->isValueDependent()) 12458 return; 12459 12460 // Check for array bounds violations in cases where the check isn't triggered 12461 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12462 // ArraySubscriptExpr is on the RHS of a variable initialization. 12463 CheckArrayAccess(E); 12464 12465 // This is not the right CC for (e.g.) a variable initialization. 12466 AnalyzeImplicitConversions(*this, E, CC); 12467 } 12468 12469 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12470 /// Input argument E is a logical expression. 12471 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12472 ::CheckBoolLikeConversion(*this, E, CC); 12473 } 12474 12475 /// Diagnose when expression is an integer constant expression and its evaluation 12476 /// results in integer overflow 12477 void Sema::CheckForIntOverflow (Expr *E) { 12478 // Use a work list to deal with nested struct initializers. 12479 SmallVector<Expr *, 2> Exprs(1, E); 12480 12481 do { 12482 Expr *OriginalE = Exprs.pop_back_val(); 12483 Expr *E = OriginalE->IgnoreParenCasts(); 12484 12485 if (isa<BinaryOperator>(E)) { 12486 E->EvaluateForOverflow(Context); 12487 continue; 12488 } 12489 12490 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12491 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12492 else if (isa<ObjCBoxedExpr>(OriginalE)) 12493 E->EvaluateForOverflow(Context); 12494 else if (auto Call = dyn_cast<CallExpr>(E)) 12495 Exprs.append(Call->arg_begin(), Call->arg_end()); 12496 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12497 Exprs.append(Message->arg_begin(), Message->arg_end()); 12498 } while (!Exprs.empty()); 12499 } 12500 12501 namespace { 12502 12503 /// Visitor for expressions which looks for unsequenced operations on the 12504 /// same object. 12505 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 12506 using Base = EvaluatedExprVisitor<SequenceChecker>; 12507 12508 /// A tree of sequenced regions within an expression. Two regions are 12509 /// unsequenced if one is an ancestor or a descendent of the other. When we 12510 /// finish processing an expression with sequencing, such as a comma 12511 /// expression, we fold its tree nodes into its parent, since they are 12512 /// unsequenced with respect to nodes we will visit later. 12513 class SequenceTree { 12514 struct Value { 12515 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12516 unsigned Parent : 31; 12517 unsigned Merged : 1; 12518 }; 12519 SmallVector<Value, 8> Values; 12520 12521 public: 12522 /// A region within an expression which may be sequenced with respect 12523 /// to some other region. 12524 class Seq { 12525 friend class SequenceTree; 12526 12527 unsigned Index; 12528 12529 explicit Seq(unsigned N) : Index(N) {} 12530 12531 public: 12532 Seq() : Index(0) {} 12533 }; 12534 12535 SequenceTree() { Values.push_back(Value(0)); } 12536 Seq root() const { return Seq(0); } 12537 12538 /// Create a new sequence of operations, which is an unsequenced 12539 /// subset of \p Parent. This sequence of operations is sequenced with 12540 /// respect to other children of \p Parent. 12541 Seq allocate(Seq Parent) { 12542 Values.push_back(Value(Parent.Index)); 12543 return Seq(Values.size() - 1); 12544 } 12545 12546 /// Merge a sequence of operations into its parent. 12547 void merge(Seq S) { 12548 Values[S.Index].Merged = true; 12549 } 12550 12551 /// Determine whether two operations are unsequenced. This operation 12552 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12553 /// should have been merged into its parent as appropriate. 12554 bool isUnsequenced(Seq Cur, Seq Old) { 12555 unsigned C = representative(Cur.Index); 12556 unsigned Target = representative(Old.Index); 12557 while (C >= Target) { 12558 if (C == Target) 12559 return true; 12560 C = Values[C].Parent; 12561 } 12562 return false; 12563 } 12564 12565 private: 12566 /// Pick a representative for a sequence. 12567 unsigned representative(unsigned K) { 12568 if (Values[K].Merged) 12569 // Perform path compression as we go. 12570 return Values[K].Parent = representative(Values[K].Parent); 12571 return K; 12572 } 12573 }; 12574 12575 /// An object for which we can track unsequenced uses. 12576 using Object = NamedDecl *; 12577 12578 /// Different flavors of object usage which we track. We only track the 12579 /// least-sequenced usage of each kind. 12580 enum UsageKind { 12581 /// A read of an object. Multiple unsequenced reads are OK. 12582 UK_Use, 12583 12584 /// A modification of an object which is sequenced before the value 12585 /// computation of the expression, such as ++n in C++. 12586 UK_ModAsValue, 12587 12588 /// A modification of an object which is not sequenced before the value 12589 /// computation of the expression, such as n++. 12590 UK_ModAsSideEffect, 12591 12592 UK_Count = UK_ModAsSideEffect + 1 12593 }; 12594 12595 struct Usage { 12596 Expr *Use; 12597 SequenceTree::Seq Seq; 12598 12599 Usage() : Use(nullptr), Seq() {} 12600 }; 12601 12602 struct UsageInfo { 12603 Usage Uses[UK_Count]; 12604 12605 /// Have we issued a diagnostic for this variable already? 12606 bool Diagnosed; 12607 12608 UsageInfo() : Uses(), Diagnosed(false) {} 12609 }; 12610 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12611 12612 Sema &SemaRef; 12613 12614 /// Sequenced regions within the expression. 12615 SequenceTree Tree; 12616 12617 /// Declaration modifications and references which we have seen. 12618 UsageInfoMap UsageMap; 12619 12620 /// The region we are currently within. 12621 SequenceTree::Seq Region; 12622 12623 /// Filled in with declarations which were modified as a side-effect 12624 /// (that is, post-increment operations). 12625 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12626 12627 /// Expressions to check later. We defer checking these to reduce 12628 /// stack usage. 12629 SmallVectorImpl<Expr *> &WorkList; 12630 12631 /// RAII object wrapping the visitation of a sequenced subexpression of an 12632 /// expression. At the end of this process, the side-effects of the evaluation 12633 /// become sequenced with respect to the value computation of the result, so 12634 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12635 /// UK_ModAsValue. 12636 struct SequencedSubexpression { 12637 SequencedSubexpression(SequenceChecker &Self) 12638 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12639 Self.ModAsSideEffect = &ModAsSideEffect; 12640 } 12641 12642 ~SequencedSubexpression() { 12643 for (auto &M : llvm::reverse(ModAsSideEffect)) { 12644 UsageInfo &U = Self.UsageMap[M.first]; 12645 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 12646 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 12647 SideEffectUsage = M.second; 12648 } 12649 Self.ModAsSideEffect = OldModAsSideEffect; 12650 } 12651 12652 SequenceChecker &Self; 12653 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12654 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12655 }; 12656 12657 /// RAII object wrapping the visitation of a subexpression which we might 12658 /// choose to evaluate as a constant. If any subexpression is evaluated and 12659 /// found to be non-constant, this allows us to suppress the evaluation of 12660 /// the outer expression. 12661 class EvaluationTracker { 12662 public: 12663 EvaluationTracker(SequenceChecker &Self) 12664 : Self(Self), Prev(Self.EvalTracker) { 12665 Self.EvalTracker = this; 12666 } 12667 12668 ~EvaluationTracker() { 12669 Self.EvalTracker = Prev; 12670 if (Prev) 12671 Prev->EvalOK &= EvalOK; 12672 } 12673 12674 bool evaluate(const Expr *E, bool &Result) { 12675 if (!EvalOK || E->isValueDependent()) 12676 return false; 12677 EvalOK = E->EvaluateAsBooleanCondition( 12678 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12679 return EvalOK; 12680 } 12681 12682 private: 12683 SequenceChecker &Self; 12684 EvaluationTracker *Prev; 12685 bool EvalOK = true; 12686 } *EvalTracker = nullptr; 12687 12688 /// Find the object which is produced by the specified expression, 12689 /// if any. 12690 Object getObject(Expr *E, bool Mod) const { 12691 E = E->IgnoreParenCasts(); 12692 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12693 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12694 return getObject(UO->getSubExpr(), Mod); 12695 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12696 if (BO->getOpcode() == BO_Comma) 12697 return getObject(BO->getRHS(), Mod); 12698 if (Mod && BO->isAssignmentOp()) 12699 return getObject(BO->getLHS(), Mod); 12700 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12701 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12702 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12703 return ME->getMemberDecl(); 12704 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12705 // FIXME: If this is a reference, map through to its value. 12706 return DRE->getDecl(); 12707 return nullptr; 12708 } 12709 12710 /// Note that an object was modified or used by an expression. 12711 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 12712 Usage &U = UI.Uses[UK]; 12713 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 12714 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12715 ModAsSideEffect->push_back(std::make_pair(O, U)); 12716 U.Use = Ref; 12717 U.Seq = Region; 12718 } 12719 } 12720 12721 /// Check whether a modification or use conflicts with a prior usage. 12722 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 12723 bool IsModMod) { 12724 if (UI.Diagnosed) 12725 return; 12726 12727 const Usage &U = UI.Uses[OtherKind]; 12728 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 12729 return; 12730 12731 Expr *Mod = U.Use; 12732 Expr *ModOrUse = Ref; 12733 if (OtherKind == UK_Use) 12734 std::swap(Mod, ModOrUse); 12735 12736 SemaRef.DiagRuntimeBehavior( 12737 Mod->getExprLoc(), {Mod, ModOrUse}, 12738 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12739 : diag::warn_unsequenced_mod_use) 12740 << O << SourceRange(ModOrUse->getExprLoc())); 12741 UI.Diagnosed = true; 12742 } 12743 12744 void notePreUse(Object O, Expr *Use) { 12745 UsageInfo &U = UsageMap[O]; 12746 // Uses conflict with other modifications. 12747 checkUsage(O, U, Use, UK_ModAsValue, false); 12748 } 12749 12750 void notePostUse(Object O, Expr *Use) { 12751 UsageInfo &U = UsageMap[O]; 12752 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 12753 addUsage(U, O, Use, UK_Use); 12754 } 12755 12756 void notePreMod(Object O, Expr *Mod) { 12757 UsageInfo &U = UsageMap[O]; 12758 // Modifications conflict with other modifications and with uses. 12759 checkUsage(O, U, Mod, UK_ModAsValue, true); 12760 checkUsage(O, U, Mod, UK_Use, false); 12761 } 12762 12763 void notePostMod(Object O, Expr *Use, UsageKind UK) { 12764 UsageInfo &U = UsageMap[O]; 12765 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 12766 addUsage(U, O, Use, UK); 12767 } 12768 12769 public: 12770 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 12771 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12772 Visit(E); 12773 } 12774 12775 void VisitStmt(Stmt *S) { 12776 // Skip all statements which aren't expressions for now. 12777 } 12778 12779 void VisitExpr(Expr *E) { 12780 // By default, just recurse to evaluated subexpressions. 12781 Base::VisitStmt(E); 12782 } 12783 12784 void VisitCastExpr(CastExpr *E) { 12785 Object O = Object(); 12786 if (E->getCastKind() == CK_LValueToRValue) 12787 O = getObject(E->getSubExpr(), false); 12788 12789 if (O) 12790 notePreUse(O, E); 12791 VisitExpr(E); 12792 if (O) 12793 notePostUse(O, E); 12794 } 12795 12796 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) { 12797 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12798 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12799 SequenceTree::Seq OldRegion = Region; 12800 12801 { 12802 SequencedSubexpression SeqBefore(*this); 12803 Region = BeforeRegion; 12804 Visit(SequencedBefore); 12805 } 12806 12807 Region = AfterRegion; 12808 Visit(SequencedAfter); 12809 12810 Region = OldRegion; 12811 12812 Tree.merge(BeforeRegion); 12813 Tree.merge(AfterRegion); 12814 } 12815 12816 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) { 12817 // C++17 [expr.sub]p1: 12818 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12819 // expression E1 is sequenced before the expression E2. 12820 if (SemaRef.getLangOpts().CPlusPlus17) 12821 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12822 else 12823 Base::VisitStmt(ASE); 12824 } 12825 12826 void VisitBinComma(BinaryOperator *BO) { 12827 // C++11 [expr.comma]p1: 12828 // Every value computation and side effect associated with the left 12829 // expression is sequenced before every value computation and side 12830 // effect associated with the right expression. 12831 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12832 } 12833 12834 void VisitBinAssign(BinaryOperator *BO) { 12835 // The modification is sequenced after the value computation of the LHS 12836 // and RHS, so check it before inspecting the operands and update the 12837 // map afterwards. 12838 Object O = getObject(BO->getLHS(), true); 12839 if (!O) 12840 return VisitExpr(BO); 12841 12842 notePreMod(O, BO); 12843 12844 // C++11 [expr.ass]p7: 12845 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 12846 // only once. 12847 // 12848 // Therefore, for a compound assignment operator, O is considered used 12849 // everywhere except within the evaluation of E1 itself. 12850 if (isa<CompoundAssignOperator>(BO)) 12851 notePreUse(O, BO); 12852 12853 Visit(BO->getLHS()); 12854 12855 if (isa<CompoundAssignOperator>(BO)) 12856 notePostUse(O, BO); 12857 12858 Visit(BO->getRHS()); 12859 12860 // C++11 [expr.ass]p1: 12861 // the assignment is sequenced [...] before the value computation of the 12862 // assignment expression. 12863 // C11 6.5.16/3 has no such rule. 12864 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12865 : UK_ModAsSideEffect); 12866 } 12867 12868 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 12869 VisitBinAssign(CAO); 12870 } 12871 12872 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12873 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12874 void VisitUnaryPreIncDec(UnaryOperator *UO) { 12875 Object O = getObject(UO->getSubExpr(), true); 12876 if (!O) 12877 return VisitExpr(UO); 12878 12879 notePreMod(O, UO); 12880 Visit(UO->getSubExpr()); 12881 // C++11 [expr.pre.incr]p1: 12882 // the expression ++x is equivalent to x+=1 12883 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12884 : UK_ModAsSideEffect); 12885 } 12886 12887 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12888 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12889 void VisitUnaryPostIncDec(UnaryOperator *UO) { 12890 Object O = getObject(UO->getSubExpr(), true); 12891 if (!O) 12892 return VisitExpr(UO); 12893 12894 notePreMod(O, UO); 12895 Visit(UO->getSubExpr()); 12896 notePostMod(O, UO, UK_ModAsSideEffect); 12897 } 12898 12899 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 12900 void VisitBinLOr(BinaryOperator *BO) { 12901 // The side-effects of the LHS of an '&&' are sequenced before the 12902 // value computation of the RHS, and hence before the value computation 12903 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 12904 // as if they were unconditionally sequenced. 12905 EvaluationTracker Eval(*this); 12906 { 12907 SequencedSubexpression Sequenced(*this); 12908 Visit(BO->getLHS()); 12909 } 12910 12911 bool Result; 12912 if (Eval.evaluate(BO->getLHS(), Result)) { 12913 if (!Result) 12914 Visit(BO->getRHS()); 12915 } else { 12916 // Check for unsequenced operations in the RHS, treating it as an 12917 // entirely separate evaluation. 12918 // 12919 // FIXME: If there are operations in the RHS which are unsequenced 12920 // with respect to operations outside the RHS, and those operations 12921 // are unconditionally evaluated, diagnose them. 12922 WorkList.push_back(BO->getRHS()); 12923 } 12924 } 12925 void VisitBinLAnd(BinaryOperator *BO) { 12926 EvaluationTracker Eval(*this); 12927 { 12928 SequencedSubexpression Sequenced(*this); 12929 Visit(BO->getLHS()); 12930 } 12931 12932 bool Result; 12933 if (Eval.evaluate(BO->getLHS(), Result)) { 12934 if (Result) 12935 Visit(BO->getRHS()); 12936 } else { 12937 WorkList.push_back(BO->getRHS()); 12938 } 12939 } 12940 12941 // Only visit the condition, unless we can be sure which subexpression will 12942 // be chosen. 12943 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 12944 EvaluationTracker Eval(*this); 12945 { 12946 SequencedSubexpression Sequenced(*this); 12947 Visit(CO->getCond()); 12948 } 12949 12950 bool Result; 12951 if (Eval.evaluate(CO->getCond(), Result)) 12952 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 12953 else { 12954 WorkList.push_back(CO->getTrueExpr()); 12955 WorkList.push_back(CO->getFalseExpr()); 12956 } 12957 } 12958 12959 void VisitCallExpr(CallExpr *CE) { 12960 // C++11 [intro.execution]p15: 12961 // When calling a function [...], every value computation and side effect 12962 // associated with any argument expression, or with the postfix expression 12963 // designating the called function, is sequenced before execution of every 12964 // expression or statement in the body of the function [and thus before 12965 // the value computation of its result]. 12966 SequencedSubexpression Sequenced(*this); 12967 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 12968 [&] { Base::VisitCallExpr(CE); }); 12969 12970 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12971 } 12972 12973 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 12974 // This is a call, so all subexpressions are sequenced before the result. 12975 SequencedSubexpression Sequenced(*this); 12976 12977 if (!CCE->isListInitialization()) 12978 return VisitExpr(CCE); 12979 12980 // In C++11, list initializations are sequenced. 12981 SmallVector<SequenceTree::Seq, 32> Elts; 12982 SequenceTree::Seq Parent = Region; 12983 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12984 E = CCE->arg_end(); 12985 I != E; ++I) { 12986 Region = Tree.allocate(Parent); 12987 Elts.push_back(Region); 12988 Visit(*I); 12989 } 12990 12991 // Forget that the initializers are sequenced. 12992 Region = Parent; 12993 for (unsigned I = 0; I < Elts.size(); ++I) 12994 Tree.merge(Elts[I]); 12995 } 12996 12997 void VisitInitListExpr(InitListExpr *ILE) { 12998 if (!SemaRef.getLangOpts().CPlusPlus11) 12999 return VisitExpr(ILE); 13000 13001 // In C++11, list initializations are sequenced. 13002 SmallVector<SequenceTree::Seq, 32> Elts; 13003 SequenceTree::Seq Parent = Region; 13004 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13005 Expr *E = ILE->getInit(I); 13006 if (!E) continue; 13007 Region = Tree.allocate(Parent); 13008 Elts.push_back(Region); 13009 Visit(E); 13010 } 13011 13012 // Forget that the initializers are sequenced. 13013 Region = Parent; 13014 for (unsigned I = 0; I < Elts.size(); ++I) 13015 Tree.merge(Elts[I]); 13016 } 13017 }; 13018 13019 } // namespace 13020 13021 void Sema::CheckUnsequencedOperations(Expr *E) { 13022 SmallVector<Expr *, 8> WorkList; 13023 WorkList.push_back(E); 13024 while (!WorkList.empty()) { 13025 Expr *Item = WorkList.pop_back_val(); 13026 SequenceChecker(*this, Item, WorkList); 13027 } 13028 } 13029 13030 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13031 bool IsConstexpr) { 13032 llvm::SaveAndRestore<bool> ConstantContext( 13033 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13034 CheckImplicitConversions(E, CheckLoc); 13035 if (!E->isInstantiationDependent()) 13036 CheckUnsequencedOperations(E); 13037 if (!IsConstexpr && !E->isValueDependent()) 13038 CheckForIntOverflow(E); 13039 DiagnoseMisalignedMembers(); 13040 } 13041 13042 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13043 FieldDecl *BitField, 13044 Expr *Init) { 13045 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13046 } 13047 13048 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13049 SourceLocation Loc) { 13050 if (!PType->isVariablyModifiedType()) 13051 return; 13052 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13053 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13054 return; 13055 } 13056 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13057 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13058 return; 13059 } 13060 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13061 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13062 return; 13063 } 13064 13065 const ArrayType *AT = S.Context.getAsArrayType(PType); 13066 if (!AT) 13067 return; 13068 13069 if (AT->getSizeModifier() != ArrayType::Star) { 13070 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13071 return; 13072 } 13073 13074 S.Diag(Loc, diag::err_array_star_in_function_definition); 13075 } 13076 13077 /// CheckParmsForFunctionDef - Check that the parameters of the given 13078 /// function are appropriate for the definition of a function. This 13079 /// takes care of any checks that cannot be performed on the 13080 /// declaration itself, e.g., that the types of each of the function 13081 /// parameters are complete. 13082 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13083 bool CheckParameterNames) { 13084 bool HasInvalidParm = false; 13085 for (ParmVarDecl *Param : Parameters) { 13086 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13087 // function declarator that is part of a function definition of 13088 // that function shall not have incomplete type. 13089 // 13090 // This is also C++ [dcl.fct]p6. 13091 if (!Param->isInvalidDecl() && 13092 RequireCompleteType(Param->getLocation(), Param->getType(), 13093 diag::err_typecheck_decl_incomplete_type)) { 13094 Param->setInvalidDecl(); 13095 HasInvalidParm = true; 13096 } 13097 13098 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13099 // declaration of each parameter shall include an identifier. 13100 if (CheckParameterNames && 13101 Param->getIdentifier() == nullptr && 13102 !Param->isImplicit() && 13103 !getLangOpts().CPlusPlus) 13104 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13105 13106 // C99 6.7.5.3p12: 13107 // If the function declarator is not part of a definition of that 13108 // function, parameters may have incomplete type and may use the [*] 13109 // notation in their sequences of declarator specifiers to specify 13110 // variable length array types. 13111 QualType PType = Param->getOriginalType(); 13112 // FIXME: This diagnostic should point the '[*]' if source-location 13113 // information is added for it. 13114 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13115 13116 // If the parameter is a c++ class type and it has to be destructed in the 13117 // callee function, declare the destructor so that it can be called by the 13118 // callee function. Do not perform any direct access check on the dtor here. 13119 if (!Param->isInvalidDecl()) { 13120 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13121 if (!ClassDecl->isInvalidDecl() && 13122 !ClassDecl->hasIrrelevantDestructor() && 13123 !ClassDecl->isDependentContext() && 13124 ClassDecl->isParamDestroyedInCallee()) { 13125 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13126 MarkFunctionReferenced(Param->getLocation(), Destructor); 13127 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13128 } 13129 } 13130 } 13131 13132 // Parameters with the pass_object_size attribute only need to be marked 13133 // constant at function definitions. Because we lack information about 13134 // whether we're on a declaration or definition when we're instantiating the 13135 // attribute, we need to check for constness here. 13136 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13137 if (!Param->getType().isConstQualified()) 13138 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13139 << Attr->getSpelling() << 1; 13140 13141 // Check for parameter names shadowing fields from the class. 13142 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13143 // The owning context for the parameter should be the function, but we 13144 // want to see if this function's declaration context is a record. 13145 DeclContext *DC = Param->getDeclContext(); 13146 if (DC && DC->isFunctionOrMethod()) { 13147 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13148 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13149 RD, /*DeclIsField*/ false); 13150 } 13151 } 13152 } 13153 13154 return HasInvalidParm; 13155 } 13156 13157 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 13158 /// or MemberExpr. 13159 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 13160 ASTContext &Context) { 13161 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 13162 return Context.getDeclAlign(DRE->getDecl()); 13163 13164 if (const auto *ME = dyn_cast<MemberExpr>(E)) 13165 return Context.getDeclAlign(ME->getMemberDecl()); 13166 13167 return TypeAlign; 13168 } 13169 13170 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13171 /// pointer cast increases the alignment requirements. 13172 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13173 // This is actually a lot of work to potentially be doing on every 13174 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13175 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13176 return; 13177 13178 // Ignore dependent types. 13179 if (T->isDependentType() || Op->getType()->isDependentType()) 13180 return; 13181 13182 // Require that the destination be a pointer type. 13183 const PointerType *DestPtr = T->getAs<PointerType>(); 13184 if (!DestPtr) return; 13185 13186 // If the destination has alignment 1, we're done. 13187 QualType DestPointee = DestPtr->getPointeeType(); 13188 if (DestPointee->isIncompleteType()) return; 13189 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13190 if (DestAlign.isOne()) return; 13191 13192 // Require that the source be a pointer type. 13193 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13194 if (!SrcPtr) return; 13195 QualType SrcPointee = SrcPtr->getPointeeType(); 13196 13197 // Whitelist casts from cv void*. We already implicitly 13198 // whitelisted casts to cv void*, since they have alignment 1. 13199 // Also whitelist casts involving incomplete types, which implicitly 13200 // includes 'void'. 13201 if (SrcPointee->isIncompleteType()) return; 13202 13203 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 13204 13205 if (auto *CE = dyn_cast<CastExpr>(Op)) { 13206 if (CE->getCastKind() == CK_ArrayToPointerDecay) 13207 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 13208 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 13209 if (UO->getOpcode() == UO_AddrOf) 13210 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 13211 } 13212 13213 if (SrcAlign >= DestAlign) return; 13214 13215 Diag(TRange.getBegin(), diag::warn_cast_align) 13216 << Op->getType() << T 13217 << static_cast<unsigned>(SrcAlign.getQuantity()) 13218 << static_cast<unsigned>(DestAlign.getQuantity()) 13219 << TRange << Op->getSourceRange(); 13220 } 13221 13222 /// Check whether this array fits the idiom of a size-one tail padded 13223 /// array member of a struct. 13224 /// 13225 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13226 /// commonly used to emulate flexible arrays in C89 code. 13227 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13228 const NamedDecl *ND) { 13229 if (Size != 1 || !ND) return false; 13230 13231 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13232 if (!FD) return false; 13233 13234 // Don't consider sizes resulting from macro expansions or template argument 13235 // substitution to form C89 tail-padded arrays. 13236 13237 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13238 while (TInfo) { 13239 TypeLoc TL = TInfo->getTypeLoc(); 13240 // Look through typedefs. 13241 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13242 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13243 TInfo = TDL->getTypeSourceInfo(); 13244 continue; 13245 } 13246 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13247 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13248 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13249 return false; 13250 } 13251 break; 13252 } 13253 13254 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13255 if (!RD) return false; 13256 if (RD->isUnion()) return false; 13257 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13258 if (!CRD->isStandardLayout()) return false; 13259 } 13260 13261 // See if this is the last field decl in the record. 13262 const Decl *D = FD; 13263 while ((D = D->getNextDeclInContext())) 13264 if (isa<FieldDecl>(D)) 13265 return false; 13266 return true; 13267 } 13268 13269 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13270 const ArraySubscriptExpr *ASE, 13271 bool AllowOnePastEnd, bool IndexNegated) { 13272 // Already diagnosed by the constant evaluator. 13273 if (isConstantEvaluated()) 13274 return; 13275 13276 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13277 if (IndexExpr->isValueDependent()) 13278 return; 13279 13280 const Type *EffectiveType = 13281 BaseExpr->getType()->getPointeeOrArrayElementType(); 13282 BaseExpr = BaseExpr->IgnoreParenCasts(); 13283 const ConstantArrayType *ArrayTy = 13284 Context.getAsConstantArrayType(BaseExpr->getType()); 13285 13286 if (!ArrayTy) 13287 return; 13288 13289 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13290 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13291 return; 13292 13293 Expr::EvalResult Result; 13294 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13295 return; 13296 13297 llvm::APSInt index = Result.Val.getInt(); 13298 if (IndexNegated) 13299 index = -index; 13300 13301 const NamedDecl *ND = nullptr; 13302 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13303 ND = DRE->getDecl(); 13304 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13305 ND = ME->getMemberDecl(); 13306 13307 if (index.isUnsigned() || !index.isNegative()) { 13308 // It is possible that the type of the base expression after 13309 // IgnoreParenCasts is incomplete, even though the type of the base 13310 // expression before IgnoreParenCasts is complete (see PR39746 for an 13311 // example). In this case we have no information about whether the array 13312 // access exceeds the array bounds. However we can still diagnose an array 13313 // access which precedes the array bounds. 13314 if (BaseType->isIncompleteType()) 13315 return; 13316 13317 llvm::APInt size = ArrayTy->getSize(); 13318 if (!size.isStrictlyPositive()) 13319 return; 13320 13321 if (BaseType != EffectiveType) { 13322 // Make sure we're comparing apples to apples when comparing index to size 13323 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13324 uint64_t array_typesize = Context.getTypeSize(BaseType); 13325 // Handle ptrarith_typesize being zero, such as when casting to void* 13326 if (!ptrarith_typesize) ptrarith_typesize = 1; 13327 if (ptrarith_typesize != array_typesize) { 13328 // There's a cast to a different size type involved 13329 uint64_t ratio = array_typesize / ptrarith_typesize; 13330 // TODO: Be smarter about handling cases where array_typesize is not a 13331 // multiple of ptrarith_typesize 13332 if (ptrarith_typesize * ratio == array_typesize) 13333 size *= llvm::APInt(size.getBitWidth(), ratio); 13334 } 13335 } 13336 13337 if (size.getBitWidth() > index.getBitWidth()) 13338 index = index.zext(size.getBitWidth()); 13339 else if (size.getBitWidth() < index.getBitWidth()) 13340 size = size.zext(index.getBitWidth()); 13341 13342 // For array subscripting the index must be less than size, but for pointer 13343 // arithmetic also allow the index (offset) to be equal to size since 13344 // computing the next address after the end of the array is legal and 13345 // commonly done e.g. in C++ iterators and range-based for loops. 13346 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13347 return; 13348 13349 // Also don't warn for arrays of size 1 which are members of some 13350 // structure. These are often used to approximate flexible arrays in C89 13351 // code. 13352 if (IsTailPaddedMemberArray(*this, size, ND)) 13353 return; 13354 13355 // Suppress the warning if the subscript expression (as identified by the 13356 // ']' location) and the index expression are both from macro expansions 13357 // within a system header. 13358 if (ASE) { 13359 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13360 ASE->getRBracketLoc()); 13361 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13362 SourceLocation IndexLoc = 13363 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13364 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13365 return; 13366 } 13367 } 13368 13369 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13370 if (ASE) 13371 DiagID = diag::warn_array_index_exceeds_bounds; 13372 13373 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13374 PDiag(DiagID) << index.toString(10, true) 13375 << size.toString(10, true) 13376 << (unsigned)size.getLimitedValue(~0U) 13377 << IndexExpr->getSourceRange()); 13378 } else { 13379 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13380 if (!ASE) { 13381 DiagID = diag::warn_ptr_arith_precedes_bounds; 13382 if (index.isNegative()) index = -index; 13383 } 13384 13385 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13386 PDiag(DiagID) << index.toString(10, true) 13387 << IndexExpr->getSourceRange()); 13388 } 13389 13390 if (!ND) { 13391 // Try harder to find a NamedDecl to point at in the note. 13392 while (const ArraySubscriptExpr *ASE = 13393 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13394 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13395 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13396 ND = DRE->getDecl(); 13397 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13398 ND = ME->getMemberDecl(); 13399 } 13400 13401 if (ND) 13402 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13403 PDiag(diag::note_array_declared_here) 13404 << ND->getDeclName()); 13405 } 13406 13407 void Sema::CheckArrayAccess(const Expr *expr) { 13408 int AllowOnePastEnd = 0; 13409 while (expr) { 13410 expr = expr->IgnoreParenImpCasts(); 13411 switch (expr->getStmtClass()) { 13412 case Stmt::ArraySubscriptExprClass: { 13413 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13414 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13415 AllowOnePastEnd > 0); 13416 expr = ASE->getBase(); 13417 break; 13418 } 13419 case Stmt::MemberExprClass: { 13420 expr = cast<MemberExpr>(expr)->getBase(); 13421 break; 13422 } 13423 case Stmt::OMPArraySectionExprClass: { 13424 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13425 if (ASE->getLowerBound()) 13426 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13427 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13428 return; 13429 } 13430 case Stmt::UnaryOperatorClass: { 13431 // Only unwrap the * and & unary operators 13432 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13433 expr = UO->getSubExpr(); 13434 switch (UO->getOpcode()) { 13435 case UO_AddrOf: 13436 AllowOnePastEnd++; 13437 break; 13438 case UO_Deref: 13439 AllowOnePastEnd--; 13440 break; 13441 default: 13442 return; 13443 } 13444 break; 13445 } 13446 case Stmt::ConditionalOperatorClass: { 13447 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13448 if (const Expr *lhs = cond->getLHS()) 13449 CheckArrayAccess(lhs); 13450 if (const Expr *rhs = cond->getRHS()) 13451 CheckArrayAccess(rhs); 13452 return; 13453 } 13454 case Stmt::CXXOperatorCallExprClass: { 13455 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13456 for (const auto *Arg : OCE->arguments()) 13457 CheckArrayAccess(Arg); 13458 return; 13459 } 13460 default: 13461 return; 13462 } 13463 } 13464 } 13465 13466 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13467 13468 namespace { 13469 13470 struct RetainCycleOwner { 13471 VarDecl *Variable = nullptr; 13472 SourceRange Range; 13473 SourceLocation Loc; 13474 bool Indirect = false; 13475 13476 RetainCycleOwner() = default; 13477 13478 void setLocsFrom(Expr *e) { 13479 Loc = e->getExprLoc(); 13480 Range = e->getSourceRange(); 13481 } 13482 }; 13483 13484 } // namespace 13485 13486 /// Consider whether capturing the given variable can possibly lead to 13487 /// a retain cycle. 13488 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13489 // In ARC, it's captured strongly iff the variable has __strong 13490 // lifetime. In MRR, it's captured strongly if the variable is 13491 // __block and has an appropriate type. 13492 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13493 return false; 13494 13495 owner.Variable = var; 13496 if (ref) 13497 owner.setLocsFrom(ref); 13498 return true; 13499 } 13500 13501 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13502 while (true) { 13503 e = e->IgnoreParens(); 13504 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13505 switch (cast->getCastKind()) { 13506 case CK_BitCast: 13507 case CK_LValueBitCast: 13508 case CK_LValueToRValue: 13509 case CK_ARCReclaimReturnedObject: 13510 e = cast->getSubExpr(); 13511 continue; 13512 13513 default: 13514 return false; 13515 } 13516 } 13517 13518 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13519 ObjCIvarDecl *ivar = ref->getDecl(); 13520 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13521 return false; 13522 13523 // Try to find a retain cycle in the base. 13524 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13525 return false; 13526 13527 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13528 owner.Indirect = true; 13529 return true; 13530 } 13531 13532 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13533 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13534 if (!var) return false; 13535 return considerVariable(var, ref, owner); 13536 } 13537 13538 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13539 if (member->isArrow()) return false; 13540 13541 // Don't count this as an indirect ownership. 13542 e = member->getBase(); 13543 continue; 13544 } 13545 13546 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13547 // Only pay attention to pseudo-objects on property references. 13548 ObjCPropertyRefExpr *pre 13549 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13550 ->IgnoreParens()); 13551 if (!pre) return false; 13552 if (pre->isImplicitProperty()) return false; 13553 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13554 if (!property->isRetaining() && 13555 !(property->getPropertyIvarDecl() && 13556 property->getPropertyIvarDecl()->getType() 13557 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13558 return false; 13559 13560 owner.Indirect = true; 13561 if (pre->isSuperReceiver()) { 13562 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13563 if (!owner.Variable) 13564 return false; 13565 owner.Loc = pre->getLocation(); 13566 owner.Range = pre->getSourceRange(); 13567 return true; 13568 } 13569 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13570 ->getSourceExpr()); 13571 continue; 13572 } 13573 13574 // Array ivars? 13575 13576 return false; 13577 } 13578 } 13579 13580 namespace { 13581 13582 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13583 ASTContext &Context; 13584 VarDecl *Variable; 13585 Expr *Capturer = nullptr; 13586 bool VarWillBeReased = false; 13587 13588 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13589 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13590 Context(Context), Variable(variable) {} 13591 13592 void VisitDeclRefExpr(DeclRefExpr *ref) { 13593 if (ref->getDecl() == Variable && !Capturer) 13594 Capturer = ref; 13595 } 13596 13597 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13598 if (Capturer) return; 13599 Visit(ref->getBase()); 13600 if (Capturer && ref->isFreeIvar()) 13601 Capturer = ref; 13602 } 13603 13604 void VisitBlockExpr(BlockExpr *block) { 13605 // Look inside nested blocks 13606 if (block->getBlockDecl()->capturesVariable(Variable)) 13607 Visit(block->getBlockDecl()->getBody()); 13608 } 13609 13610 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13611 if (Capturer) return; 13612 if (OVE->getSourceExpr()) 13613 Visit(OVE->getSourceExpr()); 13614 } 13615 13616 void VisitBinaryOperator(BinaryOperator *BinOp) { 13617 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13618 return; 13619 Expr *LHS = BinOp->getLHS(); 13620 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13621 if (DRE->getDecl() != Variable) 13622 return; 13623 if (Expr *RHS = BinOp->getRHS()) { 13624 RHS = RHS->IgnoreParenCasts(); 13625 llvm::APSInt Value; 13626 VarWillBeReased = 13627 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13628 } 13629 } 13630 } 13631 }; 13632 13633 } // namespace 13634 13635 /// Check whether the given argument is a block which captures a 13636 /// variable. 13637 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13638 assert(owner.Variable && owner.Loc.isValid()); 13639 13640 e = e->IgnoreParenCasts(); 13641 13642 // Look through [^{...} copy] and Block_copy(^{...}). 13643 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13644 Selector Cmd = ME->getSelector(); 13645 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13646 e = ME->getInstanceReceiver(); 13647 if (!e) 13648 return nullptr; 13649 e = e->IgnoreParenCasts(); 13650 } 13651 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13652 if (CE->getNumArgs() == 1) { 13653 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13654 if (Fn) { 13655 const IdentifierInfo *FnI = Fn->getIdentifier(); 13656 if (FnI && FnI->isStr("_Block_copy")) { 13657 e = CE->getArg(0)->IgnoreParenCasts(); 13658 } 13659 } 13660 } 13661 } 13662 13663 BlockExpr *block = dyn_cast<BlockExpr>(e); 13664 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13665 return nullptr; 13666 13667 FindCaptureVisitor visitor(S.Context, owner.Variable); 13668 visitor.Visit(block->getBlockDecl()->getBody()); 13669 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13670 } 13671 13672 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13673 RetainCycleOwner &owner) { 13674 assert(capturer); 13675 assert(owner.Variable && owner.Loc.isValid()); 13676 13677 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13678 << owner.Variable << capturer->getSourceRange(); 13679 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13680 << owner.Indirect << owner.Range; 13681 } 13682 13683 /// Check for a keyword selector that starts with the word 'add' or 13684 /// 'set'. 13685 static bool isSetterLikeSelector(Selector sel) { 13686 if (sel.isUnarySelector()) return false; 13687 13688 StringRef str = sel.getNameForSlot(0); 13689 while (!str.empty() && str.front() == '_') str = str.substr(1); 13690 if (str.startswith("set")) 13691 str = str.substr(3); 13692 else if (str.startswith("add")) { 13693 // Specially whitelist 'addOperationWithBlock:'. 13694 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13695 return false; 13696 str = str.substr(3); 13697 } 13698 else 13699 return false; 13700 13701 if (str.empty()) return true; 13702 return !isLowercase(str.front()); 13703 } 13704 13705 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13706 ObjCMessageExpr *Message) { 13707 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13708 Message->getReceiverInterface(), 13709 NSAPI::ClassId_NSMutableArray); 13710 if (!IsMutableArray) { 13711 return None; 13712 } 13713 13714 Selector Sel = Message->getSelector(); 13715 13716 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13717 S.NSAPIObj->getNSArrayMethodKind(Sel); 13718 if (!MKOpt) { 13719 return None; 13720 } 13721 13722 NSAPI::NSArrayMethodKind MK = *MKOpt; 13723 13724 switch (MK) { 13725 case NSAPI::NSMutableArr_addObject: 13726 case NSAPI::NSMutableArr_insertObjectAtIndex: 13727 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13728 return 0; 13729 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13730 return 1; 13731 13732 default: 13733 return None; 13734 } 13735 13736 return None; 13737 } 13738 13739 static 13740 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13741 ObjCMessageExpr *Message) { 13742 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13743 Message->getReceiverInterface(), 13744 NSAPI::ClassId_NSMutableDictionary); 13745 if (!IsMutableDictionary) { 13746 return None; 13747 } 13748 13749 Selector Sel = Message->getSelector(); 13750 13751 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13752 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13753 if (!MKOpt) { 13754 return None; 13755 } 13756 13757 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13758 13759 switch (MK) { 13760 case NSAPI::NSMutableDict_setObjectForKey: 13761 case NSAPI::NSMutableDict_setValueForKey: 13762 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13763 return 0; 13764 13765 default: 13766 return None; 13767 } 13768 13769 return None; 13770 } 13771 13772 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13773 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13774 Message->getReceiverInterface(), 13775 NSAPI::ClassId_NSMutableSet); 13776 13777 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13778 Message->getReceiverInterface(), 13779 NSAPI::ClassId_NSMutableOrderedSet); 13780 if (!IsMutableSet && !IsMutableOrderedSet) { 13781 return None; 13782 } 13783 13784 Selector Sel = Message->getSelector(); 13785 13786 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13787 if (!MKOpt) { 13788 return None; 13789 } 13790 13791 NSAPI::NSSetMethodKind MK = *MKOpt; 13792 13793 switch (MK) { 13794 case NSAPI::NSMutableSet_addObject: 13795 case NSAPI::NSOrderedSet_setObjectAtIndex: 13796 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13797 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13798 return 0; 13799 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13800 return 1; 13801 } 13802 13803 return None; 13804 } 13805 13806 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13807 if (!Message->isInstanceMessage()) { 13808 return; 13809 } 13810 13811 Optional<int> ArgOpt; 13812 13813 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13814 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13815 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13816 return; 13817 } 13818 13819 int ArgIndex = *ArgOpt; 13820 13821 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13822 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13823 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13824 } 13825 13826 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13827 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13828 if (ArgRE->isObjCSelfExpr()) { 13829 Diag(Message->getSourceRange().getBegin(), 13830 diag::warn_objc_circular_container) 13831 << ArgRE->getDecl() << StringRef("'super'"); 13832 } 13833 } 13834 } else { 13835 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13836 13837 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13838 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13839 } 13840 13841 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13842 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13843 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13844 ValueDecl *Decl = ReceiverRE->getDecl(); 13845 Diag(Message->getSourceRange().getBegin(), 13846 diag::warn_objc_circular_container) 13847 << Decl << Decl; 13848 if (!ArgRE->isObjCSelfExpr()) { 13849 Diag(Decl->getLocation(), 13850 diag::note_objc_circular_container_declared_here) 13851 << Decl; 13852 } 13853 } 13854 } 13855 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13856 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13857 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13858 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13859 Diag(Message->getSourceRange().getBegin(), 13860 diag::warn_objc_circular_container) 13861 << Decl << Decl; 13862 Diag(Decl->getLocation(), 13863 diag::note_objc_circular_container_declared_here) 13864 << Decl; 13865 } 13866 } 13867 } 13868 } 13869 } 13870 13871 /// Check a message send to see if it's likely to cause a retain cycle. 13872 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13873 // Only check instance methods whose selector looks like a setter. 13874 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13875 return; 13876 13877 // Try to find a variable that the receiver is strongly owned by. 13878 RetainCycleOwner owner; 13879 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13880 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13881 return; 13882 } else { 13883 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13884 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13885 owner.Loc = msg->getSuperLoc(); 13886 owner.Range = msg->getSuperLoc(); 13887 } 13888 13889 // Check whether the receiver is captured by any of the arguments. 13890 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13891 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13892 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13893 // noescape blocks should not be retained by the method. 13894 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13895 continue; 13896 return diagnoseRetainCycle(*this, capturer, owner); 13897 } 13898 } 13899 } 13900 13901 /// Check a property assign to see if it's likely to cause a retain cycle. 13902 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13903 RetainCycleOwner owner; 13904 if (!findRetainCycleOwner(*this, receiver, owner)) 13905 return; 13906 13907 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13908 diagnoseRetainCycle(*this, capturer, owner); 13909 } 13910 13911 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13912 RetainCycleOwner Owner; 13913 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13914 return; 13915 13916 // Because we don't have an expression for the variable, we have to set the 13917 // location explicitly here. 13918 Owner.Loc = Var->getLocation(); 13919 Owner.Range = Var->getSourceRange(); 13920 13921 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13922 diagnoseRetainCycle(*this, Capturer, Owner); 13923 } 13924 13925 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13926 Expr *RHS, bool isProperty) { 13927 // Check if RHS is an Objective-C object literal, which also can get 13928 // immediately zapped in a weak reference. Note that we explicitly 13929 // allow ObjCStringLiterals, since those are designed to never really die. 13930 RHS = RHS->IgnoreParenImpCasts(); 13931 13932 // This enum needs to match with the 'select' in 13933 // warn_objc_arc_literal_assign (off-by-1). 13934 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13935 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13936 return false; 13937 13938 S.Diag(Loc, diag::warn_arc_literal_assign) 13939 << (unsigned) Kind 13940 << (isProperty ? 0 : 1) 13941 << RHS->getSourceRange(); 13942 13943 return true; 13944 } 13945 13946 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13947 Qualifiers::ObjCLifetime LT, 13948 Expr *RHS, bool isProperty) { 13949 // Strip off any implicit cast added to get to the one ARC-specific. 13950 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13951 if (cast->getCastKind() == CK_ARCConsumeObject) { 13952 S.Diag(Loc, diag::warn_arc_retained_assign) 13953 << (LT == Qualifiers::OCL_ExplicitNone) 13954 << (isProperty ? 0 : 1) 13955 << RHS->getSourceRange(); 13956 return true; 13957 } 13958 RHS = cast->getSubExpr(); 13959 } 13960 13961 if (LT == Qualifiers::OCL_Weak && 13962 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13963 return true; 13964 13965 return false; 13966 } 13967 13968 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13969 QualType LHS, Expr *RHS) { 13970 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13971 13972 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13973 return false; 13974 13975 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13976 return true; 13977 13978 return false; 13979 } 13980 13981 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13982 Expr *LHS, Expr *RHS) { 13983 QualType LHSType; 13984 // PropertyRef on LHS type need be directly obtained from 13985 // its declaration as it has a PseudoType. 13986 ObjCPropertyRefExpr *PRE 13987 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13988 if (PRE && !PRE->isImplicitProperty()) { 13989 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13990 if (PD) 13991 LHSType = PD->getType(); 13992 } 13993 13994 if (LHSType.isNull()) 13995 LHSType = LHS->getType(); 13996 13997 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13998 13999 if (LT == Qualifiers::OCL_Weak) { 14000 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14001 getCurFunction()->markSafeWeakUse(LHS); 14002 } 14003 14004 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14005 return; 14006 14007 // FIXME. Check for other life times. 14008 if (LT != Qualifiers::OCL_None) 14009 return; 14010 14011 if (PRE) { 14012 if (PRE->isImplicitProperty()) 14013 return; 14014 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14015 if (!PD) 14016 return; 14017 14018 unsigned Attributes = PD->getPropertyAttributes(); 14019 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 14020 // when 'assign' attribute was not explicitly specified 14021 // by user, ignore it and rely on property type itself 14022 // for lifetime info. 14023 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14024 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 14025 LHSType->isObjCRetainableType()) 14026 return; 14027 14028 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14029 if (cast->getCastKind() == CK_ARCConsumeObject) { 14030 Diag(Loc, diag::warn_arc_retained_property_assign) 14031 << RHS->getSourceRange(); 14032 return; 14033 } 14034 RHS = cast->getSubExpr(); 14035 } 14036 } 14037 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 14038 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14039 return; 14040 } 14041 } 14042 } 14043 14044 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14045 14046 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14047 SourceLocation StmtLoc, 14048 const NullStmt *Body) { 14049 // Do not warn if the body is a macro that expands to nothing, e.g: 14050 // 14051 // #define CALL(x) 14052 // if (condition) 14053 // CALL(0); 14054 if (Body->hasLeadingEmptyMacro()) 14055 return false; 14056 14057 // Get line numbers of statement and body. 14058 bool StmtLineInvalid; 14059 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14060 &StmtLineInvalid); 14061 if (StmtLineInvalid) 14062 return false; 14063 14064 bool BodyLineInvalid; 14065 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14066 &BodyLineInvalid); 14067 if (BodyLineInvalid) 14068 return false; 14069 14070 // Warn if null statement and body are on the same line. 14071 if (StmtLine != BodyLine) 14072 return false; 14073 14074 return true; 14075 } 14076 14077 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14078 const Stmt *Body, 14079 unsigned DiagID) { 14080 // Since this is a syntactic check, don't emit diagnostic for template 14081 // instantiations, this just adds noise. 14082 if (CurrentInstantiationScope) 14083 return; 14084 14085 // The body should be a null statement. 14086 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14087 if (!NBody) 14088 return; 14089 14090 // Do the usual checks. 14091 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14092 return; 14093 14094 Diag(NBody->getSemiLoc(), DiagID); 14095 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14096 } 14097 14098 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14099 const Stmt *PossibleBody) { 14100 assert(!CurrentInstantiationScope); // Ensured by caller 14101 14102 SourceLocation StmtLoc; 14103 const Stmt *Body; 14104 unsigned DiagID; 14105 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14106 StmtLoc = FS->getRParenLoc(); 14107 Body = FS->getBody(); 14108 DiagID = diag::warn_empty_for_body; 14109 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14110 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14111 Body = WS->getBody(); 14112 DiagID = diag::warn_empty_while_body; 14113 } else 14114 return; // Neither `for' nor `while'. 14115 14116 // The body should be a null statement. 14117 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14118 if (!NBody) 14119 return; 14120 14121 // Skip expensive checks if diagnostic is disabled. 14122 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14123 return; 14124 14125 // Do the usual checks. 14126 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14127 return; 14128 14129 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14130 // noise level low, emit diagnostics only if for/while is followed by a 14131 // CompoundStmt, e.g.: 14132 // for (int i = 0; i < n; i++); 14133 // { 14134 // a(i); 14135 // } 14136 // or if for/while is followed by a statement with more indentation 14137 // than for/while itself: 14138 // for (int i = 0; i < n; i++); 14139 // a(i); 14140 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14141 if (!ProbableTypo) { 14142 bool BodyColInvalid; 14143 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14144 PossibleBody->getBeginLoc(), &BodyColInvalid); 14145 if (BodyColInvalid) 14146 return; 14147 14148 bool StmtColInvalid; 14149 unsigned StmtCol = 14150 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14151 if (StmtColInvalid) 14152 return; 14153 14154 if (BodyCol > StmtCol) 14155 ProbableTypo = true; 14156 } 14157 14158 if (ProbableTypo) { 14159 Diag(NBody->getSemiLoc(), DiagID); 14160 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14161 } 14162 } 14163 14164 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14165 14166 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14167 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14168 SourceLocation OpLoc) { 14169 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14170 return; 14171 14172 if (inTemplateInstantiation()) 14173 return; 14174 14175 // Strip parens and casts away. 14176 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14177 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14178 14179 // Check for a call expression 14180 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14181 if (!CE || CE->getNumArgs() != 1) 14182 return; 14183 14184 // Check for a call to std::move 14185 if (!CE->isCallToStdMove()) 14186 return; 14187 14188 // Get argument from std::move 14189 RHSExpr = CE->getArg(0); 14190 14191 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14192 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14193 14194 // Two DeclRefExpr's, check that the decls are the same. 14195 if (LHSDeclRef && RHSDeclRef) { 14196 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14197 return; 14198 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14199 RHSDeclRef->getDecl()->getCanonicalDecl()) 14200 return; 14201 14202 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14203 << LHSExpr->getSourceRange() 14204 << RHSExpr->getSourceRange(); 14205 return; 14206 } 14207 14208 // Member variables require a different approach to check for self moves. 14209 // MemberExpr's are the same if every nested MemberExpr refers to the same 14210 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14211 // the base Expr's are CXXThisExpr's. 14212 const Expr *LHSBase = LHSExpr; 14213 const Expr *RHSBase = RHSExpr; 14214 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14215 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14216 if (!LHSME || !RHSME) 14217 return; 14218 14219 while (LHSME && RHSME) { 14220 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14221 RHSME->getMemberDecl()->getCanonicalDecl()) 14222 return; 14223 14224 LHSBase = LHSME->getBase(); 14225 RHSBase = RHSME->getBase(); 14226 LHSME = dyn_cast<MemberExpr>(LHSBase); 14227 RHSME = dyn_cast<MemberExpr>(RHSBase); 14228 } 14229 14230 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14231 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14232 if (LHSDeclRef && RHSDeclRef) { 14233 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14234 return; 14235 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14236 RHSDeclRef->getDecl()->getCanonicalDecl()) 14237 return; 14238 14239 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14240 << LHSExpr->getSourceRange() 14241 << RHSExpr->getSourceRange(); 14242 return; 14243 } 14244 14245 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14246 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14247 << LHSExpr->getSourceRange() 14248 << RHSExpr->getSourceRange(); 14249 } 14250 14251 //===--- Layout compatibility ----------------------------------------------// 14252 14253 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14254 14255 /// Check if two enumeration types are layout-compatible. 14256 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14257 // C++11 [dcl.enum] p8: 14258 // Two enumeration types are layout-compatible if they have the same 14259 // underlying type. 14260 return ED1->isComplete() && ED2->isComplete() && 14261 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14262 } 14263 14264 /// Check if two fields are layout-compatible. 14265 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14266 FieldDecl *Field2) { 14267 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14268 return false; 14269 14270 if (Field1->isBitField() != Field2->isBitField()) 14271 return false; 14272 14273 if (Field1->isBitField()) { 14274 // Make sure that the bit-fields are the same length. 14275 unsigned Bits1 = Field1->getBitWidthValue(C); 14276 unsigned Bits2 = Field2->getBitWidthValue(C); 14277 14278 if (Bits1 != Bits2) 14279 return false; 14280 } 14281 14282 return true; 14283 } 14284 14285 /// Check if two standard-layout structs are layout-compatible. 14286 /// (C++11 [class.mem] p17) 14287 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14288 RecordDecl *RD2) { 14289 // If both records are C++ classes, check that base classes match. 14290 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14291 // If one of records is a CXXRecordDecl we are in C++ mode, 14292 // thus the other one is a CXXRecordDecl, too. 14293 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14294 // Check number of base classes. 14295 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14296 return false; 14297 14298 // Check the base classes. 14299 for (CXXRecordDecl::base_class_const_iterator 14300 Base1 = D1CXX->bases_begin(), 14301 BaseEnd1 = D1CXX->bases_end(), 14302 Base2 = D2CXX->bases_begin(); 14303 Base1 != BaseEnd1; 14304 ++Base1, ++Base2) { 14305 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14306 return false; 14307 } 14308 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14309 // If only RD2 is a C++ class, it should have zero base classes. 14310 if (D2CXX->getNumBases() > 0) 14311 return false; 14312 } 14313 14314 // Check the fields. 14315 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14316 Field2End = RD2->field_end(), 14317 Field1 = RD1->field_begin(), 14318 Field1End = RD1->field_end(); 14319 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14320 if (!isLayoutCompatible(C, *Field1, *Field2)) 14321 return false; 14322 } 14323 if (Field1 != Field1End || Field2 != Field2End) 14324 return false; 14325 14326 return true; 14327 } 14328 14329 /// Check if two standard-layout unions are layout-compatible. 14330 /// (C++11 [class.mem] p18) 14331 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14332 RecordDecl *RD2) { 14333 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14334 for (auto *Field2 : RD2->fields()) 14335 UnmatchedFields.insert(Field2); 14336 14337 for (auto *Field1 : RD1->fields()) { 14338 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14339 I = UnmatchedFields.begin(), 14340 E = UnmatchedFields.end(); 14341 14342 for ( ; I != E; ++I) { 14343 if (isLayoutCompatible(C, Field1, *I)) { 14344 bool Result = UnmatchedFields.erase(*I); 14345 (void) Result; 14346 assert(Result); 14347 break; 14348 } 14349 } 14350 if (I == E) 14351 return false; 14352 } 14353 14354 return UnmatchedFields.empty(); 14355 } 14356 14357 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14358 RecordDecl *RD2) { 14359 if (RD1->isUnion() != RD2->isUnion()) 14360 return false; 14361 14362 if (RD1->isUnion()) 14363 return isLayoutCompatibleUnion(C, RD1, RD2); 14364 else 14365 return isLayoutCompatibleStruct(C, RD1, RD2); 14366 } 14367 14368 /// Check if two types are layout-compatible in C++11 sense. 14369 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14370 if (T1.isNull() || T2.isNull()) 14371 return false; 14372 14373 // C++11 [basic.types] p11: 14374 // If two types T1 and T2 are the same type, then T1 and T2 are 14375 // layout-compatible types. 14376 if (C.hasSameType(T1, T2)) 14377 return true; 14378 14379 T1 = T1.getCanonicalType().getUnqualifiedType(); 14380 T2 = T2.getCanonicalType().getUnqualifiedType(); 14381 14382 const Type::TypeClass TC1 = T1->getTypeClass(); 14383 const Type::TypeClass TC2 = T2->getTypeClass(); 14384 14385 if (TC1 != TC2) 14386 return false; 14387 14388 if (TC1 == Type::Enum) { 14389 return isLayoutCompatible(C, 14390 cast<EnumType>(T1)->getDecl(), 14391 cast<EnumType>(T2)->getDecl()); 14392 } else if (TC1 == Type::Record) { 14393 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14394 return false; 14395 14396 return isLayoutCompatible(C, 14397 cast<RecordType>(T1)->getDecl(), 14398 cast<RecordType>(T2)->getDecl()); 14399 } 14400 14401 return false; 14402 } 14403 14404 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14405 14406 /// Given a type tag expression find the type tag itself. 14407 /// 14408 /// \param TypeExpr Type tag expression, as it appears in user's code. 14409 /// 14410 /// \param VD Declaration of an identifier that appears in a type tag. 14411 /// 14412 /// \param MagicValue Type tag magic value. 14413 /// 14414 /// \param isConstantEvaluated wether the evalaution should be performed in 14415 14416 /// constant context. 14417 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14418 const ValueDecl **VD, uint64_t *MagicValue, 14419 bool isConstantEvaluated) { 14420 while(true) { 14421 if (!TypeExpr) 14422 return false; 14423 14424 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14425 14426 switch (TypeExpr->getStmtClass()) { 14427 case Stmt::UnaryOperatorClass: { 14428 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14429 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14430 TypeExpr = UO->getSubExpr(); 14431 continue; 14432 } 14433 return false; 14434 } 14435 14436 case Stmt::DeclRefExprClass: { 14437 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14438 *VD = DRE->getDecl(); 14439 return true; 14440 } 14441 14442 case Stmt::IntegerLiteralClass: { 14443 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14444 llvm::APInt MagicValueAPInt = IL->getValue(); 14445 if (MagicValueAPInt.getActiveBits() <= 64) { 14446 *MagicValue = MagicValueAPInt.getZExtValue(); 14447 return true; 14448 } else 14449 return false; 14450 } 14451 14452 case Stmt::BinaryConditionalOperatorClass: 14453 case Stmt::ConditionalOperatorClass: { 14454 const AbstractConditionalOperator *ACO = 14455 cast<AbstractConditionalOperator>(TypeExpr); 14456 bool Result; 14457 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14458 isConstantEvaluated)) { 14459 if (Result) 14460 TypeExpr = ACO->getTrueExpr(); 14461 else 14462 TypeExpr = ACO->getFalseExpr(); 14463 continue; 14464 } 14465 return false; 14466 } 14467 14468 case Stmt::BinaryOperatorClass: { 14469 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14470 if (BO->getOpcode() == BO_Comma) { 14471 TypeExpr = BO->getRHS(); 14472 continue; 14473 } 14474 return false; 14475 } 14476 14477 default: 14478 return false; 14479 } 14480 } 14481 } 14482 14483 /// Retrieve the C type corresponding to type tag TypeExpr. 14484 /// 14485 /// \param TypeExpr Expression that specifies a type tag. 14486 /// 14487 /// \param MagicValues Registered magic values. 14488 /// 14489 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14490 /// kind. 14491 /// 14492 /// \param TypeInfo Information about the corresponding C type. 14493 /// 14494 /// \param isConstantEvaluated wether the evalaution should be performed in 14495 /// constant context. 14496 /// 14497 /// \returns true if the corresponding C type was found. 14498 static bool GetMatchingCType( 14499 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14500 const ASTContext &Ctx, 14501 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14502 *MagicValues, 14503 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14504 bool isConstantEvaluated) { 14505 FoundWrongKind = false; 14506 14507 // Variable declaration that has type_tag_for_datatype attribute. 14508 const ValueDecl *VD = nullptr; 14509 14510 uint64_t MagicValue; 14511 14512 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14513 return false; 14514 14515 if (VD) { 14516 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14517 if (I->getArgumentKind() != ArgumentKind) { 14518 FoundWrongKind = true; 14519 return false; 14520 } 14521 TypeInfo.Type = I->getMatchingCType(); 14522 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14523 TypeInfo.MustBeNull = I->getMustBeNull(); 14524 return true; 14525 } 14526 return false; 14527 } 14528 14529 if (!MagicValues) 14530 return false; 14531 14532 llvm::DenseMap<Sema::TypeTagMagicValue, 14533 Sema::TypeTagData>::const_iterator I = 14534 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14535 if (I == MagicValues->end()) 14536 return false; 14537 14538 TypeInfo = I->second; 14539 return true; 14540 } 14541 14542 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14543 uint64_t MagicValue, QualType Type, 14544 bool LayoutCompatible, 14545 bool MustBeNull) { 14546 if (!TypeTagForDatatypeMagicValues) 14547 TypeTagForDatatypeMagicValues.reset( 14548 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14549 14550 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14551 (*TypeTagForDatatypeMagicValues)[Magic] = 14552 TypeTagData(Type, LayoutCompatible, MustBeNull); 14553 } 14554 14555 static bool IsSameCharType(QualType T1, QualType T2) { 14556 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14557 if (!BT1) 14558 return false; 14559 14560 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14561 if (!BT2) 14562 return false; 14563 14564 BuiltinType::Kind T1Kind = BT1->getKind(); 14565 BuiltinType::Kind T2Kind = BT2->getKind(); 14566 14567 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14568 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14569 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14570 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14571 } 14572 14573 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14574 const ArrayRef<const Expr *> ExprArgs, 14575 SourceLocation CallSiteLoc) { 14576 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14577 bool IsPointerAttr = Attr->getIsPointer(); 14578 14579 // Retrieve the argument representing the 'type_tag'. 14580 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14581 if (TypeTagIdxAST >= ExprArgs.size()) { 14582 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14583 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14584 return; 14585 } 14586 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14587 bool FoundWrongKind; 14588 TypeTagData TypeInfo; 14589 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14590 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14591 TypeInfo, isConstantEvaluated())) { 14592 if (FoundWrongKind) 14593 Diag(TypeTagExpr->getExprLoc(), 14594 diag::warn_type_tag_for_datatype_wrong_kind) 14595 << TypeTagExpr->getSourceRange(); 14596 return; 14597 } 14598 14599 // Retrieve the argument representing the 'arg_idx'. 14600 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14601 if (ArgumentIdxAST >= ExprArgs.size()) { 14602 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14603 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14604 return; 14605 } 14606 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14607 if (IsPointerAttr) { 14608 // Skip implicit cast of pointer to `void *' (as a function argument). 14609 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14610 if (ICE->getType()->isVoidPointerType() && 14611 ICE->getCastKind() == CK_BitCast) 14612 ArgumentExpr = ICE->getSubExpr(); 14613 } 14614 QualType ArgumentType = ArgumentExpr->getType(); 14615 14616 // Passing a `void*' pointer shouldn't trigger a warning. 14617 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14618 return; 14619 14620 if (TypeInfo.MustBeNull) { 14621 // Type tag with matching void type requires a null pointer. 14622 if (!ArgumentExpr->isNullPointerConstant(Context, 14623 Expr::NPC_ValueDependentIsNotNull)) { 14624 Diag(ArgumentExpr->getExprLoc(), 14625 diag::warn_type_safety_null_pointer_required) 14626 << ArgumentKind->getName() 14627 << ArgumentExpr->getSourceRange() 14628 << TypeTagExpr->getSourceRange(); 14629 } 14630 return; 14631 } 14632 14633 QualType RequiredType = TypeInfo.Type; 14634 if (IsPointerAttr) 14635 RequiredType = Context.getPointerType(RequiredType); 14636 14637 bool mismatch = false; 14638 if (!TypeInfo.LayoutCompatible) { 14639 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14640 14641 // C++11 [basic.fundamental] p1: 14642 // Plain char, signed char, and unsigned char are three distinct types. 14643 // 14644 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14645 // char' depending on the current char signedness mode. 14646 if (mismatch) 14647 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14648 RequiredType->getPointeeType())) || 14649 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14650 mismatch = false; 14651 } else 14652 if (IsPointerAttr) 14653 mismatch = !isLayoutCompatible(Context, 14654 ArgumentType->getPointeeType(), 14655 RequiredType->getPointeeType()); 14656 else 14657 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14658 14659 if (mismatch) 14660 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14661 << ArgumentType << ArgumentKind 14662 << TypeInfo.LayoutCompatible << RequiredType 14663 << ArgumentExpr->getSourceRange() 14664 << TypeTagExpr->getSourceRange(); 14665 } 14666 14667 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14668 CharUnits Alignment) { 14669 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14670 } 14671 14672 void Sema::DiagnoseMisalignedMembers() { 14673 for (MisalignedMember &m : MisalignedMembers) { 14674 const NamedDecl *ND = m.RD; 14675 if (ND->getName().empty()) { 14676 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14677 ND = TD; 14678 } 14679 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14680 << m.MD << ND << m.E->getSourceRange(); 14681 } 14682 MisalignedMembers.clear(); 14683 } 14684 14685 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14686 E = E->IgnoreParens(); 14687 if (!T->isPointerType() && !T->isIntegerType()) 14688 return; 14689 if (isa<UnaryOperator>(E) && 14690 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14691 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14692 if (isa<MemberExpr>(Op)) { 14693 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14694 if (MA != MisalignedMembers.end() && 14695 (T->isIntegerType() || 14696 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14697 Context.getTypeAlignInChars( 14698 T->getPointeeType()) <= MA->Alignment)))) 14699 MisalignedMembers.erase(MA); 14700 } 14701 } 14702 } 14703 14704 void Sema::RefersToMemberWithReducedAlignment( 14705 Expr *E, 14706 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14707 Action) { 14708 const auto *ME = dyn_cast<MemberExpr>(E); 14709 if (!ME) 14710 return; 14711 14712 // No need to check expressions with an __unaligned-qualified type. 14713 if (E->getType().getQualifiers().hasUnaligned()) 14714 return; 14715 14716 // For a chain of MemberExpr like "a.b.c.d" this list 14717 // will keep FieldDecl's like [d, c, b]. 14718 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14719 const MemberExpr *TopME = nullptr; 14720 bool AnyIsPacked = false; 14721 do { 14722 QualType BaseType = ME->getBase()->getType(); 14723 if (BaseType->isDependentType()) 14724 return; 14725 if (ME->isArrow()) 14726 BaseType = BaseType->getPointeeType(); 14727 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14728 if (RD->isInvalidDecl()) 14729 return; 14730 14731 ValueDecl *MD = ME->getMemberDecl(); 14732 auto *FD = dyn_cast<FieldDecl>(MD); 14733 // We do not care about non-data members. 14734 if (!FD || FD->isInvalidDecl()) 14735 return; 14736 14737 AnyIsPacked = 14738 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14739 ReverseMemberChain.push_back(FD); 14740 14741 TopME = ME; 14742 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14743 } while (ME); 14744 assert(TopME && "We did not compute a topmost MemberExpr!"); 14745 14746 // Not the scope of this diagnostic. 14747 if (!AnyIsPacked) 14748 return; 14749 14750 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14751 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14752 // TODO: The innermost base of the member expression may be too complicated. 14753 // For now, just disregard these cases. This is left for future 14754 // improvement. 14755 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14756 return; 14757 14758 // Alignment expected by the whole expression. 14759 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14760 14761 // No need to do anything else with this case. 14762 if (ExpectedAlignment.isOne()) 14763 return; 14764 14765 // Synthesize offset of the whole access. 14766 CharUnits Offset; 14767 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14768 I++) { 14769 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14770 } 14771 14772 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14773 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14774 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14775 14776 // The base expression of the innermost MemberExpr may give 14777 // stronger guarantees than the class containing the member. 14778 if (DRE && !TopME->isArrow()) { 14779 const ValueDecl *VD = DRE->getDecl(); 14780 if (!VD->getType()->isReferenceType()) 14781 CompleteObjectAlignment = 14782 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14783 } 14784 14785 // Check if the synthesized offset fulfills the alignment. 14786 if (Offset % ExpectedAlignment != 0 || 14787 // It may fulfill the offset it but the effective alignment may still be 14788 // lower than the expected expression alignment. 14789 CompleteObjectAlignment < ExpectedAlignment) { 14790 // If this happens, we want to determine a sensible culprit of this. 14791 // Intuitively, watching the chain of member expressions from right to 14792 // left, we start with the required alignment (as required by the field 14793 // type) but some packed attribute in that chain has reduced the alignment. 14794 // It may happen that another packed structure increases it again. But if 14795 // we are here such increase has not been enough. So pointing the first 14796 // FieldDecl that either is packed or else its RecordDecl is, 14797 // seems reasonable. 14798 FieldDecl *FD = nullptr; 14799 CharUnits Alignment; 14800 for (FieldDecl *FDI : ReverseMemberChain) { 14801 if (FDI->hasAttr<PackedAttr>() || 14802 FDI->getParent()->hasAttr<PackedAttr>()) { 14803 FD = FDI; 14804 Alignment = std::min( 14805 Context.getTypeAlignInChars(FD->getType()), 14806 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14807 break; 14808 } 14809 } 14810 assert(FD && "We did not find a packed FieldDecl!"); 14811 Action(E, FD->getParent(), FD, Alignment); 14812 } 14813 } 14814 14815 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14816 using namespace std::placeholders; 14817 14818 RefersToMemberWithReducedAlignment( 14819 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14820 _2, _3, _4)); 14821 } 14822