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()->getAs<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()->getAs<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(), diag::err_typecheck_call_too_few_args); 633 return true; 634 } 635 636 Expr *Arg0 = TheCall->getArg(0); 637 Expr *Arg1 = TheCall->getArg(1); 638 Expr *Arg2 = TheCall->getArg(2); 639 Expr *Arg3 = TheCall->getArg(3); 640 641 // First argument always needs to be a queue_t type. 642 if (!Arg0->getType()->isQueueT()) { 643 S.Diag(TheCall->getArg(0)->getBeginLoc(), 644 diag::err_opencl_builtin_expected_type) 645 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 646 return true; 647 } 648 649 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 650 if (!Arg1->getType()->isIntegerType()) { 651 S.Diag(TheCall->getArg(1)->getBeginLoc(), 652 diag::err_opencl_builtin_expected_type) 653 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 654 return true; 655 } 656 657 // Third argument is always an ndrange_t type. 658 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 659 S.Diag(TheCall->getArg(2)->getBeginLoc(), 660 diag::err_opencl_builtin_expected_type) 661 << TheCall->getDirectCallee() << "'ndrange_t'"; 662 return true; 663 } 664 665 // With four arguments, there is only one form that the function could be 666 // called in: no events and no variable arguments. 667 if (NumArgs == 4) { 668 // check that the last argument is the right block type. 669 if (!isBlockPointer(Arg3)) { 670 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 671 << TheCall->getDirectCallee() << "block"; 672 return true; 673 } 674 // we have a block type, check the prototype 675 const BlockPointerType *BPT = 676 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 677 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) { 678 S.Diag(Arg3->getBeginLoc(), 679 diag::err_opencl_enqueue_kernel_blocks_no_args); 680 return true; 681 } 682 return false; 683 } 684 // we can have block + varargs. 685 if (isBlockPointer(Arg3)) 686 return (checkOpenCLBlockArgs(S, Arg3) || 687 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 688 // last two cases with either exactly 7 args or 7 args and varargs. 689 if (NumArgs >= 7) { 690 // check common block argument. 691 Expr *Arg6 = TheCall->getArg(6); 692 if (!isBlockPointer(Arg6)) { 693 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 694 << TheCall->getDirectCallee() << "block"; 695 return true; 696 } 697 if (checkOpenCLBlockArgs(S, Arg6)) 698 return true; 699 700 // Forth argument has to be any integer type. 701 if (!Arg3->getType()->isIntegerType()) { 702 S.Diag(TheCall->getArg(3)->getBeginLoc(), 703 diag::err_opencl_builtin_expected_type) 704 << TheCall->getDirectCallee() << "integer"; 705 return true; 706 } 707 // check remaining common arguments. 708 Expr *Arg4 = TheCall->getArg(4); 709 Expr *Arg5 = TheCall->getArg(5); 710 711 // Fifth argument is always passed as a pointer to clk_event_t. 712 if (!Arg4->isNullPointerConstant(S.Context, 713 Expr::NPC_ValueDependentIsNotNull) && 714 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 715 S.Diag(TheCall->getArg(4)->getBeginLoc(), 716 diag::err_opencl_builtin_expected_type) 717 << TheCall->getDirectCallee() 718 << S.Context.getPointerType(S.Context.OCLClkEventTy); 719 return true; 720 } 721 722 // Sixth argument is always passed as a pointer to clk_event_t. 723 if (!Arg5->isNullPointerConstant(S.Context, 724 Expr::NPC_ValueDependentIsNotNull) && 725 !(Arg5->getType()->isPointerType() && 726 Arg5->getType()->getPointeeType()->isClkEventT())) { 727 S.Diag(TheCall->getArg(5)->getBeginLoc(), 728 diag::err_opencl_builtin_expected_type) 729 << TheCall->getDirectCallee() 730 << S.Context.getPointerType(S.Context.OCLClkEventTy); 731 return true; 732 } 733 734 if (NumArgs == 7) 735 return false; 736 737 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 738 } 739 740 // None of the specific case has been detected, give generic error 741 S.Diag(TheCall->getBeginLoc(), 742 diag::err_opencl_enqueue_kernel_incorrect_args); 743 return true; 744 } 745 746 /// Returns OpenCL access qual. 747 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 748 return D->getAttr<OpenCLAccessAttr>(); 749 } 750 751 /// Returns true if pipe element type is different from the pointer. 752 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 753 const Expr *Arg0 = Call->getArg(0); 754 // First argument type should always be pipe. 755 if (!Arg0->getType()->isPipeType()) { 756 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 757 << Call->getDirectCallee() << Arg0->getSourceRange(); 758 return true; 759 } 760 OpenCLAccessAttr *AccessQual = 761 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 762 // Validates the access qualifier is compatible with the call. 763 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 764 // read_only and write_only, and assumed to be read_only if no qualifier is 765 // specified. 766 switch (Call->getDirectCallee()->getBuiltinID()) { 767 case Builtin::BIread_pipe: 768 case Builtin::BIreserve_read_pipe: 769 case Builtin::BIcommit_read_pipe: 770 case Builtin::BIwork_group_reserve_read_pipe: 771 case Builtin::BIsub_group_reserve_read_pipe: 772 case Builtin::BIwork_group_commit_read_pipe: 773 case Builtin::BIsub_group_commit_read_pipe: 774 if (!(!AccessQual || AccessQual->isReadOnly())) { 775 S.Diag(Arg0->getBeginLoc(), 776 diag::err_opencl_builtin_pipe_invalid_access_modifier) 777 << "read_only" << Arg0->getSourceRange(); 778 return true; 779 } 780 break; 781 case Builtin::BIwrite_pipe: 782 case Builtin::BIreserve_write_pipe: 783 case Builtin::BIcommit_write_pipe: 784 case Builtin::BIwork_group_reserve_write_pipe: 785 case Builtin::BIsub_group_reserve_write_pipe: 786 case Builtin::BIwork_group_commit_write_pipe: 787 case Builtin::BIsub_group_commit_write_pipe: 788 if (!(AccessQual && AccessQual->isWriteOnly())) { 789 S.Diag(Arg0->getBeginLoc(), 790 diag::err_opencl_builtin_pipe_invalid_access_modifier) 791 << "write_only" << Arg0->getSourceRange(); 792 return true; 793 } 794 break; 795 default: 796 break; 797 } 798 return false; 799 } 800 801 /// Returns true if pipe element type is different from the pointer. 802 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 803 const Expr *Arg0 = Call->getArg(0); 804 const Expr *ArgIdx = Call->getArg(Idx); 805 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 806 const QualType EltTy = PipeTy->getElementType(); 807 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 808 // The Idx argument should be a pointer and the type of the pointer and 809 // the type of pipe element should also be the same. 810 if (!ArgTy || 811 !S.Context.hasSameType( 812 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 813 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 814 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 815 << ArgIdx->getType() << ArgIdx->getSourceRange(); 816 return true; 817 } 818 return false; 819 } 820 821 // Performs semantic analysis for the read/write_pipe call. 822 // \param S Reference to the semantic analyzer. 823 // \param Call A pointer to the builtin call. 824 // \return True if a semantic error has been found, false otherwise. 825 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 826 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 827 // functions have two forms. 828 switch (Call->getNumArgs()) { 829 case 2: 830 if (checkOpenCLPipeArg(S, Call)) 831 return true; 832 // The call with 2 arguments should be 833 // read/write_pipe(pipe T, T*). 834 // Check packet type T. 835 if (checkOpenCLPipePacketType(S, Call, 1)) 836 return true; 837 break; 838 839 case 4: { 840 if (checkOpenCLPipeArg(S, Call)) 841 return true; 842 // The call with 4 arguments should be 843 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 844 // Check reserve_id_t. 845 if (!Call->getArg(1)->getType()->isReserveIDT()) { 846 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 847 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 848 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 849 return true; 850 } 851 852 // Check the index. 853 const Expr *Arg2 = Call->getArg(2); 854 if (!Arg2->getType()->isIntegerType() && 855 !Arg2->getType()->isUnsignedIntegerType()) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 857 << Call->getDirectCallee() << S.Context.UnsignedIntTy 858 << Arg2->getType() << Arg2->getSourceRange(); 859 return true; 860 } 861 862 // Check packet type T. 863 if (checkOpenCLPipePacketType(S, Call, 3)) 864 return true; 865 } break; 866 default: 867 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 868 << Call->getDirectCallee() << Call->getSourceRange(); 869 return true; 870 } 871 872 return false; 873 } 874 875 // Performs a semantic analysis on the {work_group_/sub_group_ 876 // /_}reserve_{read/write}_pipe 877 // \param S Reference to the semantic analyzer. 878 // \param Call The call to the builtin function to be analyzed. 879 // \return True if a semantic error was found, false otherwise. 880 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 881 if (checkArgCount(S, Call, 2)) 882 return true; 883 884 if (checkOpenCLPipeArg(S, Call)) 885 return true; 886 887 // Check the reserve size. 888 if (!Call->getArg(1)->getType()->isIntegerType() && 889 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 890 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 891 << Call->getDirectCallee() << S.Context.UnsignedIntTy 892 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 893 return true; 894 } 895 896 // Since return type of reserve_read/write_pipe built-in function is 897 // reserve_id_t, which is not defined in the builtin def file , we used int 898 // as return type and need to override the return type of these functions. 899 Call->setType(S.Context.OCLReserveIDTy); 900 901 return false; 902 } 903 904 // Performs a semantic analysis on {work_group_/sub_group_ 905 // /_}commit_{read/write}_pipe 906 // \param S Reference to the semantic analyzer. 907 // \param Call The call to the builtin function to be analyzed. 908 // \return True if a semantic error was found, false otherwise. 909 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 910 if (checkArgCount(S, Call, 2)) 911 return true; 912 913 if (checkOpenCLPipeArg(S, Call)) 914 return true; 915 916 // Check reserve_id_t. 917 if (!Call->getArg(1)->getType()->isReserveIDT()) { 918 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 919 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 920 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 921 return true; 922 } 923 924 return false; 925 } 926 927 // Performs a semantic analysis on the call to built-in Pipe 928 // Query Functions. 929 // \param S Reference to the semantic analyzer. 930 // \param Call The call to the builtin function to be analyzed. 931 // \return True if a semantic error was found, false otherwise. 932 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 933 if (checkArgCount(S, Call, 1)) 934 return true; 935 936 if (!Call->getArg(0)->getType()->isPipeType()) { 937 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 938 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 939 return true; 940 } 941 942 return false; 943 } 944 945 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 946 // Performs semantic analysis for the to_global/local/private call. 947 // \param S Reference to the semantic analyzer. 948 // \param BuiltinID ID of the builtin function. 949 // \param Call A pointer to the builtin call. 950 // \return True if a semantic error has been found, false otherwise. 951 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 952 CallExpr *Call) { 953 if (Call->getNumArgs() != 1) { 954 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 955 << Call->getDirectCallee() << Call->getSourceRange(); 956 return true; 957 } 958 959 auto RT = Call->getArg(0)->getType(); 960 if (!RT->isPointerType() || RT->getPointeeType() 961 .getAddressSpace() == LangAS::opencl_constant) { 962 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 963 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 964 return true; 965 } 966 967 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 968 S.Diag(Call->getArg(0)->getBeginLoc(), 969 diag::warn_opencl_generic_address_space_arg) 970 << Call->getDirectCallee()->getNameInfo().getAsString() 971 << Call->getArg(0)->getSourceRange(); 972 } 973 974 RT = RT->getPointeeType(); 975 auto Qual = RT.getQualifiers(); 976 switch (BuiltinID) { 977 case Builtin::BIto_global: 978 Qual.setAddressSpace(LangAS::opencl_global); 979 break; 980 case Builtin::BIto_local: 981 Qual.setAddressSpace(LangAS::opencl_local); 982 break; 983 case Builtin::BIto_private: 984 Qual.setAddressSpace(LangAS::opencl_private); 985 break; 986 default: 987 llvm_unreachable("Invalid builtin function"); 988 } 989 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 990 RT.getUnqualifiedType(), Qual))); 991 992 return false; 993 } 994 995 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 996 if (checkArgCount(S, TheCall, 1)) 997 return ExprError(); 998 999 // Compute __builtin_launder's parameter type from the argument. 1000 // The parameter type is: 1001 // * The type of the argument if it's not an array or function type, 1002 // Otherwise, 1003 // * The decayed argument type. 1004 QualType ParamTy = [&]() { 1005 QualType ArgTy = TheCall->getArg(0)->getType(); 1006 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1007 return S.Context.getPointerType(Ty->getElementType()); 1008 if (ArgTy->isFunctionType()) { 1009 return S.Context.getPointerType(ArgTy); 1010 } 1011 return ArgTy; 1012 }(); 1013 1014 TheCall->setType(ParamTy); 1015 1016 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1017 if (!ParamTy->isPointerType()) 1018 return 0; 1019 if (ParamTy->isFunctionPointerType()) 1020 return 1; 1021 if (ParamTy->isVoidPointerType()) 1022 return 2; 1023 return llvm::Optional<unsigned>{}; 1024 }(); 1025 if (DiagSelect.hasValue()) { 1026 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1027 << DiagSelect.getValue() << TheCall->getSourceRange(); 1028 return ExprError(); 1029 } 1030 1031 // We either have an incomplete class type, or we have a class template 1032 // whose instantiation has not been forced. Example: 1033 // 1034 // template <class T> struct Foo { T value; }; 1035 // Foo<int> *p = nullptr; 1036 // auto *d = __builtin_launder(p); 1037 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1038 diag::err_incomplete_type)) 1039 return ExprError(); 1040 1041 assert(ParamTy->getPointeeType()->isObjectType() && 1042 "Unhandled non-object pointer case"); 1043 1044 InitializedEntity Entity = 1045 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1046 ExprResult Arg = 1047 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1048 if (Arg.isInvalid()) 1049 return ExprError(); 1050 TheCall->setArg(0, Arg.get()); 1051 1052 return TheCall; 1053 } 1054 1055 // Emit an error and return true if the current architecture is not in the list 1056 // of supported architectures. 1057 static bool 1058 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1059 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1060 llvm::Triple::ArchType CurArch = 1061 S.getASTContext().getTargetInfo().getTriple().getArch(); 1062 if (llvm::is_contained(SupportedArchs, CurArch)) 1063 return false; 1064 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1065 << TheCall->getSourceRange(); 1066 return true; 1067 } 1068 1069 ExprResult 1070 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1071 CallExpr *TheCall) { 1072 ExprResult TheCallResult(TheCall); 1073 1074 // Find out if any arguments are required to be integer constant expressions. 1075 unsigned ICEArguments = 0; 1076 ASTContext::GetBuiltinTypeError Error; 1077 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1078 if (Error != ASTContext::GE_None) 1079 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1080 1081 // If any arguments are required to be ICE's, check and diagnose. 1082 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1083 // Skip arguments not required to be ICE's. 1084 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1085 1086 llvm::APSInt Result; 1087 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1088 return true; 1089 ICEArguments &= ~(1 << ArgNo); 1090 } 1091 1092 switch (BuiltinID) { 1093 case Builtin::BI__builtin___CFStringMakeConstantString: 1094 assert(TheCall->getNumArgs() == 1 && 1095 "Wrong # arguments to builtin CFStringMakeConstantString"); 1096 if (CheckObjCString(TheCall->getArg(0))) 1097 return ExprError(); 1098 break; 1099 case Builtin::BI__builtin_ms_va_start: 1100 case Builtin::BI__builtin_stdarg_start: 1101 case Builtin::BI__builtin_va_start: 1102 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1103 return ExprError(); 1104 break; 1105 case Builtin::BI__va_start: { 1106 switch (Context.getTargetInfo().getTriple().getArch()) { 1107 case llvm::Triple::aarch64: 1108 case llvm::Triple::arm: 1109 case llvm::Triple::thumb: 1110 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1111 return ExprError(); 1112 break; 1113 default: 1114 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1115 return ExprError(); 1116 break; 1117 } 1118 break; 1119 } 1120 1121 // The acquire, release, and no fence variants are ARM and AArch64 only. 1122 case Builtin::BI_interlockedbittestandset_acq: 1123 case Builtin::BI_interlockedbittestandset_rel: 1124 case Builtin::BI_interlockedbittestandset_nf: 1125 case Builtin::BI_interlockedbittestandreset_acq: 1126 case Builtin::BI_interlockedbittestandreset_rel: 1127 case Builtin::BI_interlockedbittestandreset_nf: 1128 if (CheckBuiltinTargetSupport( 1129 *this, BuiltinID, TheCall, 1130 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1131 return ExprError(); 1132 break; 1133 1134 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1135 case Builtin::BI_bittest64: 1136 case Builtin::BI_bittestandcomplement64: 1137 case Builtin::BI_bittestandreset64: 1138 case Builtin::BI_bittestandset64: 1139 case Builtin::BI_interlockedbittestandreset64: 1140 case Builtin::BI_interlockedbittestandset64: 1141 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1142 {llvm::Triple::x86_64, llvm::Triple::arm, 1143 llvm::Triple::thumb, llvm::Triple::aarch64})) 1144 return ExprError(); 1145 break; 1146 1147 case Builtin::BI__builtin_isgreater: 1148 case Builtin::BI__builtin_isgreaterequal: 1149 case Builtin::BI__builtin_isless: 1150 case Builtin::BI__builtin_islessequal: 1151 case Builtin::BI__builtin_islessgreater: 1152 case Builtin::BI__builtin_isunordered: 1153 if (SemaBuiltinUnorderedCompare(TheCall)) 1154 return ExprError(); 1155 break; 1156 case Builtin::BI__builtin_fpclassify: 1157 if (SemaBuiltinFPClassification(TheCall, 6)) 1158 return ExprError(); 1159 break; 1160 case Builtin::BI__builtin_isfinite: 1161 case Builtin::BI__builtin_isinf: 1162 case Builtin::BI__builtin_isinf_sign: 1163 case Builtin::BI__builtin_isnan: 1164 case Builtin::BI__builtin_isnormal: 1165 case Builtin::BI__builtin_signbit: 1166 case Builtin::BI__builtin_signbitf: 1167 case Builtin::BI__builtin_signbitl: 1168 if (SemaBuiltinFPClassification(TheCall, 1)) 1169 return ExprError(); 1170 break; 1171 case Builtin::BI__builtin_shufflevector: 1172 return SemaBuiltinShuffleVector(TheCall); 1173 // TheCall will be freed by the smart pointer here, but that's fine, since 1174 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1175 case Builtin::BI__builtin_prefetch: 1176 if (SemaBuiltinPrefetch(TheCall)) 1177 return ExprError(); 1178 break; 1179 case Builtin::BI__builtin_alloca_with_align: 1180 if (SemaBuiltinAllocaWithAlign(TheCall)) 1181 return ExprError(); 1182 break; 1183 case Builtin::BI__assume: 1184 case Builtin::BI__builtin_assume: 1185 if (SemaBuiltinAssume(TheCall)) 1186 return ExprError(); 1187 break; 1188 case Builtin::BI__builtin_assume_aligned: 1189 if (SemaBuiltinAssumeAligned(TheCall)) 1190 return ExprError(); 1191 break; 1192 case Builtin::BI__builtin_dynamic_object_size: 1193 case Builtin::BI__builtin_object_size: 1194 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1195 return ExprError(); 1196 break; 1197 case Builtin::BI__builtin_longjmp: 1198 if (SemaBuiltinLongjmp(TheCall)) 1199 return ExprError(); 1200 break; 1201 case Builtin::BI__builtin_setjmp: 1202 if (SemaBuiltinSetjmp(TheCall)) 1203 return ExprError(); 1204 break; 1205 case Builtin::BI_setjmp: 1206 case Builtin::BI_setjmpex: 1207 if (checkArgCount(*this, TheCall, 1)) 1208 return true; 1209 break; 1210 case Builtin::BI__builtin_classify_type: 1211 if (checkArgCount(*this, TheCall, 1)) return true; 1212 TheCall->setType(Context.IntTy); 1213 break; 1214 case Builtin::BI__builtin_constant_p: { 1215 if (checkArgCount(*this, TheCall, 1)) return true; 1216 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1217 if (Arg.isInvalid()) return true; 1218 TheCall->setArg(0, Arg.get()); 1219 TheCall->setType(Context.IntTy); 1220 break; 1221 } 1222 case Builtin::BI__builtin_launder: 1223 return SemaBuiltinLaunder(*this, TheCall); 1224 case Builtin::BI__sync_fetch_and_add: 1225 case Builtin::BI__sync_fetch_and_add_1: 1226 case Builtin::BI__sync_fetch_and_add_2: 1227 case Builtin::BI__sync_fetch_and_add_4: 1228 case Builtin::BI__sync_fetch_and_add_8: 1229 case Builtin::BI__sync_fetch_and_add_16: 1230 case Builtin::BI__sync_fetch_and_sub: 1231 case Builtin::BI__sync_fetch_and_sub_1: 1232 case Builtin::BI__sync_fetch_and_sub_2: 1233 case Builtin::BI__sync_fetch_and_sub_4: 1234 case Builtin::BI__sync_fetch_and_sub_8: 1235 case Builtin::BI__sync_fetch_and_sub_16: 1236 case Builtin::BI__sync_fetch_and_or: 1237 case Builtin::BI__sync_fetch_and_or_1: 1238 case Builtin::BI__sync_fetch_and_or_2: 1239 case Builtin::BI__sync_fetch_and_or_4: 1240 case Builtin::BI__sync_fetch_and_or_8: 1241 case Builtin::BI__sync_fetch_and_or_16: 1242 case Builtin::BI__sync_fetch_and_and: 1243 case Builtin::BI__sync_fetch_and_and_1: 1244 case Builtin::BI__sync_fetch_and_and_2: 1245 case Builtin::BI__sync_fetch_and_and_4: 1246 case Builtin::BI__sync_fetch_and_and_8: 1247 case Builtin::BI__sync_fetch_and_and_16: 1248 case Builtin::BI__sync_fetch_and_xor: 1249 case Builtin::BI__sync_fetch_and_xor_1: 1250 case Builtin::BI__sync_fetch_and_xor_2: 1251 case Builtin::BI__sync_fetch_and_xor_4: 1252 case Builtin::BI__sync_fetch_and_xor_8: 1253 case Builtin::BI__sync_fetch_and_xor_16: 1254 case Builtin::BI__sync_fetch_and_nand: 1255 case Builtin::BI__sync_fetch_and_nand_1: 1256 case Builtin::BI__sync_fetch_and_nand_2: 1257 case Builtin::BI__sync_fetch_and_nand_4: 1258 case Builtin::BI__sync_fetch_and_nand_8: 1259 case Builtin::BI__sync_fetch_and_nand_16: 1260 case Builtin::BI__sync_add_and_fetch: 1261 case Builtin::BI__sync_add_and_fetch_1: 1262 case Builtin::BI__sync_add_and_fetch_2: 1263 case Builtin::BI__sync_add_and_fetch_4: 1264 case Builtin::BI__sync_add_and_fetch_8: 1265 case Builtin::BI__sync_add_and_fetch_16: 1266 case Builtin::BI__sync_sub_and_fetch: 1267 case Builtin::BI__sync_sub_and_fetch_1: 1268 case Builtin::BI__sync_sub_and_fetch_2: 1269 case Builtin::BI__sync_sub_and_fetch_4: 1270 case Builtin::BI__sync_sub_and_fetch_8: 1271 case Builtin::BI__sync_sub_and_fetch_16: 1272 case Builtin::BI__sync_and_and_fetch: 1273 case Builtin::BI__sync_and_and_fetch_1: 1274 case Builtin::BI__sync_and_and_fetch_2: 1275 case Builtin::BI__sync_and_and_fetch_4: 1276 case Builtin::BI__sync_and_and_fetch_8: 1277 case Builtin::BI__sync_and_and_fetch_16: 1278 case Builtin::BI__sync_or_and_fetch: 1279 case Builtin::BI__sync_or_and_fetch_1: 1280 case Builtin::BI__sync_or_and_fetch_2: 1281 case Builtin::BI__sync_or_and_fetch_4: 1282 case Builtin::BI__sync_or_and_fetch_8: 1283 case Builtin::BI__sync_or_and_fetch_16: 1284 case Builtin::BI__sync_xor_and_fetch: 1285 case Builtin::BI__sync_xor_and_fetch_1: 1286 case Builtin::BI__sync_xor_and_fetch_2: 1287 case Builtin::BI__sync_xor_and_fetch_4: 1288 case Builtin::BI__sync_xor_and_fetch_8: 1289 case Builtin::BI__sync_xor_and_fetch_16: 1290 case Builtin::BI__sync_nand_and_fetch: 1291 case Builtin::BI__sync_nand_and_fetch_1: 1292 case Builtin::BI__sync_nand_and_fetch_2: 1293 case Builtin::BI__sync_nand_and_fetch_4: 1294 case Builtin::BI__sync_nand_and_fetch_8: 1295 case Builtin::BI__sync_nand_and_fetch_16: 1296 case Builtin::BI__sync_val_compare_and_swap: 1297 case Builtin::BI__sync_val_compare_and_swap_1: 1298 case Builtin::BI__sync_val_compare_and_swap_2: 1299 case Builtin::BI__sync_val_compare_and_swap_4: 1300 case Builtin::BI__sync_val_compare_and_swap_8: 1301 case Builtin::BI__sync_val_compare_and_swap_16: 1302 case Builtin::BI__sync_bool_compare_and_swap: 1303 case Builtin::BI__sync_bool_compare_and_swap_1: 1304 case Builtin::BI__sync_bool_compare_and_swap_2: 1305 case Builtin::BI__sync_bool_compare_and_swap_4: 1306 case Builtin::BI__sync_bool_compare_and_swap_8: 1307 case Builtin::BI__sync_bool_compare_and_swap_16: 1308 case Builtin::BI__sync_lock_test_and_set: 1309 case Builtin::BI__sync_lock_test_and_set_1: 1310 case Builtin::BI__sync_lock_test_and_set_2: 1311 case Builtin::BI__sync_lock_test_and_set_4: 1312 case Builtin::BI__sync_lock_test_and_set_8: 1313 case Builtin::BI__sync_lock_test_and_set_16: 1314 case Builtin::BI__sync_lock_release: 1315 case Builtin::BI__sync_lock_release_1: 1316 case Builtin::BI__sync_lock_release_2: 1317 case Builtin::BI__sync_lock_release_4: 1318 case Builtin::BI__sync_lock_release_8: 1319 case Builtin::BI__sync_lock_release_16: 1320 case Builtin::BI__sync_swap: 1321 case Builtin::BI__sync_swap_1: 1322 case Builtin::BI__sync_swap_2: 1323 case Builtin::BI__sync_swap_4: 1324 case Builtin::BI__sync_swap_8: 1325 case Builtin::BI__sync_swap_16: 1326 return SemaBuiltinAtomicOverloaded(TheCallResult); 1327 case Builtin::BI__sync_synchronize: 1328 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1329 << TheCall->getCallee()->getSourceRange(); 1330 break; 1331 case Builtin::BI__builtin_nontemporal_load: 1332 case Builtin::BI__builtin_nontemporal_store: 1333 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1334 #define BUILTIN(ID, TYPE, ATTRS) 1335 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1336 case Builtin::BI##ID: \ 1337 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1338 #include "clang/Basic/Builtins.def" 1339 case Builtin::BI__annotation: 1340 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1341 return ExprError(); 1342 break; 1343 case Builtin::BI__builtin_annotation: 1344 if (SemaBuiltinAnnotation(*this, TheCall)) 1345 return ExprError(); 1346 break; 1347 case Builtin::BI__builtin_addressof: 1348 if (SemaBuiltinAddressof(*this, TheCall)) 1349 return ExprError(); 1350 break; 1351 case Builtin::BI__builtin_add_overflow: 1352 case Builtin::BI__builtin_sub_overflow: 1353 case Builtin::BI__builtin_mul_overflow: 1354 if (SemaBuiltinOverflow(*this, TheCall)) 1355 return ExprError(); 1356 break; 1357 case Builtin::BI__builtin_operator_new: 1358 case Builtin::BI__builtin_operator_delete: { 1359 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1360 ExprResult Res = 1361 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1362 if (Res.isInvalid()) 1363 CorrectDelayedTyposInExpr(TheCallResult.get()); 1364 return Res; 1365 } 1366 case Builtin::BI__builtin_dump_struct: { 1367 // We first want to ensure we are called with 2 arguments 1368 if (checkArgCount(*this, TheCall, 2)) 1369 return ExprError(); 1370 // Ensure that the first argument is of type 'struct XX *' 1371 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1372 const QualType PtrArgType = PtrArg->getType(); 1373 if (!PtrArgType->isPointerType() || 1374 !PtrArgType->getPointeeType()->isRecordType()) { 1375 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1376 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1377 << "structure pointer"; 1378 return ExprError(); 1379 } 1380 1381 // Ensure that the second argument is of type 'FunctionType' 1382 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1383 const QualType FnPtrArgType = FnPtrArg->getType(); 1384 if (!FnPtrArgType->isPointerType()) { 1385 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1386 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1387 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1388 return ExprError(); 1389 } 1390 1391 const auto *FuncType = 1392 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1393 1394 if (!FuncType) { 1395 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1396 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1397 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1398 return ExprError(); 1399 } 1400 1401 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1402 if (!FT->getNumParams()) { 1403 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1404 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1405 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1406 return ExprError(); 1407 } 1408 QualType PT = FT->getParamType(0); 1409 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1410 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1411 !PT->getPointeeType().isConstQualified()) { 1412 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1413 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1414 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1415 return ExprError(); 1416 } 1417 } 1418 1419 TheCall->setType(Context.IntTy); 1420 break; 1421 } 1422 case Builtin::BI__builtin_preserve_access_index: 1423 if (SemaBuiltinPreserveAI(*this, TheCall)) 1424 return ExprError(); 1425 break; 1426 case Builtin::BI__builtin_call_with_static_chain: 1427 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1428 return ExprError(); 1429 break; 1430 case Builtin::BI__exception_code: 1431 case Builtin::BI_exception_code: 1432 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1433 diag::err_seh___except_block)) 1434 return ExprError(); 1435 break; 1436 case Builtin::BI__exception_info: 1437 case Builtin::BI_exception_info: 1438 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1439 diag::err_seh___except_filter)) 1440 return ExprError(); 1441 break; 1442 case Builtin::BI__GetExceptionInfo: 1443 if (checkArgCount(*this, TheCall, 1)) 1444 return ExprError(); 1445 1446 if (CheckCXXThrowOperand( 1447 TheCall->getBeginLoc(), 1448 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1449 TheCall)) 1450 return ExprError(); 1451 1452 TheCall->setType(Context.VoidPtrTy); 1453 break; 1454 // OpenCL v2.0, s6.13.16 - Pipe functions 1455 case Builtin::BIread_pipe: 1456 case Builtin::BIwrite_pipe: 1457 // Since those two functions are declared with var args, we need a semantic 1458 // check for the argument. 1459 if (SemaBuiltinRWPipe(*this, TheCall)) 1460 return ExprError(); 1461 break; 1462 case Builtin::BIreserve_read_pipe: 1463 case Builtin::BIreserve_write_pipe: 1464 case Builtin::BIwork_group_reserve_read_pipe: 1465 case Builtin::BIwork_group_reserve_write_pipe: 1466 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1467 return ExprError(); 1468 break; 1469 case Builtin::BIsub_group_reserve_read_pipe: 1470 case Builtin::BIsub_group_reserve_write_pipe: 1471 if (checkOpenCLSubgroupExt(*this, TheCall) || 1472 SemaBuiltinReserveRWPipe(*this, TheCall)) 1473 return ExprError(); 1474 break; 1475 case Builtin::BIcommit_read_pipe: 1476 case Builtin::BIcommit_write_pipe: 1477 case Builtin::BIwork_group_commit_read_pipe: 1478 case Builtin::BIwork_group_commit_write_pipe: 1479 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1480 return ExprError(); 1481 break; 1482 case Builtin::BIsub_group_commit_read_pipe: 1483 case Builtin::BIsub_group_commit_write_pipe: 1484 if (checkOpenCLSubgroupExt(*this, TheCall) || 1485 SemaBuiltinCommitRWPipe(*this, TheCall)) 1486 return ExprError(); 1487 break; 1488 case Builtin::BIget_pipe_num_packets: 1489 case Builtin::BIget_pipe_max_packets: 1490 if (SemaBuiltinPipePackets(*this, TheCall)) 1491 return ExprError(); 1492 break; 1493 case Builtin::BIto_global: 1494 case Builtin::BIto_local: 1495 case Builtin::BIto_private: 1496 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1497 return ExprError(); 1498 break; 1499 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1500 case Builtin::BIenqueue_kernel: 1501 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1502 return ExprError(); 1503 break; 1504 case Builtin::BIget_kernel_work_group_size: 1505 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1506 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1507 return ExprError(); 1508 break; 1509 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1510 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1511 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1512 return ExprError(); 1513 break; 1514 case Builtin::BI__builtin_os_log_format: 1515 case Builtin::BI__builtin_os_log_format_buffer_size: 1516 if (SemaBuiltinOSLogFormat(TheCall)) 1517 return ExprError(); 1518 break; 1519 } 1520 1521 // Since the target specific builtins for each arch overlap, only check those 1522 // of the arch we are compiling for. 1523 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1524 switch (Context.getTargetInfo().getTriple().getArch()) { 1525 case llvm::Triple::arm: 1526 case llvm::Triple::armeb: 1527 case llvm::Triple::thumb: 1528 case llvm::Triple::thumbeb: 1529 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1530 return ExprError(); 1531 break; 1532 case llvm::Triple::aarch64: 1533 case llvm::Triple::aarch64_be: 1534 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1535 return ExprError(); 1536 break; 1537 case llvm::Triple::hexagon: 1538 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1539 return ExprError(); 1540 break; 1541 case llvm::Triple::mips: 1542 case llvm::Triple::mipsel: 1543 case llvm::Triple::mips64: 1544 case llvm::Triple::mips64el: 1545 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1546 return ExprError(); 1547 break; 1548 case llvm::Triple::systemz: 1549 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1550 return ExprError(); 1551 break; 1552 case llvm::Triple::x86: 1553 case llvm::Triple::x86_64: 1554 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1555 return ExprError(); 1556 break; 1557 case llvm::Triple::ppc: 1558 case llvm::Triple::ppc64: 1559 case llvm::Triple::ppc64le: 1560 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1561 return ExprError(); 1562 break; 1563 default: 1564 break; 1565 } 1566 } 1567 1568 return TheCallResult; 1569 } 1570 1571 // Get the valid immediate range for the specified NEON type code. 1572 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1573 NeonTypeFlags Type(t); 1574 int IsQuad = ForceQuad ? true : Type.isQuad(); 1575 switch (Type.getEltType()) { 1576 case NeonTypeFlags::Int8: 1577 case NeonTypeFlags::Poly8: 1578 return shift ? 7 : (8 << IsQuad) - 1; 1579 case NeonTypeFlags::Int16: 1580 case NeonTypeFlags::Poly16: 1581 return shift ? 15 : (4 << IsQuad) - 1; 1582 case NeonTypeFlags::Int32: 1583 return shift ? 31 : (2 << IsQuad) - 1; 1584 case NeonTypeFlags::Int64: 1585 case NeonTypeFlags::Poly64: 1586 return shift ? 63 : (1 << IsQuad) - 1; 1587 case NeonTypeFlags::Poly128: 1588 return shift ? 127 : (1 << IsQuad) - 1; 1589 case NeonTypeFlags::Float16: 1590 assert(!shift && "cannot shift float types!"); 1591 return (4 << IsQuad) - 1; 1592 case NeonTypeFlags::Float32: 1593 assert(!shift && "cannot shift float types!"); 1594 return (2 << IsQuad) - 1; 1595 case NeonTypeFlags::Float64: 1596 assert(!shift && "cannot shift float types!"); 1597 return (1 << IsQuad) - 1; 1598 } 1599 llvm_unreachable("Invalid NeonTypeFlag!"); 1600 } 1601 1602 /// getNeonEltType - Return the QualType corresponding to the elements of 1603 /// the vector type specified by the NeonTypeFlags. This is used to check 1604 /// the pointer arguments for Neon load/store intrinsics. 1605 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1606 bool IsPolyUnsigned, bool IsInt64Long) { 1607 switch (Flags.getEltType()) { 1608 case NeonTypeFlags::Int8: 1609 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1610 case NeonTypeFlags::Int16: 1611 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1612 case NeonTypeFlags::Int32: 1613 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1614 case NeonTypeFlags::Int64: 1615 if (IsInt64Long) 1616 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1617 else 1618 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1619 : Context.LongLongTy; 1620 case NeonTypeFlags::Poly8: 1621 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1622 case NeonTypeFlags::Poly16: 1623 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1624 case NeonTypeFlags::Poly64: 1625 if (IsInt64Long) 1626 return Context.UnsignedLongTy; 1627 else 1628 return Context.UnsignedLongLongTy; 1629 case NeonTypeFlags::Poly128: 1630 break; 1631 case NeonTypeFlags::Float16: 1632 return Context.HalfTy; 1633 case NeonTypeFlags::Float32: 1634 return Context.FloatTy; 1635 case NeonTypeFlags::Float64: 1636 return Context.DoubleTy; 1637 } 1638 llvm_unreachable("Invalid NeonTypeFlag!"); 1639 } 1640 1641 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1642 llvm::APSInt Result; 1643 uint64_t mask = 0; 1644 unsigned TV = 0; 1645 int PtrArgNum = -1; 1646 bool HasConstPtr = false; 1647 switch (BuiltinID) { 1648 #define GET_NEON_OVERLOAD_CHECK 1649 #include "clang/Basic/arm_neon.inc" 1650 #include "clang/Basic/arm_fp16.inc" 1651 #undef GET_NEON_OVERLOAD_CHECK 1652 } 1653 1654 // For NEON intrinsics which are overloaded on vector element type, validate 1655 // the immediate which specifies which variant to emit. 1656 unsigned ImmArg = TheCall->getNumArgs()-1; 1657 if (mask) { 1658 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1659 return true; 1660 1661 TV = Result.getLimitedValue(64); 1662 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 1663 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 1664 << TheCall->getArg(ImmArg)->getSourceRange(); 1665 } 1666 1667 if (PtrArgNum >= 0) { 1668 // Check that pointer arguments have the specified type. 1669 Expr *Arg = TheCall->getArg(PtrArgNum); 1670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 1671 Arg = ICE->getSubExpr(); 1672 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 1673 QualType RHSTy = RHS.get()->getType(); 1674 1675 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1676 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 1677 Arch == llvm::Triple::aarch64_be; 1678 bool IsInt64Long = 1679 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 1680 QualType EltTy = 1681 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 1682 if (HasConstPtr) 1683 EltTy = EltTy.withConst(); 1684 QualType LHSTy = Context.getPointerType(EltTy); 1685 AssignConvertType ConvTy; 1686 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 1687 if (RHS.isInvalid()) 1688 return true; 1689 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 1690 RHS.get(), AA_Assigning)) 1691 return true; 1692 } 1693 1694 // For NEON intrinsics which take an immediate value as part of the 1695 // instruction, range check them here. 1696 unsigned i = 0, l = 0, u = 0; 1697 switch (BuiltinID) { 1698 default: 1699 return false; 1700 #define GET_NEON_IMMEDIATE_CHECK 1701 #include "clang/Basic/arm_neon.inc" 1702 #include "clang/Basic/arm_fp16.inc" 1703 #undef GET_NEON_IMMEDIATE_CHECK 1704 } 1705 1706 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1707 } 1708 1709 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 1710 unsigned MaxWidth) { 1711 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 1712 BuiltinID == ARM::BI__builtin_arm_ldaex || 1713 BuiltinID == ARM::BI__builtin_arm_strex || 1714 BuiltinID == ARM::BI__builtin_arm_stlex || 1715 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1716 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1717 BuiltinID == AArch64::BI__builtin_arm_strex || 1718 BuiltinID == AArch64::BI__builtin_arm_stlex) && 1719 "unexpected ARM builtin"); 1720 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 1721 BuiltinID == ARM::BI__builtin_arm_ldaex || 1722 BuiltinID == AArch64::BI__builtin_arm_ldrex || 1723 BuiltinID == AArch64::BI__builtin_arm_ldaex; 1724 1725 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1726 1727 // Ensure that we have the proper number of arguments. 1728 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 1729 return true; 1730 1731 // Inspect the pointer argument of the atomic builtin. This should always be 1732 // a pointer type, whose element is an integral scalar or pointer type. 1733 // Because it is a pointer type, we don't have to worry about any implicit 1734 // casts here. 1735 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 1736 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 1737 if (PointerArgRes.isInvalid()) 1738 return true; 1739 PointerArg = PointerArgRes.get(); 1740 1741 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 1742 if (!pointerType) { 1743 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 1744 << PointerArg->getType() << PointerArg->getSourceRange(); 1745 return true; 1746 } 1747 1748 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 1749 // task is to insert the appropriate casts into the AST. First work out just 1750 // what the appropriate type is. 1751 QualType ValType = pointerType->getPointeeType(); 1752 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 1753 if (IsLdrex) 1754 AddrType.addConst(); 1755 1756 // Issue a warning if the cast is dodgy. 1757 CastKind CastNeeded = CK_NoOp; 1758 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 1759 CastNeeded = CK_BitCast; 1760 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 1761 << PointerArg->getType() << Context.getPointerType(AddrType) 1762 << AA_Passing << PointerArg->getSourceRange(); 1763 } 1764 1765 // Finally, do the cast and replace the argument with the corrected version. 1766 AddrType = Context.getPointerType(AddrType); 1767 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 1768 if (PointerArgRes.isInvalid()) 1769 return true; 1770 PointerArg = PointerArgRes.get(); 1771 1772 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 1773 1774 // In general, we allow ints, floats and pointers to be loaded and stored. 1775 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 1776 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 1777 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 1778 << PointerArg->getType() << PointerArg->getSourceRange(); 1779 return true; 1780 } 1781 1782 // But ARM doesn't have instructions to deal with 128-bit versions. 1783 if (Context.getTypeSize(ValType) > MaxWidth) { 1784 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 1785 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 1786 << PointerArg->getType() << PointerArg->getSourceRange(); 1787 return true; 1788 } 1789 1790 switch (ValType.getObjCLifetime()) { 1791 case Qualifiers::OCL_None: 1792 case Qualifiers::OCL_ExplicitNone: 1793 // okay 1794 break; 1795 1796 case Qualifiers::OCL_Weak: 1797 case Qualifiers::OCL_Strong: 1798 case Qualifiers::OCL_Autoreleasing: 1799 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 1800 << ValType << PointerArg->getSourceRange(); 1801 return true; 1802 } 1803 1804 if (IsLdrex) { 1805 TheCall->setType(ValType); 1806 return false; 1807 } 1808 1809 // Initialize the argument to be stored. 1810 ExprResult ValArg = TheCall->getArg(0); 1811 InitializedEntity Entity = InitializedEntity::InitializeParameter( 1812 Context, ValType, /*consume*/ false); 1813 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 1814 if (ValArg.isInvalid()) 1815 return true; 1816 TheCall->setArg(0, ValArg.get()); 1817 1818 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 1819 // but the custom checker bypasses all default analysis. 1820 TheCall->setType(Context.IntTy); 1821 return false; 1822 } 1823 1824 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1825 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 1826 BuiltinID == ARM::BI__builtin_arm_ldaex || 1827 BuiltinID == ARM::BI__builtin_arm_strex || 1828 BuiltinID == ARM::BI__builtin_arm_stlex) { 1829 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 1830 } 1831 1832 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 1833 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1834 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 1835 } 1836 1837 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 1838 BuiltinID == ARM::BI__builtin_arm_wsr64) 1839 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 1840 1841 if (BuiltinID == ARM::BI__builtin_arm_rsr || 1842 BuiltinID == ARM::BI__builtin_arm_rsrp || 1843 BuiltinID == ARM::BI__builtin_arm_wsr || 1844 BuiltinID == ARM::BI__builtin_arm_wsrp) 1845 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1846 1847 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1848 return true; 1849 1850 // For intrinsics which take an immediate value as part of the instruction, 1851 // range check them here. 1852 // FIXME: VFP Intrinsics should error if VFP not present. 1853 switch (BuiltinID) { 1854 default: return false; 1855 case ARM::BI__builtin_arm_ssat: 1856 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 1857 case ARM::BI__builtin_arm_usat: 1858 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 1859 case ARM::BI__builtin_arm_ssat16: 1860 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 1861 case ARM::BI__builtin_arm_usat16: 1862 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 1863 case ARM::BI__builtin_arm_vcvtr_f: 1864 case ARM::BI__builtin_arm_vcvtr_d: 1865 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 1866 case ARM::BI__builtin_arm_dmb: 1867 case ARM::BI__builtin_arm_dsb: 1868 case ARM::BI__builtin_arm_isb: 1869 case ARM::BI__builtin_arm_dbg: 1870 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 1871 } 1872 } 1873 1874 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 1875 CallExpr *TheCall) { 1876 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 1877 BuiltinID == AArch64::BI__builtin_arm_ldaex || 1878 BuiltinID == AArch64::BI__builtin_arm_strex || 1879 BuiltinID == AArch64::BI__builtin_arm_stlex) { 1880 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 1881 } 1882 1883 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 1884 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 1885 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 1886 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 1887 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 1888 } 1889 1890 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 1891 BuiltinID == AArch64::BI__builtin_arm_wsr64) 1892 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1893 1894 // Memory Tagging Extensions (MTE) Intrinsics 1895 if (BuiltinID == AArch64::BI__builtin_arm_irg || 1896 BuiltinID == AArch64::BI__builtin_arm_addg || 1897 BuiltinID == AArch64::BI__builtin_arm_gmi || 1898 BuiltinID == AArch64::BI__builtin_arm_ldg || 1899 BuiltinID == AArch64::BI__builtin_arm_stg || 1900 BuiltinID == AArch64::BI__builtin_arm_subp) { 1901 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 1902 } 1903 1904 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 1905 BuiltinID == AArch64::BI__builtin_arm_rsrp || 1906 BuiltinID == AArch64::BI__builtin_arm_wsr || 1907 BuiltinID == AArch64::BI__builtin_arm_wsrp) 1908 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 1909 1910 // Only check the valid encoding range. Any constant in this range would be 1911 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 1912 // an exception for incorrect registers. This matches MSVC behavior. 1913 if (BuiltinID == AArch64::BI_ReadStatusReg || 1914 BuiltinID == AArch64::BI_WriteStatusReg) 1915 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 1916 1917 if (BuiltinID == AArch64::BI__getReg) 1918 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 1919 1920 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 1921 return true; 1922 1923 // For intrinsics which take an immediate value as part of the instruction, 1924 // range check them here. 1925 unsigned i = 0, l = 0, u = 0; 1926 switch (BuiltinID) { 1927 default: return false; 1928 case AArch64::BI__builtin_arm_dmb: 1929 case AArch64::BI__builtin_arm_dsb: 1930 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 1931 } 1932 1933 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 1934 } 1935 1936 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 1937 struct BuiltinAndString { 1938 unsigned BuiltinID; 1939 const char *Str; 1940 }; 1941 1942 static BuiltinAndString ValidCPU[] = { 1943 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" }, 1944 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" }, 1945 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" }, 1946 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" }, 1947 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" }, 1948 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" }, 1949 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" }, 1950 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" }, 1951 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" }, 1952 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" }, 1953 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" }, 1954 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" }, 1955 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" }, 1956 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" }, 1957 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" }, 1958 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" }, 1959 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" }, 1960 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" }, 1961 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" }, 1962 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" }, 1963 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" }, 1964 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" }, 1965 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" }, 1966 }; 1967 1968 static BuiltinAndString ValidHVX[] = { 1969 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" }, 1970 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" }, 1971 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" }, 1972 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" }, 1973 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" }, 1974 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" }, 1975 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" }, 1976 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" }, 1977 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" }, 1978 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" }, 1979 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" }, 1980 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" }, 1981 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" }, 1982 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" }, 1983 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" }, 1984 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" }, 1985 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" }, 1986 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" }, 1987 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" }, 1988 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" }, 1989 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" }, 1990 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" }, 1991 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" }, 1992 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" }, 1993 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" }, 1994 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" }, 1995 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" }, 1996 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" }, 1997 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" }, 1998 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" }, 1999 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" }, 2000 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" }, 2001 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" }, 2002 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" }, 2003 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" }, 2004 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" }, 2005 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" }, 2006 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" }, 2007 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" }, 2008 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" }, 2009 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" }, 2010 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" }, 2011 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" }, 2012 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" }, 2013 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" }, 2014 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" }, 2015 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" }, 2016 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" }, 2017 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" }, 2018 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" }, 2019 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" }, 2020 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" }, 2021 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" }, 2022 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" }, 2023 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" }, 2024 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" }, 2025 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" }, 2026 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" }, 2027 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" }, 2028 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" }, 2029 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" }, 2030 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" }, 2031 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" }, 2032 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" }, 2033 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" }, 2034 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" }, 2035 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" }, 2036 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" }, 2037 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" }, 2038 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" }, 2039 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" }, 2040 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" }, 2041 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" }, 2042 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" }, 2043 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" }, 2044 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" }, 2045 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" }, 2046 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" }, 2047 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" }, 2048 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" }, 2049 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" }, 2050 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" }, 2051 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" }, 2052 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" }, 2053 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" }, 2054 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" }, 2055 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" }, 2056 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" }, 2057 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" }, 2058 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" }, 2059 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" }, 2060 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" }, 2061 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" }, 2062 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" }, 2063 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" }, 2064 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" }, 2065 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" }, 2066 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" }, 2067 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" }, 2068 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" }, 2069 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" }, 2070 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" }, 2071 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" }, 2072 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" }, 2073 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" }, 2074 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" }, 2075 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" }, 2076 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" }, 2077 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" }, 2078 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" }, 2079 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" }, 2080 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" }, 2081 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" }, 2082 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" }, 2083 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" }, 2084 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" }, 2085 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" }, 2086 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" }, 2087 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" }, 2088 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" }, 2089 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" }, 2090 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" }, 2091 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" }, 2092 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" }, 2093 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" }, 2094 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" }, 2095 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" }, 2096 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" }, 2097 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" }, 2098 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" }, 2099 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" }, 2100 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" }, 2101 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" }, 2102 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" }, 2103 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" }, 2104 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" }, 2105 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" }, 2106 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" }, 2107 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" }, 2108 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" }, 2109 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" }, 2110 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" }, 2111 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" }, 2112 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" }, 2113 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" }, 2114 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" }, 2115 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" }, 2116 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" }, 2117 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" }, 2118 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" }, 2119 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" }, 2120 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" }, 2121 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" }, 2122 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" }, 2123 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" }, 2124 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" }, 2125 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" }, 2126 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" }, 2127 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" }, 2128 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" }, 2129 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" }, 2130 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" }, 2131 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" }, 2132 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" }, 2133 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" }, 2134 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" }, 2135 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" }, 2136 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" }, 2137 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" }, 2138 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" }, 2139 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" }, 2140 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" }, 2141 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" }, 2142 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" }, 2143 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" }, 2144 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" }, 2145 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" }, 2146 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" }, 2147 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" }, 2148 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" }, 2149 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" }, 2150 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" }, 2151 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" }, 2152 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" }, 2153 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" }, 2154 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" }, 2155 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" }, 2156 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" }, 2157 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" }, 2158 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" }, 2159 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" }, 2160 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" }, 2161 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" }, 2162 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" }, 2163 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" }, 2164 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" }, 2165 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" }, 2166 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" }, 2167 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" }, 2168 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" }, 2169 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" }, 2170 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" }, 2171 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" }, 2172 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" }, 2173 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" }, 2174 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" }, 2175 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" }, 2176 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" }, 2177 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" }, 2178 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" }, 2179 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" }, 2180 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" }, 2181 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" }, 2182 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" }, 2183 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" }, 2184 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" }, 2185 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" }, 2186 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" }, 2187 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" }, 2188 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" }, 2189 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" }, 2190 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" }, 2191 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" }, 2192 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" }, 2193 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" }, 2194 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" }, 2195 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" }, 2196 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" }, 2197 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" }, 2198 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" }, 2199 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" }, 2200 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" }, 2201 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" }, 2202 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" }, 2203 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" }, 2204 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" }, 2205 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" }, 2206 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" }, 2207 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" }, 2208 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" }, 2209 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" }, 2210 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" }, 2211 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" }, 2212 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" }, 2213 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" }, 2214 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" }, 2215 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" }, 2216 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" }, 2217 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" }, 2218 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" }, 2219 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" }, 2220 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" }, 2221 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" }, 2222 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" }, 2223 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" }, 2224 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2225 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" }, 2226 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" }, 2227 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" }, 2228 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" }, 2229 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" }, 2230 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" }, 2231 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" }, 2232 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" }, 2233 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" }, 2234 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" }, 2235 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" }, 2236 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" }, 2237 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" }, 2238 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" }, 2239 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" }, 2240 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" }, 2241 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" }, 2242 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" }, 2243 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" }, 2244 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" }, 2245 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" }, 2246 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" }, 2247 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" }, 2248 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" }, 2249 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" }, 2250 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" }, 2251 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" }, 2252 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" }, 2253 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" }, 2254 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" }, 2255 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" }, 2256 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" }, 2257 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" }, 2258 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" }, 2259 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" }, 2260 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" }, 2261 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" }, 2262 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" }, 2263 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" }, 2264 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" }, 2265 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" }, 2266 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" }, 2267 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" }, 2268 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" }, 2269 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" }, 2270 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" }, 2271 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" }, 2272 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" }, 2273 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" }, 2274 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" }, 2275 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" }, 2276 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" }, 2277 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" }, 2278 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" }, 2279 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" }, 2280 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" }, 2281 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" }, 2282 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" }, 2283 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" }, 2284 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" }, 2285 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" }, 2286 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" }, 2287 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" }, 2288 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" }, 2289 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" }, 2290 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" }, 2291 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" }, 2292 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" }, 2293 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" }, 2294 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" }, 2295 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" }, 2296 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" }, 2297 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" }, 2298 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" }, 2299 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" }, 2300 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" }, 2301 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" }, 2302 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" }, 2303 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" }, 2304 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" }, 2305 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" }, 2306 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" }, 2307 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" }, 2308 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" }, 2309 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" }, 2310 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" }, 2311 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" }, 2312 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" }, 2313 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" }, 2314 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" }, 2315 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" }, 2316 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" }, 2317 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" }, 2318 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" }, 2319 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" }, 2320 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" }, 2321 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" }, 2322 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" }, 2323 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" }, 2324 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" }, 2325 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" }, 2326 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" }, 2327 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" }, 2328 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" }, 2329 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" }, 2330 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" }, 2331 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" }, 2332 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" }, 2333 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" }, 2334 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" }, 2335 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" }, 2336 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" }, 2337 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" }, 2338 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" }, 2339 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" }, 2340 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" }, 2341 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" }, 2342 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" }, 2343 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" }, 2344 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" }, 2345 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" }, 2346 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" }, 2347 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" }, 2348 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" }, 2349 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" }, 2350 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" }, 2351 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" }, 2352 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" }, 2353 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" }, 2354 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" }, 2355 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" }, 2356 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" }, 2357 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" }, 2358 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" }, 2359 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" }, 2360 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" }, 2361 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" }, 2362 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" }, 2363 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" }, 2364 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" }, 2365 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" }, 2366 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" }, 2367 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" }, 2368 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" }, 2369 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" }, 2370 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" }, 2371 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" }, 2372 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" }, 2373 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" }, 2374 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" }, 2375 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" }, 2376 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" }, 2377 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" }, 2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" }, 2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" }, 2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" }, 2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" }, 2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" }, 2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" }, 2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" }, 2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" }, 2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" }, 2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" }, 2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" }, 2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" }, 2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" }, 2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" }, 2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" }, 2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" }, 2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" }, 2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" }, 2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" }, 2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" }, 2398 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" }, 2399 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" }, 2400 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" }, 2401 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" }, 2402 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" }, 2403 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" }, 2404 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" }, 2405 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" }, 2406 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" }, 2407 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" }, 2408 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" }, 2409 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" }, 2410 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" }, 2411 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" }, 2412 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" }, 2413 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" }, 2414 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" }, 2415 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" }, 2416 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" }, 2417 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" }, 2418 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" }, 2419 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" }, 2420 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" }, 2421 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" }, 2422 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" }, 2423 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" }, 2424 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" }, 2425 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" }, 2426 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" }, 2427 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" }, 2428 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" }, 2429 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" }, 2430 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" }, 2431 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" }, 2432 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" }, 2433 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" }, 2434 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" }, 2435 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" }, 2436 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" }, 2437 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" }, 2438 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" }, 2439 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" }, 2440 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" }, 2441 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" }, 2442 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" }, 2443 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" }, 2444 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" }, 2445 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" }, 2446 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" }, 2447 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" }, 2448 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" }, 2449 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" }, 2450 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" }, 2451 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" }, 2452 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" }, 2453 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" }, 2454 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" }, 2455 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" }, 2456 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" }, 2457 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" }, 2458 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" }, 2459 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" }, 2460 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" }, 2461 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" }, 2462 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" }, 2463 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" }, 2464 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" }, 2465 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" }, 2466 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" }, 2467 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" }, 2468 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" }, 2469 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" }, 2470 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" }, 2471 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" }, 2472 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" }, 2473 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" }, 2474 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" }, 2475 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" }, 2476 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" }, 2477 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" }, 2478 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" }, 2479 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" }, 2480 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" }, 2481 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" }, 2482 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" }, 2483 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" }, 2484 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" }, 2485 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" }, 2486 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" }, 2487 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" }, 2488 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" }, 2489 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" }, 2490 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" }, 2491 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" }, 2492 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" }, 2493 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" }, 2494 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" }, 2495 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" }, 2504 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" }, 2509 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" }, 2514 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" }, 2515 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" }, 2516 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" }, 2517 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" }, 2518 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" }, 2519 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" }, 2520 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" }, 2521 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" }, 2522 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" }, 2523 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" }, 2524 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" }, 2525 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" }, 2526 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" }, 2527 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" }, 2528 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" }, 2529 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" }, 2530 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" }, 2531 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" }, 2532 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" }, 2533 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" }, 2534 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" }, 2535 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" }, 2536 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" }, 2537 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" }, 2538 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" }, 2539 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" }, 2540 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" }, 2541 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" }, 2542 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" }, 2543 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" }, 2544 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" }, 2545 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" }, 2546 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" }, 2547 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" }, 2548 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" }, 2549 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" }, 2550 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" }, 2551 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" }, 2552 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" }, 2553 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" }, 2554 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" }, 2555 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" }, 2556 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" }, 2557 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" }, 2558 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" }, 2559 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" }, 2560 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" }, 2561 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" }, 2562 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" }, 2563 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" }, 2564 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" }, 2565 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" }, 2566 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" }, 2567 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" }, 2568 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" }, 2569 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" }, 2570 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" }, 2571 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" }, 2572 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" }, 2573 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" }, 2574 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" }, 2588 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" }, 2593 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" }, 2598 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" }, 2599 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" }, 2600 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" }, 2601 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" }, 2602 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" }, 2603 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" }, 2604 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" }, 2605 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" }, 2606 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" }, 2607 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" }, 2608 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" }, 2609 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" }, 2610 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" }, 2611 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" }, 2612 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" }, 2613 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" }, 2614 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" }, 2615 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" }, 2616 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" }, 2617 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" }, 2618 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" }, 2619 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" }, 2620 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" }, 2621 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" }, 2622 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" }, 2623 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" }, 2624 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" }, 2625 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" }, 2626 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" }, 2627 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" }, 2628 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" }, 2629 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" }, 2630 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" }, 2631 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" }, 2632 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" }, 2633 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" }, 2634 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" }, 2635 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" }, 2636 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" }, 2637 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" }, 2638 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" }, 2639 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" }, 2640 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" }, 2641 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" }, 2642 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" }, 2643 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" }, 2644 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" }, 2645 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" }, 2646 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" }, 2647 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" }, 2648 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" }, 2649 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" }, 2650 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" }, 2651 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" }, 2652 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" }, 2653 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" }, 2654 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" }, 2655 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" }, 2656 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" }, 2657 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" }, 2658 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" }, 2659 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" }, 2660 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" }, 2661 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" }, 2662 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" }, 2663 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" }, 2664 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" }, 2665 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" }, 2666 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" }, 2667 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" }, 2668 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" }, 2669 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" }, 2670 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" }, 2671 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" }, 2672 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" }, 2673 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" }, 2674 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" }, 2675 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" }, 2676 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" }, 2677 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" }, 2678 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" }, 2679 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" }, 2680 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" }, 2681 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" }, 2682 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" }, 2683 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" }, 2684 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" }, 2685 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" }, 2686 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" }, 2687 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" }, 2688 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" }, 2689 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" }, 2690 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" }, 2691 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" }, 2692 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" }, 2693 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" }, 2694 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" }, 2695 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" }, 2696 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" }, 2697 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" }, 2698 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" }, 2699 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" }, 2700 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" }, 2701 }; 2702 2703 // Sort the tables on first execution so we can binary search them. 2704 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) { 2705 return LHS.BuiltinID < RHS.BuiltinID; 2706 }; 2707 static const bool SortOnce = 2708 (llvm::sort(ValidCPU, SortCmp), 2709 llvm::sort(ValidHVX, SortCmp), true); 2710 (void)SortOnce; 2711 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) { 2712 return BI.BuiltinID < BuiltinID; 2713 }; 2714 2715 const TargetInfo &TI = Context.getTargetInfo(); 2716 2717 const BuiltinAndString *FC = 2718 llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp); 2719 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) { 2720 const TargetOptions &Opts = TI.getTargetOpts(); 2721 StringRef CPU = Opts.CPU; 2722 if (!CPU.empty()) { 2723 assert(CPU.startswith("hexagon") && "Unexpected CPU name"); 2724 CPU.consume_front("hexagon"); 2725 SmallVector<StringRef, 3> CPUs; 2726 StringRef(FC->Str).split(CPUs, ','); 2727 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; })) 2728 return Diag(TheCall->getBeginLoc(), 2729 diag::err_hexagon_builtin_unsupported_cpu); 2730 } 2731 } 2732 2733 const BuiltinAndString *FH = 2734 llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp); 2735 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) { 2736 if (!TI.hasFeature("hvx")) 2737 return Diag(TheCall->getBeginLoc(), 2738 diag::err_hexagon_builtin_requires_hvx); 2739 2740 SmallVector<StringRef, 3> HVXs; 2741 StringRef(FH->Str).split(HVXs, ','); 2742 bool IsValid = llvm::any_of(HVXs, 2743 [&TI] (StringRef V) { 2744 std::string F = "hvx" + V.str(); 2745 return TI.hasFeature(F); 2746 }); 2747 if (!IsValid) 2748 return Diag(TheCall->getBeginLoc(), 2749 diag::err_hexagon_builtin_unsupported_hvx); 2750 } 2751 2752 return false; 2753 } 2754 2755 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2756 struct ArgInfo { 2757 uint8_t OpNum; 2758 bool IsSigned; 2759 uint8_t BitWidth; 2760 uint8_t Align; 2761 }; 2762 struct BuiltinInfo { 2763 unsigned BuiltinID; 2764 ArgInfo Infos[2]; 2765 }; 2766 2767 static BuiltinInfo Infos[] = { 2768 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2769 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2770 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2771 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} }, 2772 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2773 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2774 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2775 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2776 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2777 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2778 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2779 2780 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2791 2792 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2844 {{ 1, false, 6, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2852 {{ 1, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2859 { 2, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2861 { 2, false, 6, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2863 { 3, false, 5, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2865 { 3, false, 6, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2882 {{ 2, false, 4, 0 }, 2883 { 3, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2885 {{ 2, false, 4, 0 }, 2886 { 3, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2888 {{ 2, false, 4, 0 }, 2889 { 3, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2891 {{ 2, false, 4, 0 }, 2892 { 3, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2894 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2904 { 2, false, 5, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2906 { 2, false, 6, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2916 {{ 1, false, 4, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2919 {{ 1, false, 4, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2940 {{ 3, false, 1, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2945 {{ 3, false, 1, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2948 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2950 {{ 3, false, 1, 0 }} }, 2951 }; 2952 2953 // Use a dynamically initialized static to sort the table exactly once on 2954 // first run. 2955 static const bool SortOnce = 2956 (llvm::sort(Infos, 2957 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2958 return LHS.BuiltinID < RHS.BuiltinID; 2959 }), 2960 true); 2961 (void)SortOnce; 2962 2963 const BuiltinInfo *F = llvm::partition_point( 2964 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2965 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2966 return false; 2967 2968 bool Error = false; 2969 2970 for (const ArgInfo &A : F->Infos) { 2971 // Ignore empty ArgInfo elements. 2972 if (A.BitWidth == 0) 2973 continue; 2974 2975 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2976 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2977 if (!A.Align) { 2978 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2979 } else { 2980 unsigned M = 1 << A.Align; 2981 Min *= M; 2982 Max *= M; 2983 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2984 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2985 } 2986 } 2987 return Error; 2988 } 2989 2990 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2991 CallExpr *TheCall) { 2992 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) || 2993 CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2994 } 2995 2996 2997 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the 2998 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2999 // ordering for DSP is unspecified. MSA is ordered by the data format used 3000 // by the underlying instruction i.e., df/m, df/n and then by size. 3001 // 3002 // FIXME: The size tests here should instead be tablegen'd along with the 3003 // definitions from include/clang/Basic/BuiltinsMips.def. 3004 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3005 // be too. 3006 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3007 unsigned i = 0, l = 0, u = 0, m = 0; 3008 switch (BuiltinID) { 3009 default: return false; 3010 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3011 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3012 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3013 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3014 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3015 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3016 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3017 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3018 // df/m field. 3019 // These intrinsics take an unsigned 3 bit immediate. 3020 case Mips::BI__builtin_msa_bclri_b: 3021 case Mips::BI__builtin_msa_bnegi_b: 3022 case Mips::BI__builtin_msa_bseti_b: 3023 case Mips::BI__builtin_msa_sat_s_b: 3024 case Mips::BI__builtin_msa_sat_u_b: 3025 case Mips::BI__builtin_msa_slli_b: 3026 case Mips::BI__builtin_msa_srai_b: 3027 case Mips::BI__builtin_msa_srari_b: 3028 case Mips::BI__builtin_msa_srli_b: 3029 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3030 case Mips::BI__builtin_msa_binsli_b: 3031 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3032 // These intrinsics take an unsigned 4 bit immediate. 3033 case Mips::BI__builtin_msa_bclri_h: 3034 case Mips::BI__builtin_msa_bnegi_h: 3035 case Mips::BI__builtin_msa_bseti_h: 3036 case Mips::BI__builtin_msa_sat_s_h: 3037 case Mips::BI__builtin_msa_sat_u_h: 3038 case Mips::BI__builtin_msa_slli_h: 3039 case Mips::BI__builtin_msa_srai_h: 3040 case Mips::BI__builtin_msa_srari_h: 3041 case Mips::BI__builtin_msa_srli_h: 3042 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3043 case Mips::BI__builtin_msa_binsli_h: 3044 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3045 // These intrinsics take an unsigned 5 bit immediate. 3046 // The first block of intrinsics actually have an unsigned 5 bit field, 3047 // not a df/n field. 3048 case Mips::BI__builtin_msa_cfcmsa: 3049 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3050 case Mips::BI__builtin_msa_clei_u_b: 3051 case Mips::BI__builtin_msa_clei_u_h: 3052 case Mips::BI__builtin_msa_clei_u_w: 3053 case Mips::BI__builtin_msa_clei_u_d: 3054 case Mips::BI__builtin_msa_clti_u_b: 3055 case Mips::BI__builtin_msa_clti_u_h: 3056 case Mips::BI__builtin_msa_clti_u_w: 3057 case Mips::BI__builtin_msa_clti_u_d: 3058 case Mips::BI__builtin_msa_maxi_u_b: 3059 case Mips::BI__builtin_msa_maxi_u_h: 3060 case Mips::BI__builtin_msa_maxi_u_w: 3061 case Mips::BI__builtin_msa_maxi_u_d: 3062 case Mips::BI__builtin_msa_mini_u_b: 3063 case Mips::BI__builtin_msa_mini_u_h: 3064 case Mips::BI__builtin_msa_mini_u_w: 3065 case Mips::BI__builtin_msa_mini_u_d: 3066 case Mips::BI__builtin_msa_addvi_b: 3067 case Mips::BI__builtin_msa_addvi_h: 3068 case Mips::BI__builtin_msa_addvi_w: 3069 case Mips::BI__builtin_msa_addvi_d: 3070 case Mips::BI__builtin_msa_bclri_w: 3071 case Mips::BI__builtin_msa_bnegi_w: 3072 case Mips::BI__builtin_msa_bseti_w: 3073 case Mips::BI__builtin_msa_sat_s_w: 3074 case Mips::BI__builtin_msa_sat_u_w: 3075 case Mips::BI__builtin_msa_slli_w: 3076 case Mips::BI__builtin_msa_srai_w: 3077 case Mips::BI__builtin_msa_srari_w: 3078 case Mips::BI__builtin_msa_srli_w: 3079 case Mips::BI__builtin_msa_srlri_w: 3080 case Mips::BI__builtin_msa_subvi_b: 3081 case Mips::BI__builtin_msa_subvi_h: 3082 case Mips::BI__builtin_msa_subvi_w: 3083 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3084 case Mips::BI__builtin_msa_binsli_w: 3085 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3086 // These intrinsics take an unsigned 6 bit immediate. 3087 case Mips::BI__builtin_msa_bclri_d: 3088 case Mips::BI__builtin_msa_bnegi_d: 3089 case Mips::BI__builtin_msa_bseti_d: 3090 case Mips::BI__builtin_msa_sat_s_d: 3091 case Mips::BI__builtin_msa_sat_u_d: 3092 case Mips::BI__builtin_msa_slli_d: 3093 case Mips::BI__builtin_msa_srai_d: 3094 case Mips::BI__builtin_msa_srari_d: 3095 case Mips::BI__builtin_msa_srli_d: 3096 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3097 case Mips::BI__builtin_msa_binsli_d: 3098 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3099 // These intrinsics take a signed 5 bit immediate. 3100 case Mips::BI__builtin_msa_ceqi_b: 3101 case Mips::BI__builtin_msa_ceqi_h: 3102 case Mips::BI__builtin_msa_ceqi_w: 3103 case Mips::BI__builtin_msa_ceqi_d: 3104 case Mips::BI__builtin_msa_clti_s_b: 3105 case Mips::BI__builtin_msa_clti_s_h: 3106 case Mips::BI__builtin_msa_clti_s_w: 3107 case Mips::BI__builtin_msa_clti_s_d: 3108 case Mips::BI__builtin_msa_clei_s_b: 3109 case Mips::BI__builtin_msa_clei_s_h: 3110 case Mips::BI__builtin_msa_clei_s_w: 3111 case Mips::BI__builtin_msa_clei_s_d: 3112 case Mips::BI__builtin_msa_maxi_s_b: 3113 case Mips::BI__builtin_msa_maxi_s_h: 3114 case Mips::BI__builtin_msa_maxi_s_w: 3115 case Mips::BI__builtin_msa_maxi_s_d: 3116 case Mips::BI__builtin_msa_mini_s_b: 3117 case Mips::BI__builtin_msa_mini_s_h: 3118 case Mips::BI__builtin_msa_mini_s_w: 3119 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3120 // These intrinsics take an unsigned 8 bit immediate. 3121 case Mips::BI__builtin_msa_andi_b: 3122 case Mips::BI__builtin_msa_nori_b: 3123 case Mips::BI__builtin_msa_ori_b: 3124 case Mips::BI__builtin_msa_shf_b: 3125 case Mips::BI__builtin_msa_shf_h: 3126 case Mips::BI__builtin_msa_shf_w: 3127 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3128 case Mips::BI__builtin_msa_bseli_b: 3129 case Mips::BI__builtin_msa_bmnzi_b: 3130 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3131 // df/n format 3132 // These intrinsics take an unsigned 4 bit immediate. 3133 case Mips::BI__builtin_msa_copy_s_b: 3134 case Mips::BI__builtin_msa_copy_u_b: 3135 case Mips::BI__builtin_msa_insve_b: 3136 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3137 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3138 // These intrinsics take an unsigned 3 bit immediate. 3139 case Mips::BI__builtin_msa_copy_s_h: 3140 case Mips::BI__builtin_msa_copy_u_h: 3141 case Mips::BI__builtin_msa_insve_h: 3142 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3143 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3144 // These intrinsics take an unsigned 2 bit immediate. 3145 case Mips::BI__builtin_msa_copy_s_w: 3146 case Mips::BI__builtin_msa_copy_u_w: 3147 case Mips::BI__builtin_msa_insve_w: 3148 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3149 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3150 // These intrinsics take an unsigned 1 bit immediate. 3151 case Mips::BI__builtin_msa_copy_s_d: 3152 case Mips::BI__builtin_msa_copy_u_d: 3153 case Mips::BI__builtin_msa_insve_d: 3154 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3155 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3156 // Memory offsets and immediate loads. 3157 // These intrinsics take a signed 10 bit immediate. 3158 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3159 case Mips::BI__builtin_msa_ldi_h: 3160 case Mips::BI__builtin_msa_ldi_w: 3161 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3162 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3163 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3164 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3165 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3166 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3167 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3168 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3169 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3170 } 3171 3172 if (!m) 3173 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3174 3175 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3176 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3177 } 3178 3179 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3180 unsigned i = 0, l = 0, u = 0; 3181 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3182 BuiltinID == PPC::BI__builtin_divdeu || 3183 BuiltinID == PPC::BI__builtin_bpermd; 3184 bool IsTarget64Bit = Context.getTargetInfo() 3185 .getTypeWidth(Context 3186 .getTargetInfo() 3187 .getIntPtrType()) == 64; 3188 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3189 BuiltinID == PPC::BI__builtin_divweu || 3190 BuiltinID == PPC::BI__builtin_divde || 3191 BuiltinID == PPC::BI__builtin_divdeu; 3192 3193 if (Is64BitBltin && !IsTarget64Bit) 3194 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3195 << TheCall->getSourceRange(); 3196 3197 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 3198 (BuiltinID == PPC::BI__builtin_bpermd && 3199 !Context.getTargetInfo().hasFeature("bpermd"))) 3200 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3201 << TheCall->getSourceRange(); 3202 3203 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3204 if (!Context.getTargetInfo().hasFeature("vsx")) 3205 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3206 << TheCall->getSourceRange(); 3207 return false; 3208 }; 3209 3210 switch (BuiltinID) { 3211 default: return false; 3212 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3213 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3214 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3215 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3216 case PPC::BI__builtin_tbegin: 3217 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3218 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3219 case PPC::BI__builtin_tabortwc: 3220 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3221 case PPC::BI__builtin_tabortwci: 3222 case PPC::BI__builtin_tabortdci: 3223 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3224 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3225 case PPC::BI__builtin_vsx_xxpermdi: 3226 case PPC::BI__builtin_vsx_xxsldwi: 3227 return SemaBuiltinVSX(TheCall); 3228 case PPC::BI__builtin_unpack_vector_int128: 3229 return SemaVSXCheck(TheCall) || 3230 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3231 case PPC::BI__builtin_pack_vector_int128: 3232 return SemaVSXCheck(TheCall); 3233 } 3234 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3235 } 3236 3237 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3238 CallExpr *TheCall) { 3239 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3240 Expr *Arg = TheCall->getArg(0); 3241 llvm::APSInt AbortCode(32); 3242 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3243 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3244 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3245 << Arg->getSourceRange(); 3246 } 3247 3248 // For intrinsics which take an immediate value as part of the instruction, 3249 // range check them here. 3250 unsigned i = 0, l = 0, u = 0; 3251 switch (BuiltinID) { 3252 default: return false; 3253 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3254 case SystemZ::BI__builtin_s390_verimb: 3255 case SystemZ::BI__builtin_s390_verimh: 3256 case SystemZ::BI__builtin_s390_verimf: 3257 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3258 case SystemZ::BI__builtin_s390_vfaeb: 3259 case SystemZ::BI__builtin_s390_vfaeh: 3260 case SystemZ::BI__builtin_s390_vfaef: 3261 case SystemZ::BI__builtin_s390_vfaebs: 3262 case SystemZ::BI__builtin_s390_vfaehs: 3263 case SystemZ::BI__builtin_s390_vfaefs: 3264 case SystemZ::BI__builtin_s390_vfaezb: 3265 case SystemZ::BI__builtin_s390_vfaezh: 3266 case SystemZ::BI__builtin_s390_vfaezf: 3267 case SystemZ::BI__builtin_s390_vfaezbs: 3268 case SystemZ::BI__builtin_s390_vfaezhs: 3269 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3270 case SystemZ::BI__builtin_s390_vfisb: 3271 case SystemZ::BI__builtin_s390_vfidb: 3272 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3273 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3274 case SystemZ::BI__builtin_s390_vftcisb: 3275 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3276 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3277 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3278 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3279 case SystemZ::BI__builtin_s390_vstrcb: 3280 case SystemZ::BI__builtin_s390_vstrch: 3281 case SystemZ::BI__builtin_s390_vstrcf: 3282 case SystemZ::BI__builtin_s390_vstrczb: 3283 case SystemZ::BI__builtin_s390_vstrczh: 3284 case SystemZ::BI__builtin_s390_vstrczf: 3285 case SystemZ::BI__builtin_s390_vstrcbs: 3286 case SystemZ::BI__builtin_s390_vstrchs: 3287 case SystemZ::BI__builtin_s390_vstrcfs: 3288 case SystemZ::BI__builtin_s390_vstrczbs: 3289 case SystemZ::BI__builtin_s390_vstrczhs: 3290 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3291 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3292 case SystemZ::BI__builtin_s390_vfminsb: 3293 case SystemZ::BI__builtin_s390_vfmaxsb: 3294 case SystemZ::BI__builtin_s390_vfmindb: 3295 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3296 } 3297 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3298 } 3299 3300 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3301 /// This checks that the target supports __builtin_cpu_supports and 3302 /// that the string argument is constant and valid. 3303 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3304 Expr *Arg = TheCall->getArg(0); 3305 3306 // Check if the argument is a string literal. 3307 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3308 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3309 << Arg->getSourceRange(); 3310 3311 // Check the contents of the string. 3312 StringRef Feature = 3313 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3314 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3315 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3316 << Arg->getSourceRange(); 3317 return false; 3318 } 3319 3320 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3321 /// This checks that the target supports __builtin_cpu_is and 3322 /// that the string argument is constant and valid. 3323 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3324 Expr *Arg = TheCall->getArg(0); 3325 3326 // Check if the argument is a string literal. 3327 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3328 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3329 << Arg->getSourceRange(); 3330 3331 // Check the contents of the string. 3332 StringRef Feature = 3333 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3334 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3335 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3336 << Arg->getSourceRange(); 3337 return false; 3338 } 3339 3340 // Check if the rounding mode is legal. 3341 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3342 // Indicates if this instruction has rounding control or just SAE. 3343 bool HasRC = false; 3344 3345 unsigned ArgNum = 0; 3346 switch (BuiltinID) { 3347 default: 3348 return false; 3349 case X86::BI__builtin_ia32_vcvttsd2si32: 3350 case X86::BI__builtin_ia32_vcvttsd2si64: 3351 case X86::BI__builtin_ia32_vcvttsd2usi32: 3352 case X86::BI__builtin_ia32_vcvttsd2usi64: 3353 case X86::BI__builtin_ia32_vcvttss2si32: 3354 case X86::BI__builtin_ia32_vcvttss2si64: 3355 case X86::BI__builtin_ia32_vcvttss2usi32: 3356 case X86::BI__builtin_ia32_vcvttss2usi64: 3357 ArgNum = 1; 3358 break; 3359 case X86::BI__builtin_ia32_maxpd512: 3360 case X86::BI__builtin_ia32_maxps512: 3361 case X86::BI__builtin_ia32_minpd512: 3362 case X86::BI__builtin_ia32_minps512: 3363 ArgNum = 2; 3364 break; 3365 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3366 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3367 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3368 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3369 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3370 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3371 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3372 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3373 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3374 case X86::BI__builtin_ia32_exp2pd_mask: 3375 case X86::BI__builtin_ia32_exp2ps_mask: 3376 case X86::BI__builtin_ia32_getexppd512_mask: 3377 case X86::BI__builtin_ia32_getexpps512_mask: 3378 case X86::BI__builtin_ia32_rcp28pd_mask: 3379 case X86::BI__builtin_ia32_rcp28ps_mask: 3380 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3381 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3382 case X86::BI__builtin_ia32_vcomisd: 3383 case X86::BI__builtin_ia32_vcomiss: 3384 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3385 ArgNum = 3; 3386 break; 3387 case X86::BI__builtin_ia32_cmppd512_mask: 3388 case X86::BI__builtin_ia32_cmpps512_mask: 3389 case X86::BI__builtin_ia32_cmpsd_mask: 3390 case X86::BI__builtin_ia32_cmpss_mask: 3391 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3392 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3393 case X86::BI__builtin_ia32_getexpss128_round_mask: 3394 case X86::BI__builtin_ia32_getmantpd512_mask: 3395 case X86::BI__builtin_ia32_getmantps512_mask: 3396 case X86::BI__builtin_ia32_maxsd_round_mask: 3397 case X86::BI__builtin_ia32_maxss_round_mask: 3398 case X86::BI__builtin_ia32_minsd_round_mask: 3399 case X86::BI__builtin_ia32_minss_round_mask: 3400 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3401 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3402 case X86::BI__builtin_ia32_reducepd512_mask: 3403 case X86::BI__builtin_ia32_reduceps512_mask: 3404 case X86::BI__builtin_ia32_rndscalepd_mask: 3405 case X86::BI__builtin_ia32_rndscaleps_mask: 3406 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3407 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3408 ArgNum = 4; 3409 break; 3410 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3411 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3412 case X86::BI__builtin_ia32_fixupimmps512_mask: 3413 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3414 case X86::BI__builtin_ia32_fixupimmsd_mask: 3415 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3416 case X86::BI__builtin_ia32_fixupimmss_mask: 3417 case X86::BI__builtin_ia32_fixupimmss_maskz: 3418 case X86::BI__builtin_ia32_getmantsd_round_mask: 3419 case X86::BI__builtin_ia32_getmantss_round_mask: 3420 case X86::BI__builtin_ia32_rangepd512_mask: 3421 case X86::BI__builtin_ia32_rangeps512_mask: 3422 case X86::BI__builtin_ia32_rangesd128_round_mask: 3423 case X86::BI__builtin_ia32_rangess128_round_mask: 3424 case X86::BI__builtin_ia32_reducesd_mask: 3425 case X86::BI__builtin_ia32_reducess_mask: 3426 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3427 case X86::BI__builtin_ia32_rndscaless_round_mask: 3428 ArgNum = 5; 3429 break; 3430 case X86::BI__builtin_ia32_vcvtsd2si64: 3431 case X86::BI__builtin_ia32_vcvtsd2si32: 3432 case X86::BI__builtin_ia32_vcvtsd2usi32: 3433 case X86::BI__builtin_ia32_vcvtsd2usi64: 3434 case X86::BI__builtin_ia32_vcvtss2si32: 3435 case X86::BI__builtin_ia32_vcvtss2si64: 3436 case X86::BI__builtin_ia32_vcvtss2usi32: 3437 case X86::BI__builtin_ia32_vcvtss2usi64: 3438 case X86::BI__builtin_ia32_sqrtpd512: 3439 case X86::BI__builtin_ia32_sqrtps512: 3440 ArgNum = 1; 3441 HasRC = true; 3442 break; 3443 case X86::BI__builtin_ia32_addpd512: 3444 case X86::BI__builtin_ia32_addps512: 3445 case X86::BI__builtin_ia32_divpd512: 3446 case X86::BI__builtin_ia32_divps512: 3447 case X86::BI__builtin_ia32_mulpd512: 3448 case X86::BI__builtin_ia32_mulps512: 3449 case X86::BI__builtin_ia32_subpd512: 3450 case X86::BI__builtin_ia32_subps512: 3451 case X86::BI__builtin_ia32_cvtsi2sd64: 3452 case X86::BI__builtin_ia32_cvtsi2ss32: 3453 case X86::BI__builtin_ia32_cvtsi2ss64: 3454 case X86::BI__builtin_ia32_cvtusi2sd64: 3455 case X86::BI__builtin_ia32_cvtusi2ss32: 3456 case X86::BI__builtin_ia32_cvtusi2ss64: 3457 ArgNum = 2; 3458 HasRC = true; 3459 break; 3460 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3461 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3462 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3463 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3464 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3465 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3466 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3467 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3468 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3469 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3470 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3471 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3472 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3473 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3474 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3475 ArgNum = 3; 3476 HasRC = true; 3477 break; 3478 case X86::BI__builtin_ia32_addss_round_mask: 3479 case X86::BI__builtin_ia32_addsd_round_mask: 3480 case X86::BI__builtin_ia32_divss_round_mask: 3481 case X86::BI__builtin_ia32_divsd_round_mask: 3482 case X86::BI__builtin_ia32_mulss_round_mask: 3483 case X86::BI__builtin_ia32_mulsd_round_mask: 3484 case X86::BI__builtin_ia32_subss_round_mask: 3485 case X86::BI__builtin_ia32_subsd_round_mask: 3486 case X86::BI__builtin_ia32_scalefpd512_mask: 3487 case X86::BI__builtin_ia32_scalefps512_mask: 3488 case X86::BI__builtin_ia32_scalefsd_round_mask: 3489 case X86::BI__builtin_ia32_scalefss_round_mask: 3490 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3491 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3492 case X86::BI__builtin_ia32_sqrtss_round_mask: 3493 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3494 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3495 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3496 case X86::BI__builtin_ia32_vfmaddss3_mask: 3497 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3498 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3499 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3500 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3501 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3502 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3503 case X86::BI__builtin_ia32_vfmaddps512_mask: 3504 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3505 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3506 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3507 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3508 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3509 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3510 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3511 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3512 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3513 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3514 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3515 ArgNum = 4; 3516 HasRC = true; 3517 break; 3518 } 3519 3520 llvm::APSInt Result; 3521 3522 // We can't check the value of a dependent argument. 3523 Expr *Arg = TheCall->getArg(ArgNum); 3524 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3525 return false; 3526 3527 // Check constant-ness first. 3528 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3529 return true; 3530 3531 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3532 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3533 // combined with ROUND_NO_EXC. 3534 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3535 Result == 8/*ROUND_NO_EXC*/ || 3536 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3537 return false; 3538 3539 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3540 << Arg->getSourceRange(); 3541 } 3542 3543 // Check if the gather/scatter scale is legal. 3544 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3545 CallExpr *TheCall) { 3546 unsigned ArgNum = 0; 3547 switch (BuiltinID) { 3548 default: 3549 return false; 3550 case X86::BI__builtin_ia32_gatherpfdpd: 3551 case X86::BI__builtin_ia32_gatherpfdps: 3552 case X86::BI__builtin_ia32_gatherpfqpd: 3553 case X86::BI__builtin_ia32_gatherpfqps: 3554 case X86::BI__builtin_ia32_scatterpfdpd: 3555 case X86::BI__builtin_ia32_scatterpfdps: 3556 case X86::BI__builtin_ia32_scatterpfqpd: 3557 case X86::BI__builtin_ia32_scatterpfqps: 3558 ArgNum = 3; 3559 break; 3560 case X86::BI__builtin_ia32_gatherd_pd: 3561 case X86::BI__builtin_ia32_gatherd_pd256: 3562 case X86::BI__builtin_ia32_gatherq_pd: 3563 case X86::BI__builtin_ia32_gatherq_pd256: 3564 case X86::BI__builtin_ia32_gatherd_ps: 3565 case X86::BI__builtin_ia32_gatherd_ps256: 3566 case X86::BI__builtin_ia32_gatherq_ps: 3567 case X86::BI__builtin_ia32_gatherq_ps256: 3568 case X86::BI__builtin_ia32_gatherd_q: 3569 case X86::BI__builtin_ia32_gatherd_q256: 3570 case X86::BI__builtin_ia32_gatherq_q: 3571 case X86::BI__builtin_ia32_gatherq_q256: 3572 case X86::BI__builtin_ia32_gatherd_d: 3573 case X86::BI__builtin_ia32_gatherd_d256: 3574 case X86::BI__builtin_ia32_gatherq_d: 3575 case X86::BI__builtin_ia32_gatherq_d256: 3576 case X86::BI__builtin_ia32_gather3div2df: 3577 case X86::BI__builtin_ia32_gather3div2di: 3578 case X86::BI__builtin_ia32_gather3div4df: 3579 case X86::BI__builtin_ia32_gather3div4di: 3580 case X86::BI__builtin_ia32_gather3div4sf: 3581 case X86::BI__builtin_ia32_gather3div4si: 3582 case X86::BI__builtin_ia32_gather3div8sf: 3583 case X86::BI__builtin_ia32_gather3div8si: 3584 case X86::BI__builtin_ia32_gather3siv2df: 3585 case X86::BI__builtin_ia32_gather3siv2di: 3586 case X86::BI__builtin_ia32_gather3siv4df: 3587 case X86::BI__builtin_ia32_gather3siv4di: 3588 case X86::BI__builtin_ia32_gather3siv4sf: 3589 case X86::BI__builtin_ia32_gather3siv4si: 3590 case X86::BI__builtin_ia32_gather3siv8sf: 3591 case X86::BI__builtin_ia32_gather3siv8si: 3592 case X86::BI__builtin_ia32_gathersiv8df: 3593 case X86::BI__builtin_ia32_gathersiv16sf: 3594 case X86::BI__builtin_ia32_gatherdiv8df: 3595 case X86::BI__builtin_ia32_gatherdiv16sf: 3596 case X86::BI__builtin_ia32_gathersiv8di: 3597 case X86::BI__builtin_ia32_gathersiv16si: 3598 case X86::BI__builtin_ia32_gatherdiv8di: 3599 case X86::BI__builtin_ia32_gatherdiv16si: 3600 case X86::BI__builtin_ia32_scatterdiv2df: 3601 case X86::BI__builtin_ia32_scatterdiv2di: 3602 case X86::BI__builtin_ia32_scatterdiv4df: 3603 case X86::BI__builtin_ia32_scatterdiv4di: 3604 case X86::BI__builtin_ia32_scatterdiv4sf: 3605 case X86::BI__builtin_ia32_scatterdiv4si: 3606 case X86::BI__builtin_ia32_scatterdiv8sf: 3607 case X86::BI__builtin_ia32_scatterdiv8si: 3608 case X86::BI__builtin_ia32_scattersiv2df: 3609 case X86::BI__builtin_ia32_scattersiv2di: 3610 case X86::BI__builtin_ia32_scattersiv4df: 3611 case X86::BI__builtin_ia32_scattersiv4di: 3612 case X86::BI__builtin_ia32_scattersiv4sf: 3613 case X86::BI__builtin_ia32_scattersiv4si: 3614 case X86::BI__builtin_ia32_scattersiv8sf: 3615 case X86::BI__builtin_ia32_scattersiv8si: 3616 case X86::BI__builtin_ia32_scattersiv8df: 3617 case X86::BI__builtin_ia32_scattersiv16sf: 3618 case X86::BI__builtin_ia32_scatterdiv8df: 3619 case X86::BI__builtin_ia32_scatterdiv16sf: 3620 case X86::BI__builtin_ia32_scattersiv8di: 3621 case X86::BI__builtin_ia32_scattersiv16si: 3622 case X86::BI__builtin_ia32_scatterdiv8di: 3623 case X86::BI__builtin_ia32_scatterdiv16si: 3624 ArgNum = 4; 3625 break; 3626 } 3627 3628 llvm::APSInt Result; 3629 3630 // We can't check the value of a dependent argument. 3631 Expr *Arg = TheCall->getArg(ArgNum); 3632 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3633 return false; 3634 3635 // Check constant-ness first. 3636 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3637 return true; 3638 3639 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3640 return false; 3641 3642 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3643 << Arg->getSourceRange(); 3644 } 3645 3646 static bool isX86_32Builtin(unsigned BuiltinID) { 3647 // These builtins only work on x86-32 targets. 3648 switch (BuiltinID) { 3649 case X86::BI__builtin_ia32_readeflags_u32: 3650 case X86::BI__builtin_ia32_writeeflags_u32: 3651 return true; 3652 } 3653 3654 return false; 3655 } 3656 3657 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3658 if (BuiltinID == X86::BI__builtin_cpu_supports) 3659 return SemaBuiltinCpuSupports(*this, TheCall); 3660 3661 if (BuiltinID == X86::BI__builtin_cpu_is) 3662 return SemaBuiltinCpuIs(*this, TheCall); 3663 3664 // Check for 32-bit only builtins on a 64-bit target. 3665 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3666 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3667 return Diag(TheCall->getCallee()->getBeginLoc(), 3668 diag::err_32_bit_builtin_64_bit_tgt); 3669 3670 // If the intrinsic has rounding or SAE make sure its valid. 3671 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3672 return true; 3673 3674 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3675 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3676 return true; 3677 3678 // For intrinsics which take an immediate value as part of the instruction, 3679 // range check them here. 3680 int i = 0, l = 0, u = 0; 3681 switch (BuiltinID) { 3682 default: 3683 return false; 3684 case X86::BI__builtin_ia32_vec_ext_v2si: 3685 case X86::BI__builtin_ia32_vec_ext_v2di: 3686 case X86::BI__builtin_ia32_vextractf128_pd256: 3687 case X86::BI__builtin_ia32_vextractf128_ps256: 3688 case X86::BI__builtin_ia32_vextractf128_si256: 3689 case X86::BI__builtin_ia32_extract128i256: 3690 case X86::BI__builtin_ia32_extractf64x4_mask: 3691 case X86::BI__builtin_ia32_extracti64x4_mask: 3692 case X86::BI__builtin_ia32_extractf32x8_mask: 3693 case X86::BI__builtin_ia32_extracti32x8_mask: 3694 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3695 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3696 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3697 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3698 i = 1; l = 0; u = 1; 3699 break; 3700 case X86::BI__builtin_ia32_vec_set_v2di: 3701 case X86::BI__builtin_ia32_vinsertf128_pd256: 3702 case X86::BI__builtin_ia32_vinsertf128_ps256: 3703 case X86::BI__builtin_ia32_vinsertf128_si256: 3704 case X86::BI__builtin_ia32_insert128i256: 3705 case X86::BI__builtin_ia32_insertf32x8: 3706 case X86::BI__builtin_ia32_inserti32x8: 3707 case X86::BI__builtin_ia32_insertf64x4: 3708 case X86::BI__builtin_ia32_inserti64x4: 3709 case X86::BI__builtin_ia32_insertf64x2_256: 3710 case X86::BI__builtin_ia32_inserti64x2_256: 3711 case X86::BI__builtin_ia32_insertf32x4_256: 3712 case X86::BI__builtin_ia32_inserti32x4_256: 3713 i = 2; l = 0; u = 1; 3714 break; 3715 case X86::BI__builtin_ia32_vpermilpd: 3716 case X86::BI__builtin_ia32_vec_ext_v4hi: 3717 case X86::BI__builtin_ia32_vec_ext_v4si: 3718 case X86::BI__builtin_ia32_vec_ext_v4sf: 3719 case X86::BI__builtin_ia32_vec_ext_v4di: 3720 case X86::BI__builtin_ia32_extractf32x4_mask: 3721 case X86::BI__builtin_ia32_extracti32x4_mask: 3722 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3723 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3724 i = 1; l = 0; u = 3; 3725 break; 3726 case X86::BI_mm_prefetch: 3727 case X86::BI__builtin_ia32_vec_ext_v8hi: 3728 case X86::BI__builtin_ia32_vec_ext_v8si: 3729 i = 1; l = 0; u = 7; 3730 break; 3731 case X86::BI__builtin_ia32_sha1rnds4: 3732 case X86::BI__builtin_ia32_blendpd: 3733 case X86::BI__builtin_ia32_shufpd: 3734 case X86::BI__builtin_ia32_vec_set_v4hi: 3735 case X86::BI__builtin_ia32_vec_set_v4si: 3736 case X86::BI__builtin_ia32_vec_set_v4di: 3737 case X86::BI__builtin_ia32_shuf_f32x4_256: 3738 case X86::BI__builtin_ia32_shuf_f64x2_256: 3739 case X86::BI__builtin_ia32_shuf_i32x4_256: 3740 case X86::BI__builtin_ia32_shuf_i64x2_256: 3741 case X86::BI__builtin_ia32_insertf64x2_512: 3742 case X86::BI__builtin_ia32_inserti64x2_512: 3743 case X86::BI__builtin_ia32_insertf32x4: 3744 case X86::BI__builtin_ia32_inserti32x4: 3745 i = 2; l = 0; u = 3; 3746 break; 3747 case X86::BI__builtin_ia32_vpermil2pd: 3748 case X86::BI__builtin_ia32_vpermil2pd256: 3749 case X86::BI__builtin_ia32_vpermil2ps: 3750 case X86::BI__builtin_ia32_vpermil2ps256: 3751 i = 3; l = 0; u = 3; 3752 break; 3753 case X86::BI__builtin_ia32_cmpb128_mask: 3754 case X86::BI__builtin_ia32_cmpw128_mask: 3755 case X86::BI__builtin_ia32_cmpd128_mask: 3756 case X86::BI__builtin_ia32_cmpq128_mask: 3757 case X86::BI__builtin_ia32_cmpb256_mask: 3758 case X86::BI__builtin_ia32_cmpw256_mask: 3759 case X86::BI__builtin_ia32_cmpd256_mask: 3760 case X86::BI__builtin_ia32_cmpq256_mask: 3761 case X86::BI__builtin_ia32_cmpb512_mask: 3762 case X86::BI__builtin_ia32_cmpw512_mask: 3763 case X86::BI__builtin_ia32_cmpd512_mask: 3764 case X86::BI__builtin_ia32_cmpq512_mask: 3765 case X86::BI__builtin_ia32_ucmpb128_mask: 3766 case X86::BI__builtin_ia32_ucmpw128_mask: 3767 case X86::BI__builtin_ia32_ucmpd128_mask: 3768 case X86::BI__builtin_ia32_ucmpq128_mask: 3769 case X86::BI__builtin_ia32_ucmpb256_mask: 3770 case X86::BI__builtin_ia32_ucmpw256_mask: 3771 case X86::BI__builtin_ia32_ucmpd256_mask: 3772 case X86::BI__builtin_ia32_ucmpq256_mask: 3773 case X86::BI__builtin_ia32_ucmpb512_mask: 3774 case X86::BI__builtin_ia32_ucmpw512_mask: 3775 case X86::BI__builtin_ia32_ucmpd512_mask: 3776 case X86::BI__builtin_ia32_ucmpq512_mask: 3777 case X86::BI__builtin_ia32_vpcomub: 3778 case X86::BI__builtin_ia32_vpcomuw: 3779 case X86::BI__builtin_ia32_vpcomud: 3780 case X86::BI__builtin_ia32_vpcomuq: 3781 case X86::BI__builtin_ia32_vpcomb: 3782 case X86::BI__builtin_ia32_vpcomw: 3783 case X86::BI__builtin_ia32_vpcomd: 3784 case X86::BI__builtin_ia32_vpcomq: 3785 case X86::BI__builtin_ia32_vec_set_v8hi: 3786 case X86::BI__builtin_ia32_vec_set_v8si: 3787 i = 2; l = 0; u = 7; 3788 break; 3789 case X86::BI__builtin_ia32_vpermilpd256: 3790 case X86::BI__builtin_ia32_roundps: 3791 case X86::BI__builtin_ia32_roundpd: 3792 case X86::BI__builtin_ia32_roundps256: 3793 case X86::BI__builtin_ia32_roundpd256: 3794 case X86::BI__builtin_ia32_getmantpd128_mask: 3795 case X86::BI__builtin_ia32_getmantpd256_mask: 3796 case X86::BI__builtin_ia32_getmantps128_mask: 3797 case X86::BI__builtin_ia32_getmantps256_mask: 3798 case X86::BI__builtin_ia32_getmantpd512_mask: 3799 case X86::BI__builtin_ia32_getmantps512_mask: 3800 case X86::BI__builtin_ia32_vec_ext_v16qi: 3801 case X86::BI__builtin_ia32_vec_ext_v16hi: 3802 i = 1; l = 0; u = 15; 3803 break; 3804 case X86::BI__builtin_ia32_pblendd128: 3805 case X86::BI__builtin_ia32_blendps: 3806 case X86::BI__builtin_ia32_blendpd256: 3807 case X86::BI__builtin_ia32_shufpd256: 3808 case X86::BI__builtin_ia32_roundss: 3809 case X86::BI__builtin_ia32_roundsd: 3810 case X86::BI__builtin_ia32_rangepd128_mask: 3811 case X86::BI__builtin_ia32_rangepd256_mask: 3812 case X86::BI__builtin_ia32_rangepd512_mask: 3813 case X86::BI__builtin_ia32_rangeps128_mask: 3814 case X86::BI__builtin_ia32_rangeps256_mask: 3815 case X86::BI__builtin_ia32_rangeps512_mask: 3816 case X86::BI__builtin_ia32_getmantsd_round_mask: 3817 case X86::BI__builtin_ia32_getmantss_round_mask: 3818 case X86::BI__builtin_ia32_vec_set_v16qi: 3819 case X86::BI__builtin_ia32_vec_set_v16hi: 3820 i = 2; l = 0; u = 15; 3821 break; 3822 case X86::BI__builtin_ia32_vec_ext_v32qi: 3823 i = 1; l = 0; u = 31; 3824 break; 3825 case X86::BI__builtin_ia32_cmpps: 3826 case X86::BI__builtin_ia32_cmpss: 3827 case X86::BI__builtin_ia32_cmppd: 3828 case X86::BI__builtin_ia32_cmpsd: 3829 case X86::BI__builtin_ia32_cmpps256: 3830 case X86::BI__builtin_ia32_cmppd256: 3831 case X86::BI__builtin_ia32_cmpps128_mask: 3832 case X86::BI__builtin_ia32_cmppd128_mask: 3833 case X86::BI__builtin_ia32_cmpps256_mask: 3834 case X86::BI__builtin_ia32_cmppd256_mask: 3835 case X86::BI__builtin_ia32_cmpps512_mask: 3836 case X86::BI__builtin_ia32_cmppd512_mask: 3837 case X86::BI__builtin_ia32_cmpsd_mask: 3838 case X86::BI__builtin_ia32_cmpss_mask: 3839 case X86::BI__builtin_ia32_vec_set_v32qi: 3840 i = 2; l = 0; u = 31; 3841 break; 3842 case X86::BI__builtin_ia32_permdf256: 3843 case X86::BI__builtin_ia32_permdi256: 3844 case X86::BI__builtin_ia32_permdf512: 3845 case X86::BI__builtin_ia32_permdi512: 3846 case X86::BI__builtin_ia32_vpermilps: 3847 case X86::BI__builtin_ia32_vpermilps256: 3848 case X86::BI__builtin_ia32_vpermilpd512: 3849 case X86::BI__builtin_ia32_vpermilps512: 3850 case X86::BI__builtin_ia32_pshufd: 3851 case X86::BI__builtin_ia32_pshufd256: 3852 case X86::BI__builtin_ia32_pshufd512: 3853 case X86::BI__builtin_ia32_pshufhw: 3854 case X86::BI__builtin_ia32_pshufhw256: 3855 case X86::BI__builtin_ia32_pshufhw512: 3856 case X86::BI__builtin_ia32_pshuflw: 3857 case X86::BI__builtin_ia32_pshuflw256: 3858 case X86::BI__builtin_ia32_pshuflw512: 3859 case X86::BI__builtin_ia32_vcvtps2ph: 3860 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3861 case X86::BI__builtin_ia32_vcvtps2ph256: 3862 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3863 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3864 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3865 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3866 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3867 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3868 case X86::BI__builtin_ia32_rndscaleps_mask: 3869 case X86::BI__builtin_ia32_rndscalepd_mask: 3870 case X86::BI__builtin_ia32_reducepd128_mask: 3871 case X86::BI__builtin_ia32_reducepd256_mask: 3872 case X86::BI__builtin_ia32_reducepd512_mask: 3873 case X86::BI__builtin_ia32_reduceps128_mask: 3874 case X86::BI__builtin_ia32_reduceps256_mask: 3875 case X86::BI__builtin_ia32_reduceps512_mask: 3876 case X86::BI__builtin_ia32_prold512: 3877 case X86::BI__builtin_ia32_prolq512: 3878 case X86::BI__builtin_ia32_prold128: 3879 case X86::BI__builtin_ia32_prold256: 3880 case X86::BI__builtin_ia32_prolq128: 3881 case X86::BI__builtin_ia32_prolq256: 3882 case X86::BI__builtin_ia32_prord512: 3883 case X86::BI__builtin_ia32_prorq512: 3884 case X86::BI__builtin_ia32_prord128: 3885 case X86::BI__builtin_ia32_prord256: 3886 case X86::BI__builtin_ia32_prorq128: 3887 case X86::BI__builtin_ia32_prorq256: 3888 case X86::BI__builtin_ia32_fpclasspd128_mask: 3889 case X86::BI__builtin_ia32_fpclasspd256_mask: 3890 case X86::BI__builtin_ia32_fpclassps128_mask: 3891 case X86::BI__builtin_ia32_fpclassps256_mask: 3892 case X86::BI__builtin_ia32_fpclassps512_mask: 3893 case X86::BI__builtin_ia32_fpclasspd512_mask: 3894 case X86::BI__builtin_ia32_fpclasssd_mask: 3895 case X86::BI__builtin_ia32_fpclassss_mask: 3896 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3897 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3898 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3899 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3900 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3901 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3902 case X86::BI__builtin_ia32_kshiftliqi: 3903 case X86::BI__builtin_ia32_kshiftlihi: 3904 case X86::BI__builtin_ia32_kshiftlisi: 3905 case X86::BI__builtin_ia32_kshiftlidi: 3906 case X86::BI__builtin_ia32_kshiftriqi: 3907 case X86::BI__builtin_ia32_kshiftrihi: 3908 case X86::BI__builtin_ia32_kshiftrisi: 3909 case X86::BI__builtin_ia32_kshiftridi: 3910 i = 1; l = 0; u = 255; 3911 break; 3912 case X86::BI__builtin_ia32_vperm2f128_pd256: 3913 case X86::BI__builtin_ia32_vperm2f128_ps256: 3914 case X86::BI__builtin_ia32_vperm2f128_si256: 3915 case X86::BI__builtin_ia32_permti256: 3916 case X86::BI__builtin_ia32_pblendw128: 3917 case X86::BI__builtin_ia32_pblendw256: 3918 case X86::BI__builtin_ia32_blendps256: 3919 case X86::BI__builtin_ia32_pblendd256: 3920 case X86::BI__builtin_ia32_palignr128: 3921 case X86::BI__builtin_ia32_palignr256: 3922 case X86::BI__builtin_ia32_palignr512: 3923 case X86::BI__builtin_ia32_alignq512: 3924 case X86::BI__builtin_ia32_alignd512: 3925 case X86::BI__builtin_ia32_alignd128: 3926 case X86::BI__builtin_ia32_alignd256: 3927 case X86::BI__builtin_ia32_alignq128: 3928 case X86::BI__builtin_ia32_alignq256: 3929 case X86::BI__builtin_ia32_vcomisd: 3930 case X86::BI__builtin_ia32_vcomiss: 3931 case X86::BI__builtin_ia32_shuf_f32x4: 3932 case X86::BI__builtin_ia32_shuf_f64x2: 3933 case X86::BI__builtin_ia32_shuf_i32x4: 3934 case X86::BI__builtin_ia32_shuf_i64x2: 3935 case X86::BI__builtin_ia32_shufpd512: 3936 case X86::BI__builtin_ia32_shufps: 3937 case X86::BI__builtin_ia32_shufps256: 3938 case X86::BI__builtin_ia32_shufps512: 3939 case X86::BI__builtin_ia32_dbpsadbw128: 3940 case X86::BI__builtin_ia32_dbpsadbw256: 3941 case X86::BI__builtin_ia32_dbpsadbw512: 3942 case X86::BI__builtin_ia32_vpshldd128: 3943 case X86::BI__builtin_ia32_vpshldd256: 3944 case X86::BI__builtin_ia32_vpshldd512: 3945 case X86::BI__builtin_ia32_vpshldq128: 3946 case X86::BI__builtin_ia32_vpshldq256: 3947 case X86::BI__builtin_ia32_vpshldq512: 3948 case X86::BI__builtin_ia32_vpshldw128: 3949 case X86::BI__builtin_ia32_vpshldw256: 3950 case X86::BI__builtin_ia32_vpshldw512: 3951 case X86::BI__builtin_ia32_vpshrdd128: 3952 case X86::BI__builtin_ia32_vpshrdd256: 3953 case X86::BI__builtin_ia32_vpshrdd512: 3954 case X86::BI__builtin_ia32_vpshrdq128: 3955 case X86::BI__builtin_ia32_vpshrdq256: 3956 case X86::BI__builtin_ia32_vpshrdq512: 3957 case X86::BI__builtin_ia32_vpshrdw128: 3958 case X86::BI__builtin_ia32_vpshrdw256: 3959 case X86::BI__builtin_ia32_vpshrdw512: 3960 i = 2; l = 0; u = 255; 3961 break; 3962 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3963 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3964 case X86::BI__builtin_ia32_fixupimmps512_mask: 3965 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3966 case X86::BI__builtin_ia32_fixupimmsd_mask: 3967 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3968 case X86::BI__builtin_ia32_fixupimmss_mask: 3969 case X86::BI__builtin_ia32_fixupimmss_maskz: 3970 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3971 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3972 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3973 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3974 case X86::BI__builtin_ia32_fixupimmps128_mask: 3975 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3976 case X86::BI__builtin_ia32_fixupimmps256_mask: 3977 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3978 case X86::BI__builtin_ia32_pternlogd512_mask: 3979 case X86::BI__builtin_ia32_pternlogd512_maskz: 3980 case X86::BI__builtin_ia32_pternlogq512_mask: 3981 case X86::BI__builtin_ia32_pternlogq512_maskz: 3982 case X86::BI__builtin_ia32_pternlogd128_mask: 3983 case X86::BI__builtin_ia32_pternlogd128_maskz: 3984 case X86::BI__builtin_ia32_pternlogd256_mask: 3985 case X86::BI__builtin_ia32_pternlogd256_maskz: 3986 case X86::BI__builtin_ia32_pternlogq128_mask: 3987 case X86::BI__builtin_ia32_pternlogq128_maskz: 3988 case X86::BI__builtin_ia32_pternlogq256_mask: 3989 case X86::BI__builtin_ia32_pternlogq256_maskz: 3990 i = 3; l = 0; u = 255; 3991 break; 3992 case X86::BI__builtin_ia32_gatherpfdpd: 3993 case X86::BI__builtin_ia32_gatherpfdps: 3994 case X86::BI__builtin_ia32_gatherpfqpd: 3995 case X86::BI__builtin_ia32_gatherpfqps: 3996 case X86::BI__builtin_ia32_scatterpfdpd: 3997 case X86::BI__builtin_ia32_scatterpfdps: 3998 case X86::BI__builtin_ia32_scatterpfqpd: 3999 case X86::BI__builtin_ia32_scatterpfqps: 4000 i = 4; l = 2; u = 3; 4001 break; 4002 case X86::BI__builtin_ia32_reducesd_mask: 4003 case X86::BI__builtin_ia32_reducess_mask: 4004 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4005 case X86::BI__builtin_ia32_rndscaless_round_mask: 4006 i = 4; l = 0; u = 255; 4007 break; 4008 } 4009 4010 // Note that we don't force a hard error on the range check here, allowing 4011 // template-generated or macro-generated dead code to potentially have out-of- 4012 // range values. These need to code generate, but don't need to necessarily 4013 // make any sense. We use a warning that defaults to an error. 4014 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4015 } 4016 4017 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4018 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4019 /// Returns true when the format fits the function and the FormatStringInfo has 4020 /// been populated. 4021 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4022 FormatStringInfo *FSI) { 4023 FSI->HasVAListArg = Format->getFirstArg() == 0; 4024 FSI->FormatIdx = Format->getFormatIdx() - 1; 4025 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4026 4027 // The way the format attribute works in GCC, the implicit this argument 4028 // of member functions is counted. However, it doesn't appear in our own 4029 // lists, so decrement format_idx in that case. 4030 if (IsCXXMember) { 4031 if(FSI->FormatIdx == 0) 4032 return false; 4033 --FSI->FormatIdx; 4034 if (FSI->FirstDataArg != 0) 4035 --FSI->FirstDataArg; 4036 } 4037 return true; 4038 } 4039 4040 /// Checks if a the given expression evaluates to null. 4041 /// 4042 /// Returns true if the value evaluates to null. 4043 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4044 // If the expression has non-null type, it doesn't evaluate to null. 4045 if (auto nullability 4046 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4047 if (*nullability == NullabilityKind::NonNull) 4048 return false; 4049 } 4050 4051 // As a special case, transparent unions initialized with zero are 4052 // considered null for the purposes of the nonnull attribute. 4053 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4054 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4055 if (const CompoundLiteralExpr *CLE = 4056 dyn_cast<CompoundLiteralExpr>(Expr)) 4057 if (const InitListExpr *ILE = 4058 dyn_cast<InitListExpr>(CLE->getInitializer())) 4059 Expr = ILE->getInit(0); 4060 } 4061 4062 bool Result; 4063 return (!Expr->isValueDependent() && 4064 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4065 !Result); 4066 } 4067 4068 static void CheckNonNullArgument(Sema &S, 4069 const Expr *ArgExpr, 4070 SourceLocation CallSiteLoc) { 4071 if (CheckNonNullExpr(S, ArgExpr)) 4072 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4073 S.PDiag(diag::warn_null_arg) 4074 << ArgExpr->getSourceRange()); 4075 } 4076 4077 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4078 FormatStringInfo FSI; 4079 if ((GetFormatStringType(Format) == FST_NSString) && 4080 getFormatStringInfo(Format, false, &FSI)) { 4081 Idx = FSI.FormatIdx; 4082 return true; 4083 } 4084 return false; 4085 } 4086 4087 /// Diagnose use of %s directive in an NSString which is being passed 4088 /// as formatting string to formatting method. 4089 static void 4090 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4091 const NamedDecl *FDecl, 4092 Expr **Args, 4093 unsigned NumArgs) { 4094 unsigned Idx = 0; 4095 bool Format = false; 4096 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4097 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4098 Idx = 2; 4099 Format = true; 4100 } 4101 else 4102 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4103 if (S.GetFormatNSStringIdx(I, Idx)) { 4104 Format = true; 4105 break; 4106 } 4107 } 4108 if (!Format || NumArgs <= Idx) 4109 return; 4110 const Expr *FormatExpr = Args[Idx]; 4111 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4112 FormatExpr = CSCE->getSubExpr(); 4113 const StringLiteral *FormatString; 4114 if (const ObjCStringLiteral *OSL = 4115 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4116 FormatString = OSL->getString(); 4117 else 4118 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4119 if (!FormatString) 4120 return; 4121 if (S.FormatStringHasSArg(FormatString)) { 4122 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4123 << "%s" << 1 << 1; 4124 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4125 << FDecl->getDeclName(); 4126 } 4127 } 4128 4129 /// Determine whether the given type has a non-null nullability annotation. 4130 static bool isNonNullType(ASTContext &ctx, QualType type) { 4131 if (auto nullability = type->getNullability(ctx)) 4132 return *nullability == NullabilityKind::NonNull; 4133 4134 return false; 4135 } 4136 4137 static void CheckNonNullArguments(Sema &S, 4138 const NamedDecl *FDecl, 4139 const FunctionProtoType *Proto, 4140 ArrayRef<const Expr *> Args, 4141 SourceLocation CallSiteLoc) { 4142 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4143 4144 // Already checked by by constant evaluator. 4145 if (S.isConstantEvaluated()) 4146 return; 4147 // Check the attributes attached to the method/function itself. 4148 llvm::SmallBitVector NonNullArgs; 4149 if (FDecl) { 4150 // Handle the nonnull attribute on the function/method declaration itself. 4151 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4152 if (!NonNull->args_size()) { 4153 // Easy case: all pointer arguments are nonnull. 4154 for (const auto *Arg : Args) 4155 if (S.isValidPointerAttrType(Arg->getType())) 4156 CheckNonNullArgument(S, Arg, CallSiteLoc); 4157 return; 4158 } 4159 4160 for (const ParamIdx &Idx : NonNull->args()) { 4161 unsigned IdxAST = Idx.getASTIndex(); 4162 if (IdxAST >= Args.size()) 4163 continue; 4164 if (NonNullArgs.empty()) 4165 NonNullArgs.resize(Args.size()); 4166 NonNullArgs.set(IdxAST); 4167 } 4168 } 4169 } 4170 4171 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4172 // Handle the nonnull attribute on the parameters of the 4173 // function/method. 4174 ArrayRef<ParmVarDecl*> parms; 4175 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4176 parms = FD->parameters(); 4177 else 4178 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4179 4180 unsigned ParamIndex = 0; 4181 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4182 I != E; ++I, ++ParamIndex) { 4183 const ParmVarDecl *PVD = *I; 4184 if (PVD->hasAttr<NonNullAttr>() || 4185 isNonNullType(S.Context, PVD->getType())) { 4186 if (NonNullArgs.empty()) 4187 NonNullArgs.resize(Args.size()); 4188 4189 NonNullArgs.set(ParamIndex); 4190 } 4191 } 4192 } else { 4193 // If we have a non-function, non-method declaration but no 4194 // function prototype, try to dig out the function prototype. 4195 if (!Proto) { 4196 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4197 QualType type = VD->getType().getNonReferenceType(); 4198 if (auto pointerType = type->getAs<PointerType>()) 4199 type = pointerType->getPointeeType(); 4200 else if (auto blockType = type->getAs<BlockPointerType>()) 4201 type = blockType->getPointeeType(); 4202 // FIXME: data member pointers? 4203 4204 // Dig out the function prototype, if there is one. 4205 Proto = type->getAs<FunctionProtoType>(); 4206 } 4207 } 4208 4209 // Fill in non-null argument information from the nullability 4210 // information on the parameter types (if we have them). 4211 if (Proto) { 4212 unsigned Index = 0; 4213 for (auto paramType : Proto->getParamTypes()) { 4214 if (isNonNullType(S.Context, paramType)) { 4215 if (NonNullArgs.empty()) 4216 NonNullArgs.resize(Args.size()); 4217 4218 NonNullArgs.set(Index); 4219 } 4220 4221 ++Index; 4222 } 4223 } 4224 } 4225 4226 // Check for non-null arguments. 4227 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4228 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4229 if (NonNullArgs[ArgIndex]) 4230 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4231 } 4232 } 4233 4234 /// Handles the checks for format strings, non-POD arguments to vararg 4235 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4236 /// attributes. 4237 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4238 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4239 bool IsMemberFunction, SourceLocation Loc, 4240 SourceRange Range, VariadicCallType CallType) { 4241 // FIXME: We should check as much as we can in the template definition. 4242 if (CurContext->isDependentContext()) 4243 return; 4244 4245 // Printf and scanf checking. 4246 llvm::SmallBitVector CheckedVarArgs; 4247 if (FDecl) { 4248 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4249 // Only create vector if there are format attributes. 4250 CheckedVarArgs.resize(Args.size()); 4251 4252 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4253 CheckedVarArgs); 4254 } 4255 } 4256 4257 // Refuse POD arguments that weren't caught by the format string 4258 // checks above. 4259 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4260 if (CallType != VariadicDoesNotApply && 4261 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4262 unsigned NumParams = Proto ? Proto->getNumParams() 4263 : FDecl && isa<FunctionDecl>(FDecl) 4264 ? cast<FunctionDecl>(FDecl)->getNumParams() 4265 : FDecl && isa<ObjCMethodDecl>(FDecl) 4266 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4267 : 0; 4268 4269 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4270 // Args[ArgIdx] can be null in malformed code. 4271 if (const Expr *Arg = Args[ArgIdx]) { 4272 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4273 checkVariadicArgument(Arg, CallType); 4274 } 4275 } 4276 } 4277 4278 if (FDecl || Proto) { 4279 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4280 4281 // Type safety checking. 4282 if (FDecl) { 4283 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4284 CheckArgumentWithTypeTag(I, Args, Loc); 4285 } 4286 } 4287 4288 if (FD) 4289 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4290 } 4291 4292 /// CheckConstructorCall - Check a constructor call for correctness and safety 4293 /// properties not enforced by the C type system. 4294 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4295 ArrayRef<const Expr *> Args, 4296 const FunctionProtoType *Proto, 4297 SourceLocation Loc) { 4298 VariadicCallType CallType = 4299 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4300 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4301 Loc, SourceRange(), CallType); 4302 } 4303 4304 /// CheckFunctionCall - Check a direct function call for various correctness 4305 /// and safety properties not strictly enforced by the C type system. 4306 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4307 const FunctionProtoType *Proto) { 4308 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4309 isa<CXXMethodDecl>(FDecl); 4310 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4311 IsMemberOperatorCall; 4312 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4313 TheCall->getCallee()); 4314 Expr** Args = TheCall->getArgs(); 4315 unsigned NumArgs = TheCall->getNumArgs(); 4316 4317 Expr *ImplicitThis = nullptr; 4318 if (IsMemberOperatorCall) { 4319 // If this is a call to a member operator, hide the first argument 4320 // from checkCall. 4321 // FIXME: Our choice of AST representation here is less than ideal. 4322 ImplicitThis = Args[0]; 4323 ++Args; 4324 --NumArgs; 4325 } else if (IsMemberFunction) 4326 ImplicitThis = 4327 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4328 4329 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4330 IsMemberFunction, TheCall->getRParenLoc(), 4331 TheCall->getCallee()->getSourceRange(), CallType); 4332 4333 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4334 // None of the checks below are needed for functions that don't have 4335 // simple names (e.g., C++ conversion functions). 4336 if (!FnInfo) 4337 return false; 4338 4339 CheckAbsoluteValueFunction(TheCall, FDecl); 4340 CheckMaxUnsignedZero(TheCall, FDecl); 4341 4342 if (getLangOpts().ObjC) 4343 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4344 4345 unsigned CMId = FDecl->getMemoryFunctionKind(); 4346 if (CMId == 0) 4347 return false; 4348 4349 // Handle memory setting and copying functions. 4350 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4351 CheckStrlcpycatArguments(TheCall, FnInfo); 4352 else if (CMId == Builtin::BIstrncat) 4353 CheckStrncatArguments(TheCall, FnInfo); 4354 else 4355 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4356 4357 return false; 4358 } 4359 4360 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4361 ArrayRef<const Expr *> Args) { 4362 VariadicCallType CallType = 4363 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4364 4365 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4366 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4367 CallType); 4368 4369 return false; 4370 } 4371 4372 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4373 const FunctionProtoType *Proto) { 4374 QualType Ty; 4375 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4376 Ty = V->getType().getNonReferenceType(); 4377 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4378 Ty = F->getType().getNonReferenceType(); 4379 else 4380 return false; 4381 4382 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4383 !Ty->isFunctionProtoType()) 4384 return false; 4385 4386 VariadicCallType CallType; 4387 if (!Proto || !Proto->isVariadic()) { 4388 CallType = VariadicDoesNotApply; 4389 } else if (Ty->isBlockPointerType()) { 4390 CallType = VariadicBlock; 4391 } else { // Ty->isFunctionPointerType() 4392 CallType = VariadicFunction; 4393 } 4394 4395 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4396 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4397 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4398 TheCall->getCallee()->getSourceRange(), CallType); 4399 4400 return false; 4401 } 4402 4403 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4404 /// such as function pointers returned from functions. 4405 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4406 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4407 TheCall->getCallee()); 4408 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4409 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4410 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4411 TheCall->getCallee()->getSourceRange(), CallType); 4412 4413 return false; 4414 } 4415 4416 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4417 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4418 return false; 4419 4420 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4421 switch (Op) { 4422 case AtomicExpr::AO__c11_atomic_init: 4423 case AtomicExpr::AO__opencl_atomic_init: 4424 llvm_unreachable("There is no ordering argument for an init"); 4425 4426 case AtomicExpr::AO__c11_atomic_load: 4427 case AtomicExpr::AO__opencl_atomic_load: 4428 case AtomicExpr::AO__atomic_load_n: 4429 case AtomicExpr::AO__atomic_load: 4430 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4431 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4432 4433 case AtomicExpr::AO__c11_atomic_store: 4434 case AtomicExpr::AO__opencl_atomic_store: 4435 case AtomicExpr::AO__atomic_store: 4436 case AtomicExpr::AO__atomic_store_n: 4437 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4438 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4439 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4440 4441 default: 4442 return true; 4443 } 4444 } 4445 4446 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4447 AtomicExpr::AtomicOp Op) { 4448 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4449 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4450 4451 // All the non-OpenCL operations take one of the following forms. 4452 // The OpenCL operations take the __c11 forms with one extra argument for 4453 // synchronization scope. 4454 enum { 4455 // C __c11_atomic_init(A *, C) 4456 Init, 4457 4458 // C __c11_atomic_load(A *, int) 4459 Load, 4460 4461 // void __atomic_load(A *, CP, int) 4462 LoadCopy, 4463 4464 // void __atomic_store(A *, CP, int) 4465 Copy, 4466 4467 // C __c11_atomic_add(A *, M, int) 4468 Arithmetic, 4469 4470 // C __atomic_exchange_n(A *, CP, int) 4471 Xchg, 4472 4473 // void __atomic_exchange(A *, C *, CP, int) 4474 GNUXchg, 4475 4476 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4477 C11CmpXchg, 4478 4479 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4480 GNUCmpXchg 4481 } Form = Init; 4482 4483 const unsigned NumForm = GNUCmpXchg + 1; 4484 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4485 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4486 // where: 4487 // C is an appropriate type, 4488 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4489 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4490 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4491 // the int parameters are for orderings. 4492 4493 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4494 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4495 "need to update code for modified forms"); 4496 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4497 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == 4498 AtomicExpr::AO__atomic_load, 4499 "need to update code for modified C11 atomics"); 4500 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4501 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4502 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4503 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) || 4504 IsOpenCL; 4505 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4506 Op == AtomicExpr::AO__atomic_store_n || 4507 Op == AtomicExpr::AO__atomic_exchange_n || 4508 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4509 bool IsAddSub = false; 4510 bool IsMinMax = false; 4511 4512 switch (Op) { 4513 case AtomicExpr::AO__c11_atomic_init: 4514 case AtomicExpr::AO__opencl_atomic_init: 4515 Form = Init; 4516 break; 4517 4518 case AtomicExpr::AO__c11_atomic_load: 4519 case AtomicExpr::AO__opencl_atomic_load: 4520 case AtomicExpr::AO__atomic_load_n: 4521 Form = Load; 4522 break; 4523 4524 case AtomicExpr::AO__atomic_load: 4525 Form = LoadCopy; 4526 break; 4527 4528 case AtomicExpr::AO__c11_atomic_store: 4529 case AtomicExpr::AO__opencl_atomic_store: 4530 case AtomicExpr::AO__atomic_store: 4531 case AtomicExpr::AO__atomic_store_n: 4532 Form = Copy; 4533 break; 4534 4535 case AtomicExpr::AO__c11_atomic_fetch_add: 4536 case AtomicExpr::AO__c11_atomic_fetch_sub: 4537 case AtomicExpr::AO__opencl_atomic_fetch_add: 4538 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4539 case AtomicExpr::AO__opencl_atomic_fetch_min: 4540 case AtomicExpr::AO__opencl_atomic_fetch_max: 4541 case AtomicExpr::AO__atomic_fetch_add: 4542 case AtomicExpr::AO__atomic_fetch_sub: 4543 case AtomicExpr::AO__atomic_add_fetch: 4544 case AtomicExpr::AO__atomic_sub_fetch: 4545 IsAddSub = true; 4546 LLVM_FALLTHROUGH; 4547 case AtomicExpr::AO__c11_atomic_fetch_and: 4548 case AtomicExpr::AO__c11_atomic_fetch_or: 4549 case AtomicExpr::AO__c11_atomic_fetch_xor: 4550 case AtomicExpr::AO__opencl_atomic_fetch_and: 4551 case AtomicExpr::AO__opencl_atomic_fetch_or: 4552 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4553 case AtomicExpr::AO__atomic_fetch_and: 4554 case AtomicExpr::AO__atomic_fetch_or: 4555 case AtomicExpr::AO__atomic_fetch_xor: 4556 case AtomicExpr::AO__atomic_fetch_nand: 4557 case AtomicExpr::AO__atomic_and_fetch: 4558 case AtomicExpr::AO__atomic_or_fetch: 4559 case AtomicExpr::AO__atomic_xor_fetch: 4560 case AtomicExpr::AO__atomic_nand_fetch: 4561 Form = Arithmetic; 4562 break; 4563 4564 case AtomicExpr::AO__atomic_fetch_min: 4565 case AtomicExpr::AO__atomic_fetch_max: 4566 IsMinMax = true; 4567 Form = Arithmetic; 4568 break; 4569 4570 case AtomicExpr::AO__c11_atomic_exchange: 4571 case AtomicExpr::AO__opencl_atomic_exchange: 4572 case AtomicExpr::AO__atomic_exchange_n: 4573 Form = Xchg; 4574 break; 4575 4576 case AtomicExpr::AO__atomic_exchange: 4577 Form = GNUXchg; 4578 break; 4579 4580 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4581 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4582 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4583 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4584 Form = C11CmpXchg; 4585 break; 4586 4587 case AtomicExpr::AO__atomic_compare_exchange: 4588 case AtomicExpr::AO__atomic_compare_exchange_n: 4589 Form = GNUCmpXchg; 4590 break; 4591 } 4592 4593 unsigned AdjustedNumArgs = NumArgs[Form]; 4594 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4595 ++AdjustedNumArgs; 4596 // Check we have the right number of arguments. 4597 if (TheCall->getNumArgs() < AdjustedNumArgs) { 4598 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 4599 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4600 << TheCall->getCallee()->getSourceRange(); 4601 return ExprError(); 4602 } else if (TheCall->getNumArgs() > AdjustedNumArgs) { 4603 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(), 4604 diag::err_typecheck_call_too_many_args) 4605 << 0 << AdjustedNumArgs << TheCall->getNumArgs() 4606 << TheCall->getCallee()->getSourceRange(); 4607 return ExprError(); 4608 } 4609 4610 // Inspect the first argument of the atomic operation. 4611 Expr *Ptr = TheCall->getArg(0); 4612 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4613 if (ConvertedPtr.isInvalid()) 4614 return ExprError(); 4615 4616 Ptr = ConvertedPtr.get(); 4617 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4618 if (!pointerType) { 4619 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4620 << Ptr->getType() << Ptr->getSourceRange(); 4621 return ExprError(); 4622 } 4623 4624 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4625 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4626 QualType ValType = AtomTy; // 'C' 4627 if (IsC11) { 4628 if (!AtomTy->isAtomicType()) { 4629 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic) 4630 << Ptr->getType() << Ptr->getSourceRange(); 4631 return ExprError(); 4632 } 4633 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4634 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4635 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic) 4636 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4637 << Ptr->getSourceRange(); 4638 return ExprError(); 4639 } 4640 ValType = AtomTy->getAs<AtomicType>()->getValueType(); 4641 } else if (Form != Load && Form != LoadCopy) { 4642 if (ValType.isConstQualified()) { 4643 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer) 4644 << Ptr->getType() << Ptr->getSourceRange(); 4645 return ExprError(); 4646 } 4647 } 4648 4649 // For an arithmetic operation, the implied arithmetic must be well-formed. 4650 if (Form == Arithmetic) { 4651 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4652 if (IsAddSub && !ValType->isIntegerType() 4653 && !ValType->isPointerType()) { 4654 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4655 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4656 return ExprError(); 4657 } 4658 if (IsMinMax) { 4659 const BuiltinType *BT = ValType->getAs<BuiltinType>(); 4660 if (!BT || (BT->getKind() != BuiltinType::Int && 4661 BT->getKind() != BuiltinType::UInt)) { 4662 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr); 4663 return ExprError(); 4664 } 4665 } 4666 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) { 4667 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int) 4668 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4669 return ExprError(); 4670 } 4671 if (IsC11 && ValType->isPointerType() && 4672 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4673 diag::err_incomplete_type)) { 4674 return ExprError(); 4675 } 4676 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4677 // For __atomic_*_n operations, the value type must be a scalar integral or 4678 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4679 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4680 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4681 return ExprError(); 4682 } 4683 4684 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4685 !AtomTy->isScalarType()) { 4686 // For GNU atomics, require a trivially-copyable type. This is not part of 4687 // the GNU atomics specification, but we enforce it for sanity. 4688 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy) 4689 << Ptr->getType() << Ptr->getSourceRange(); 4690 return ExprError(); 4691 } 4692 4693 switch (ValType.getObjCLifetime()) { 4694 case Qualifiers::OCL_None: 4695 case Qualifiers::OCL_ExplicitNone: 4696 // okay 4697 break; 4698 4699 case Qualifiers::OCL_Weak: 4700 case Qualifiers::OCL_Strong: 4701 case Qualifiers::OCL_Autoreleasing: 4702 // FIXME: Can this happen? By this point, ValType should be known 4703 // to be trivially copyable. 4704 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4705 << ValType << Ptr->getSourceRange(); 4706 return ExprError(); 4707 } 4708 4709 // All atomic operations have an overload which takes a pointer to a volatile 4710 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4711 // into the result or the other operands. Similarly atomic_load takes a 4712 // pointer to a const 'A'. 4713 ValType.removeLocalVolatile(); 4714 ValType.removeLocalConst(); 4715 QualType ResultType = ValType; 4716 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4717 Form == Init) 4718 ResultType = Context.VoidTy; 4719 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4720 ResultType = Context.BoolTy; 4721 4722 // The type of a parameter passed 'by value'. In the GNU atomics, such 4723 // arguments are actually passed as pointers. 4724 QualType ByValType = ValType; // 'CP' 4725 bool IsPassedByAddress = false; 4726 if (!IsC11 && !IsN) { 4727 ByValType = Ptr->getType(); 4728 IsPassedByAddress = true; 4729 } 4730 4731 // The first argument's non-CV pointer type is used to deduce the type of 4732 // subsequent arguments, except for: 4733 // - weak flag (always converted to bool) 4734 // - memory order (always converted to int) 4735 // - scope (always converted to int) 4736 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 4737 QualType Ty; 4738 if (i < NumVals[Form] + 1) { 4739 switch (i) { 4740 case 0: 4741 // The first argument is always a pointer. It has a fixed type. 4742 // It is always dereferenced, a nullptr is undefined. 4743 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4744 // Nothing else to do: we already know all we want about this pointer. 4745 continue; 4746 case 1: 4747 // The second argument is the non-atomic operand. For arithmetic, this 4748 // is always passed by value, and for a compare_exchange it is always 4749 // passed by address. For the rest, GNU uses by-address and C11 uses 4750 // by-value. 4751 assert(Form != Load); 4752 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4753 Ty = ValType; 4754 else if (Form == Copy || Form == Xchg) { 4755 if (IsPassedByAddress) 4756 // The value pointer is always dereferenced, a nullptr is undefined. 4757 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4758 Ty = ByValType; 4759 } else if (Form == Arithmetic) 4760 Ty = Context.getPointerDiffType(); 4761 else { 4762 Expr *ValArg = TheCall->getArg(i); 4763 // The value pointer is always dereferenced, a nullptr is undefined. 4764 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc()); 4765 LangAS AS = LangAS::Default; 4766 // Keep address space of non-atomic pointer type. 4767 if (const PointerType *PtrTy = 4768 ValArg->getType()->getAs<PointerType>()) { 4769 AS = PtrTy->getPointeeType().getAddressSpace(); 4770 } 4771 Ty = Context.getPointerType( 4772 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4773 } 4774 break; 4775 case 2: 4776 // The third argument to compare_exchange / GNU exchange is the desired 4777 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4778 if (IsPassedByAddress) 4779 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc()); 4780 Ty = ByValType; 4781 break; 4782 case 3: 4783 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4784 Ty = Context.BoolTy; 4785 break; 4786 } 4787 } else { 4788 // The order(s) and scope are always converted to int. 4789 Ty = Context.IntTy; 4790 } 4791 4792 InitializedEntity Entity = 4793 InitializedEntity::InitializeParameter(Context, Ty, false); 4794 ExprResult Arg = TheCall->getArg(i); 4795 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4796 if (Arg.isInvalid()) 4797 return true; 4798 TheCall->setArg(i, Arg.get()); 4799 } 4800 4801 // Permute the arguments into a 'consistent' order. 4802 SmallVector<Expr*, 5> SubExprs; 4803 SubExprs.push_back(Ptr); 4804 switch (Form) { 4805 case Init: 4806 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4807 SubExprs.push_back(TheCall->getArg(1)); // Val1 4808 break; 4809 case Load: 4810 SubExprs.push_back(TheCall->getArg(1)); // Order 4811 break; 4812 case LoadCopy: 4813 case Copy: 4814 case Arithmetic: 4815 case Xchg: 4816 SubExprs.push_back(TheCall->getArg(2)); // Order 4817 SubExprs.push_back(TheCall->getArg(1)); // Val1 4818 break; 4819 case GNUXchg: 4820 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4821 SubExprs.push_back(TheCall->getArg(3)); // Order 4822 SubExprs.push_back(TheCall->getArg(1)); // Val1 4823 SubExprs.push_back(TheCall->getArg(2)); // Val2 4824 break; 4825 case C11CmpXchg: 4826 SubExprs.push_back(TheCall->getArg(3)); // Order 4827 SubExprs.push_back(TheCall->getArg(1)); // Val1 4828 SubExprs.push_back(TheCall->getArg(4)); // OrderFail 4829 SubExprs.push_back(TheCall->getArg(2)); // Val2 4830 break; 4831 case GNUCmpXchg: 4832 SubExprs.push_back(TheCall->getArg(4)); // Order 4833 SubExprs.push_back(TheCall->getArg(1)); // Val1 4834 SubExprs.push_back(TheCall->getArg(5)); // OrderFail 4835 SubExprs.push_back(TheCall->getArg(2)); // Val2 4836 SubExprs.push_back(TheCall->getArg(3)); // Weak 4837 break; 4838 } 4839 4840 if (SubExprs.size() >= 2 && Form != Init) { 4841 llvm::APSInt Result(32); 4842 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4843 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4844 Diag(SubExprs[1]->getBeginLoc(), 4845 diag::warn_atomic_op_has_invalid_memory_order) 4846 << SubExprs[1]->getSourceRange(); 4847 } 4848 4849 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4850 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1); 4851 llvm::APSInt Result(32); 4852 if (Scope->isIntegerConstantExpr(Result, Context) && 4853 !ScopeModel->isValid(Result.getZExtValue())) { 4854 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4855 << Scope->getSourceRange(); 4856 } 4857 SubExprs.push_back(Scope); 4858 } 4859 4860 AtomicExpr *AE = 4861 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs, 4862 ResultType, Op, TheCall->getRParenLoc()); 4863 4864 if ((Op == AtomicExpr::AO__c11_atomic_load || 4865 Op == AtomicExpr::AO__c11_atomic_store || 4866 Op == AtomicExpr::AO__opencl_atomic_load || 4867 Op == AtomicExpr::AO__opencl_atomic_store ) && 4868 Context.AtomicUsesUnsupportedLibcall(AE)) 4869 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4870 << ((Op == AtomicExpr::AO__c11_atomic_load || 4871 Op == AtomicExpr::AO__opencl_atomic_load) 4872 ? 0 4873 : 1); 4874 4875 return AE; 4876 } 4877 4878 /// checkBuiltinArgument - Given a call to a builtin function, perform 4879 /// normal type-checking on the given argument, updating the call in 4880 /// place. This is useful when a builtin function requires custom 4881 /// type-checking for some of its arguments but not necessarily all of 4882 /// them. 4883 /// 4884 /// Returns true on error. 4885 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4886 FunctionDecl *Fn = E->getDirectCallee(); 4887 assert(Fn && "builtin call without direct callee!"); 4888 4889 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4890 InitializedEntity Entity = 4891 InitializedEntity::InitializeParameter(S.Context, Param); 4892 4893 ExprResult Arg = E->getArg(0); 4894 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4895 if (Arg.isInvalid()) 4896 return true; 4897 4898 E->setArg(ArgIndex, Arg.get()); 4899 return false; 4900 } 4901 4902 /// We have a call to a function like __sync_fetch_and_add, which is an 4903 /// overloaded function based on the pointer type of its first argument. 4904 /// The main BuildCallExpr routines have already promoted the types of 4905 /// arguments because all of these calls are prototyped as void(...). 4906 /// 4907 /// This function goes through and does final semantic checking for these 4908 /// builtins, as well as generating any warnings. 4909 ExprResult 4910 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4911 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4912 Expr *Callee = TheCall->getCallee(); 4913 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4914 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4915 4916 // Ensure that we have at least one argument to do type inference from. 4917 if (TheCall->getNumArgs() < 1) { 4918 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4919 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4920 return ExprError(); 4921 } 4922 4923 // Inspect the first argument of the atomic builtin. This should always be 4924 // a pointer type, whose element is an integral scalar or pointer type. 4925 // Because it is a pointer type, we don't have to worry about any implicit 4926 // casts here. 4927 // FIXME: We don't allow floating point scalars as input. 4928 Expr *FirstArg = TheCall->getArg(0); 4929 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4930 if (FirstArgResult.isInvalid()) 4931 return ExprError(); 4932 FirstArg = FirstArgResult.get(); 4933 TheCall->setArg(0, FirstArg); 4934 4935 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4936 if (!pointerType) { 4937 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4938 << FirstArg->getType() << FirstArg->getSourceRange(); 4939 return ExprError(); 4940 } 4941 4942 QualType ValType = pointerType->getPointeeType(); 4943 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4944 !ValType->isBlockPointerType()) { 4945 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4946 << FirstArg->getType() << FirstArg->getSourceRange(); 4947 return ExprError(); 4948 } 4949 4950 if (ValType.isConstQualified()) { 4951 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4952 << FirstArg->getType() << FirstArg->getSourceRange(); 4953 return ExprError(); 4954 } 4955 4956 switch (ValType.getObjCLifetime()) { 4957 case Qualifiers::OCL_None: 4958 case Qualifiers::OCL_ExplicitNone: 4959 // okay 4960 break; 4961 4962 case Qualifiers::OCL_Weak: 4963 case Qualifiers::OCL_Strong: 4964 case Qualifiers::OCL_Autoreleasing: 4965 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4966 << ValType << FirstArg->getSourceRange(); 4967 return ExprError(); 4968 } 4969 4970 // Strip any qualifiers off ValType. 4971 ValType = ValType.getUnqualifiedType(); 4972 4973 // The majority of builtins return a value, but a few have special return 4974 // types, so allow them to override appropriately below. 4975 QualType ResultType = ValType; 4976 4977 // We need to figure out which concrete builtin this maps onto. For example, 4978 // __sync_fetch_and_add with a 2 byte object turns into 4979 // __sync_fetch_and_add_2. 4980 #define BUILTIN_ROW(x) \ 4981 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4982 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4983 4984 static const unsigned BuiltinIndices[][5] = { 4985 BUILTIN_ROW(__sync_fetch_and_add), 4986 BUILTIN_ROW(__sync_fetch_and_sub), 4987 BUILTIN_ROW(__sync_fetch_and_or), 4988 BUILTIN_ROW(__sync_fetch_and_and), 4989 BUILTIN_ROW(__sync_fetch_and_xor), 4990 BUILTIN_ROW(__sync_fetch_and_nand), 4991 4992 BUILTIN_ROW(__sync_add_and_fetch), 4993 BUILTIN_ROW(__sync_sub_and_fetch), 4994 BUILTIN_ROW(__sync_and_and_fetch), 4995 BUILTIN_ROW(__sync_or_and_fetch), 4996 BUILTIN_ROW(__sync_xor_and_fetch), 4997 BUILTIN_ROW(__sync_nand_and_fetch), 4998 4999 BUILTIN_ROW(__sync_val_compare_and_swap), 5000 BUILTIN_ROW(__sync_bool_compare_and_swap), 5001 BUILTIN_ROW(__sync_lock_test_and_set), 5002 BUILTIN_ROW(__sync_lock_release), 5003 BUILTIN_ROW(__sync_swap) 5004 }; 5005 #undef BUILTIN_ROW 5006 5007 // Determine the index of the size. 5008 unsigned SizeIndex; 5009 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5010 case 1: SizeIndex = 0; break; 5011 case 2: SizeIndex = 1; break; 5012 case 4: SizeIndex = 2; break; 5013 case 8: SizeIndex = 3; break; 5014 case 16: SizeIndex = 4; break; 5015 default: 5016 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5017 << FirstArg->getType() << FirstArg->getSourceRange(); 5018 return ExprError(); 5019 } 5020 5021 // Each of these builtins has one pointer argument, followed by some number of 5022 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5023 // that we ignore. Find out which row of BuiltinIndices to read from as well 5024 // as the number of fixed args. 5025 unsigned BuiltinID = FDecl->getBuiltinID(); 5026 unsigned BuiltinIndex, NumFixed = 1; 5027 bool WarnAboutSemanticsChange = false; 5028 switch (BuiltinID) { 5029 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5030 case Builtin::BI__sync_fetch_and_add: 5031 case Builtin::BI__sync_fetch_and_add_1: 5032 case Builtin::BI__sync_fetch_and_add_2: 5033 case Builtin::BI__sync_fetch_and_add_4: 5034 case Builtin::BI__sync_fetch_and_add_8: 5035 case Builtin::BI__sync_fetch_and_add_16: 5036 BuiltinIndex = 0; 5037 break; 5038 5039 case Builtin::BI__sync_fetch_and_sub: 5040 case Builtin::BI__sync_fetch_and_sub_1: 5041 case Builtin::BI__sync_fetch_and_sub_2: 5042 case Builtin::BI__sync_fetch_and_sub_4: 5043 case Builtin::BI__sync_fetch_and_sub_8: 5044 case Builtin::BI__sync_fetch_and_sub_16: 5045 BuiltinIndex = 1; 5046 break; 5047 5048 case Builtin::BI__sync_fetch_and_or: 5049 case Builtin::BI__sync_fetch_and_or_1: 5050 case Builtin::BI__sync_fetch_and_or_2: 5051 case Builtin::BI__sync_fetch_and_or_4: 5052 case Builtin::BI__sync_fetch_and_or_8: 5053 case Builtin::BI__sync_fetch_and_or_16: 5054 BuiltinIndex = 2; 5055 break; 5056 5057 case Builtin::BI__sync_fetch_and_and: 5058 case Builtin::BI__sync_fetch_and_and_1: 5059 case Builtin::BI__sync_fetch_and_and_2: 5060 case Builtin::BI__sync_fetch_and_and_4: 5061 case Builtin::BI__sync_fetch_and_and_8: 5062 case Builtin::BI__sync_fetch_and_and_16: 5063 BuiltinIndex = 3; 5064 break; 5065 5066 case Builtin::BI__sync_fetch_and_xor: 5067 case Builtin::BI__sync_fetch_and_xor_1: 5068 case Builtin::BI__sync_fetch_and_xor_2: 5069 case Builtin::BI__sync_fetch_and_xor_4: 5070 case Builtin::BI__sync_fetch_and_xor_8: 5071 case Builtin::BI__sync_fetch_and_xor_16: 5072 BuiltinIndex = 4; 5073 break; 5074 5075 case Builtin::BI__sync_fetch_and_nand: 5076 case Builtin::BI__sync_fetch_and_nand_1: 5077 case Builtin::BI__sync_fetch_and_nand_2: 5078 case Builtin::BI__sync_fetch_and_nand_4: 5079 case Builtin::BI__sync_fetch_and_nand_8: 5080 case Builtin::BI__sync_fetch_and_nand_16: 5081 BuiltinIndex = 5; 5082 WarnAboutSemanticsChange = true; 5083 break; 5084 5085 case Builtin::BI__sync_add_and_fetch: 5086 case Builtin::BI__sync_add_and_fetch_1: 5087 case Builtin::BI__sync_add_and_fetch_2: 5088 case Builtin::BI__sync_add_and_fetch_4: 5089 case Builtin::BI__sync_add_and_fetch_8: 5090 case Builtin::BI__sync_add_and_fetch_16: 5091 BuiltinIndex = 6; 5092 break; 5093 5094 case Builtin::BI__sync_sub_and_fetch: 5095 case Builtin::BI__sync_sub_and_fetch_1: 5096 case Builtin::BI__sync_sub_and_fetch_2: 5097 case Builtin::BI__sync_sub_and_fetch_4: 5098 case Builtin::BI__sync_sub_and_fetch_8: 5099 case Builtin::BI__sync_sub_and_fetch_16: 5100 BuiltinIndex = 7; 5101 break; 5102 5103 case Builtin::BI__sync_and_and_fetch: 5104 case Builtin::BI__sync_and_and_fetch_1: 5105 case Builtin::BI__sync_and_and_fetch_2: 5106 case Builtin::BI__sync_and_and_fetch_4: 5107 case Builtin::BI__sync_and_and_fetch_8: 5108 case Builtin::BI__sync_and_and_fetch_16: 5109 BuiltinIndex = 8; 5110 break; 5111 5112 case Builtin::BI__sync_or_and_fetch: 5113 case Builtin::BI__sync_or_and_fetch_1: 5114 case Builtin::BI__sync_or_and_fetch_2: 5115 case Builtin::BI__sync_or_and_fetch_4: 5116 case Builtin::BI__sync_or_and_fetch_8: 5117 case Builtin::BI__sync_or_and_fetch_16: 5118 BuiltinIndex = 9; 5119 break; 5120 5121 case Builtin::BI__sync_xor_and_fetch: 5122 case Builtin::BI__sync_xor_and_fetch_1: 5123 case Builtin::BI__sync_xor_and_fetch_2: 5124 case Builtin::BI__sync_xor_and_fetch_4: 5125 case Builtin::BI__sync_xor_and_fetch_8: 5126 case Builtin::BI__sync_xor_and_fetch_16: 5127 BuiltinIndex = 10; 5128 break; 5129 5130 case Builtin::BI__sync_nand_and_fetch: 5131 case Builtin::BI__sync_nand_and_fetch_1: 5132 case Builtin::BI__sync_nand_and_fetch_2: 5133 case Builtin::BI__sync_nand_and_fetch_4: 5134 case Builtin::BI__sync_nand_and_fetch_8: 5135 case Builtin::BI__sync_nand_and_fetch_16: 5136 BuiltinIndex = 11; 5137 WarnAboutSemanticsChange = true; 5138 break; 5139 5140 case Builtin::BI__sync_val_compare_and_swap: 5141 case Builtin::BI__sync_val_compare_and_swap_1: 5142 case Builtin::BI__sync_val_compare_and_swap_2: 5143 case Builtin::BI__sync_val_compare_and_swap_4: 5144 case Builtin::BI__sync_val_compare_and_swap_8: 5145 case Builtin::BI__sync_val_compare_and_swap_16: 5146 BuiltinIndex = 12; 5147 NumFixed = 2; 5148 break; 5149 5150 case Builtin::BI__sync_bool_compare_and_swap: 5151 case Builtin::BI__sync_bool_compare_and_swap_1: 5152 case Builtin::BI__sync_bool_compare_and_swap_2: 5153 case Builtin::BI__sync_bool_compare_and_swap_4: 5154 case Builtin::BI__sync_bool_compare_and_swap_8: 5155 case Builtin::BI__sync_bool_compare_and_swap_16: 5156 BuiltinIndex = 13; 5157 NumFixed = 2; 5158 ResultType = Context.BoolTy; 5159 break; 5160 5161 case Builtin::BI__sync_lock_test_and_set: 5162 case Builtin::BI__sync_lock_test_and_set_1: 5163 case Builtin::BI__sync_lock_test_and_set_2: 5164 case Builtin::BI__sync_lock_test_and_set_4: 5165 case Builtin::BI__sync_lock_test_and_set_8: 5166 case Builtin::BI__sync_lock_test_and_set_16: 5167 BuiltinIndex = 14; 5168 break; 5169 5170 case Builtin::BI__sync_lock_release: 5171 case Builtin::BI__sync_lock_release_1: 5172 case Builtin::BI__sync_lock_release_2: 5173 case Builtin::BI__sync_lock_release_4: 5174 case Builtin::BI__sync_lock_release_8: 5175 case Builtin::BI__sync_lock_release_16: 5176 BuiltinIndex = 15; 5177 NumFixed = 0; 5178 ResultType = Context.VoidTy; 5179 break; 5180 5181 case Builtin::BI__sync_swap: 5182 case Builtin::BI__sync_swap_1: 5183 case Builtin::BI__sync_swap_2: 5184 case Builtin::BI__sync_swap_4: 5185 case Builtin::BI__sync_swap_8: 5186 case Builtin::BI__sync_swap_16: 5187 BuiltinIndex = 16; 5188 break; 5189 } 5190 5191 // Now that we know how many fixed arguments we expect, first check that we 5192 // have at least that many. 5193 if (TheCall->getNumArgs() < 1+NumFixed) { 5194 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5195 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5196 << Callee->getSourceRange(); 5197 return ExprError(); 5198 } 5199 5200 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5201 << Callee->getSourceRange(); 5202 5203 if (WarnAboutSemanticsChange) { 5204 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5205 << Callee->getSourceRange(); 5206 } 5207 5208 // Get the decl for the concrete builtin from this, we can tell what the 5209 // concrete integer type we should convert to is. 5210 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5211 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5212 FunctionDecl *NewBuiltinDecl; 5213 if (NewBuiltinID == BuiltinID) 5214 NewBuiltinDecl = FDecl; 5215 else { 5216 // Perform builtin lookup to avoid redeclaring it. 5217 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5218 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5219 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5220 assert(Res.getFoundDecl()); 5221 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5222 if (!NewBuiltinDecl) 5223 return ExprError(); 5224 } 5225 5226 // The first argument --- the pointer --- has a fixed type; we 5227 // deduce the types of the rest of the arguments accordingly. Walk 5228 // the remaining arguments, converting them to the deduced value type. 5229 for (unsigned i = 0; i != NumFixed; ++i) { 5230 ExprResult Arg = TheCall->getArg(i+1); 5231 5232 // GCC does an implicit conversion to the pointer or integer ValType. This 5233 // can fail in some cases (1i -> int**), check for this error case now. 5234 // Initialize the argument. 5235 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5236 ValType, /*consume*/ false); 5237 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5238 if (Arg.isInvalid()) 5239 return ExprError(); 5240 5241 // Okay, we have something that *can* be converted to the right type. Check 5242 // to see if there is a potentially weird extension going on here. This can 5243 // happen when you do an atomic operation on something like an char* and 5244 // pass in 42. The 42 gets converted to char. This is even more strange 5245 // for things like 45.123 -> char, etc. 5246 // FIXME: Do this check. 5247 TheCall->setArg(i+1, Arg.get()); 5248 } 5249 5250 // Create a new DeclRefExpr to refer to the new decl. 5251 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5252 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5253 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5254 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5255 5256 // Set the callee in the CallExpr. 5257 // FIXME: This loses syntactic information. 5258 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5259 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5260 CK_BuiltinFnToFnPtr); 5261 TheCall->setCallee(PromotedCall.get()); 5262 5263 // Change the result type of the call to match the original value type. This 5264 // is arbitrary, but the codegen for these builtins ins design to handle it 5265 // gracefully. 5266 TheCall->setType(ResultType); 5267 5268 return TheCallResult; 5269 } 5270 5271 /// SemaBuiltinNontemporalOverloaded - We have a call to 5272 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5273 /// overloaded function based on the pointer type of its last argument. 5274 /// 5275 /// This function goes through and does final semantic checking for these 5276 /// builtins. 5277 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5278 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5279 DeclRefExpr *DRE = 5280 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5281 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5282 unsigned BuiltinID = FDecl->getBuiltinID(); 5283 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5284 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5285 "Unexpected nontemporal load/store builtin!"); 5286 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5287 unsigned numArgs = isStore ? 2 : 1; 5288 5289 // Ensure that we have the proper number of arguments. 5290 if (checkArgCount(*this, TheCall, numArgs)) 5291 return ExprError(); 5292 5293 // Inspect the last argument of the nontemporal builtin. This should always 5294 // be a pointer type, from which we imply the type of the memory access. 5295 // Because it is a pointer type, we don't have to worry about any implicit 5296 // casts here. 5297 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5298 ExprResult PointerArgResult = 5299 DefaultFunctionArrayLvalueConversion(PointerArg); 5300 5301 if (PointerArgResult.isInvalid()) 5302 return ExprError(); 5303 PointerArg = PointerArgResult.get(); 5304 TheCall->setArg(numArgs - 1, PointerArg); 5305 5306 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5307 if (!pointerType) { 5308 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5309 << PointerArg->getType() << PointerArg->getSourceRange(); 5310 return ExprError(); 5311 } 5312 5313 QualType ValType = pointerType->getPointeeType(); 5314 5315 // Strip any qualifiers off ValType. 5316 ValType = ValType.getUnqualifiedType(); 5317 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5318 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5319 !ValType->isVectorType()) { 5320 Diag(DRE->getBeginLoc(), 5321 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5322 << PointerArg->getType() << PointerArg->getSourceRange(); 5323 return ExprError(); 5324 } 5325 5326 if (!isStore) { 5327 TheCall->setType(ValType); 5328 return TheCallResult; 5329 } 5330 5331 ExprResult ValArg = TheCall->getArg(0); 5332 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5333 Context, ValType, /*consume*/ false); 5334 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5335 if (ValArg.isInvalid()) 5336 return ExprError(); 5337 5338 TheCall->setArg(0, ValArg.get()); 5339 TheCall->setType(Context.VoidTy); 5340 return TheCallResult; 5341 } 5342 5343 /// CheckObjCString - Checks that the argument to the builtin 5344 /// CFString constructor is correct 5345 /// Note: It might also make sense to do the UTF-16 conversion here (would 5346 /// simplify the backend). 5347 bool Sema::CheckObjCString(Expr *Arg) { 5348 Arg = Arg->IgnoreParenCasts(); 5349 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5350 5351 if (!Literal || !Literal->isAscii()) { 5352 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5353 << Arg->getSourceRange(); 5354 return true; 5355 } 5356 5357 if (Literal->containsNonAsciiOrNull()) { 5358 StringRef String = Literal->getString(); 5359 unsigned NumBytes = String.size(); 5360 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5361 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5362 llvm::UTF16 *ToPtr = &ToBuf[0]; 5363 5364 llvm::ConversionResult Result = 5365 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5366 ToPtr + NumBytes, llvm::strictConversion); 5367 // Check for conversion failure. 5368 if (Result != llvm::conversionOK) 5369 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5370 << Arg->getSourceRange(); 5371 } 5372 return false; 5373 } 5374 5375 /// CheckObjCString - Checks that the format string argument to the os_log() 5376 /// and os_trace() functions is correct, and converts it to const char *. 5377 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5378 Arg = Arg->IgnoreParenCasts(); 5379 auto *Literal = dyn_cast<StringLiteral>(Arg); 5380 if (!Literal) { 5381 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5382 Literal = ObjcLiteral->getString(); 5383 } 5384 } 5385 5386 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5387 return ExprError( 5388 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5389 << Arg->getSourceRange()); 5390 } 5391 5392 ExprResult Result(Literal); 5393 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5394 InitializedEntity Entity = 5395 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5396 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5397 return Result; 5398 } 5399 5400 /// Check that the user is calling the appropriate va_start builtin for the 5401 /// target and calling convention. 5402 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5403 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5404 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5405 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64; 5406 bool IsWindows = TT.isOSWindows(); 5407 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5408 if (IsX64 || IsAArch64) { 5409 CallingConv CC = CC_C; 5410 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5411 CC = FD->getType()->getAs<FunctionType>()->getCallConv(); 5412 if (IsMSVAStart) { 5413 // Don't allow this in System V ABI functions. 5414 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5415 return S.Diag(Fn->getBeginLoc(), 5416 diag::err_ms_va_start_used_in_sysv_function); 5417 } else { 5418 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5419 // On x64 Windows, don't allow this in System V ABI functions. 5420 // (Yes, that means there's no corresponding way to support variadic 5421 // System V ABI functions on Windows.) 5422 if ((IsWindows && CC == CC_X86_64SysV) || 5423 (!IsWindows && CC == CC_Win64)) 5424 return S.Diag(Fn->getBeginLoc(), 5425 diag::err_va_start_used_in_wrong_abi_function) 5426 << !IsWindows; 5427 } 5428 return false; 5429 } 5430 5431 if (IsMSVAStart) 5432 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5433 return false; 5434 } 5435 5436 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5437 ParmVarDecl **LastParam = nullptr) { 5438 // Determine whether the current function, block, or obj-c method is variadic 5439 // and get its parameter list. 5440 bool IsVariadic = false; 5441 ArrayRef<ParmVarDecl *> Params; 5442 DeclContext *Caller = S.CurContext; 5443 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5444 IsVariadic = Block->isVariadic(); 5445 Params = Block->parameters(); 5446 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5447 IsVariadic = FD->isVariadic(); 5448 Params = FD->parameters(); 5449 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5450 IsVariadic = MD->isVariadic(); 5451 // FIXME: This isn't correct for methods (results in bogus warning). 5452 Params = MD->parameters(); 5453 } else if (isa<CapturedDecl>(Caller)) { 5454 // We don't support va_start in a CapturedDecl. 5455 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5456 return true; 5457 } else { 5458 // This must be some other declcontext that parses exprs. 5459 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5460 return true; 5461 } 5462 5463 if (!IsVariadic) { 5464 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5465 return true; 5466 } 5467 5468 if (LastParam) 5469 *LastParam = Params.empty() ? nullptr : Params.back(); 5470 5471 return false; 5472 } 5473 5474 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5475 /// for validity. Emit an error and return true on failure; return false 5476 /// on success. 5477 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5478 Expr *Fn = TheCall->getCallee(); 5479 5480 if (checkVAStartABI(*this, BuiltinID, Fn)) 5481 return true; 5482 5483 if (TheCall->getNumArgs() > 2) { 5484 Diag(TheCall->getArg(2)->getBeginLoc(), 5485 diag::err_typecheck_call_too_many_args) 5486 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5487 << Fn->getSourceRange() 5488 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5489 (*(TheCall->arg_end() - 1))->getEndLoc()); 5490 return true; 5491 } 5492 5493 if (TheCall->getNumArgs() < 2) { 5494 return Diag(TheCall->getEndLoc(), 5495 diag::err_typecheck_call_too_few_args_at_least) 5496 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5497 } 5498 5499 // Type-check the first argument normally. 5500 if (checkBuiltinArgument(*this, TheCall, 0)) 5501 return true; 5502 5503 // Check that the current function is variadic, and get its last parameter. 5504 ParmVarDecl *LastParam; 5505 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5506 return true; 5507 5508 // Verify that the second argument to the builtin is the last argument of the 5509 // current function or method. 5510 bool SecondArgIsLastNamedArgument = false; 5511 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5512 5513 // These are valid if SecondArgIsLastNamedArgument is false after the next 5514 // block. 5515 QualType Type; 5516 SourceLocation ParamLoc; 5517 bool IsCRegister = false; 5518 5519 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5520 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5521 SecondArgIsLastNamedArgument = PV == LastParam; 5522 5523 Type = PV->getType(); 5524 ParamLoc = PV->getLocation(); 5525 IsCRegister = 5526 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5527 } 5528 } 5529 5530 if (!SecondArgIsLastNamedArgument) 5531 Diag(TheCall->getArg(1)->getBeginLoc(), 5532 diag::warn_second_arg_of_va_start_not_last_named_param); 5533 else if (IsCRegister || Type->isReferenceType() || 5534 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5535 // Promotable integers are UB, but enumerations need a bit of 5536 // extra checking to see what their promotable type actually is. 5537 if (!Type->isPromotableIntegerType()) 5538 return false; 5539 if (!Type->isEnumeralType()) 5540 return true; 5541 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl(); 5542 return !(ED && 5543 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5544 }()) { 5545 unsigned Reason = 0; 5546 if (Type->isReferenceType()) Reason = 1; 5547 else if (IsCRegister) Reason = 2; 5548 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5549 Diag(ParamLoc, diag::note_parameter_type) << Type; 5550 } 5551 5552 TheCall->setType(Context.VoidTy); 5553 return false; 5554 } 5555 5556 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5557 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5558 // const char *named_addr); 5559 5560 Expr *Func = Call->getCallee(); 5561 5562 if (Call->getNumArgs() < 3) 5563 return Diag(Call->getEndLoc(), 5564 diag::err_typecheck_call_too_few_args_at_least) 5565 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5566 5567 // Type-check the first argument normally. 5568 if (checkBuiltinArgument(*this, Call, 0)) 5569 return true; 5570 5571 // Check that the current function is variadic. 5572 if (checkVAStartIsInVariadicFunction(*this, Func)) 5573 return true; 5574 5575 // __va_start on Windows does not validate the parameter qualifiers 5576 5577 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5578 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5579 5580 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5581 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5582 5583 const QualType &ConstCharPtrTy = 5584 Context.getPointerType(Context.CharTy.withConst()); 5585 if (!Arg1Ty->isPointerType() || 5586 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5587 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5588 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5589 << 0 /* qualifier difference */ 5590 << 3 /* parameter mismatch */ 5591 << 2 << Arg1->getType() << ConstCharPtrTy; 5592 5593 const QualType SizeTy = Context.getSizeType(); 5594 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5595 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5596 << Arg2->getType() << SizeTy << 1 /* different class */ 5597 << 0 /* qualifier difference */ 5598 << 3 /* parameter mismatch */ 5599 << 3 << Arg2->getType() << SizeTy; 5600 5601 return false; 5602 } 5603 5604 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5605 /// friends. This is declared to take (...), so we have to check everything. 5606 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5607 if (TheCall->getNumArgs() < 2) 5608 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5609 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5610 if (TheCall->getNumArgs() > 2) 5611 return Diag(TheCall->getArg(2)->getBeginLoc(), 5612 diag::err_typecheck_call_too_many_args) 5613 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5614 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5615 (*(TheCall->arg_end() - 1))->getEndLoc()); 5616 5617 ExprResult OrigArg0 = TheCall->getArg(0); 5618 ExprResult OrigArg1 = TheCall->getArg(1); 5619 5620 // Do standard promotions between the two arguments, returning their common 5621 // type. 5622 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false); 5623 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5624 return true; 5625 5626 // Make sure any conversions are pushed back into the call; this is 5627 // type safe since unordered compare builtins are declared as "_Bool 5628 // foo(...)". 5629 TheCall->setArg(0, OrigArg0.get()); 5630 TheCall->setArg(1, OrigArg1.get()); 5631 5632 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5633 return false; 5634 5635 // If the common type isn't a real floating type, then the arguments were 5636 // invalid for this operation. 5637 if (Res.isNull() || !Res->isRealFloatingType()) 5638 return Diag(OrigArg0.get()->getBeginLoc(), 5639 diag::err_typecheck_call_invalid_ordered_compare) 5640 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5641 << SourceRange(OrigArg0.get()->getBeginLoc(), 5642 OrigArg1.get()->getEndLoc()); 5643 5644 return false; 5645 } 5646 5647 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5648 /// __builtin_isnan and friends. This is declared to take (...), so we have 5649 /// to check everything. We expect the last argument to be a floating point 5650 /// value. 5651 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5652 if (TheCall->getNumArgs() < NumArgs) 5653 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5654 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5655 if (TheCall->getNumArgs() > NumArgs) 5656 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5657 diag::err_typecheck_call_too_many_args) 5658 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5659 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5660 (*(TheCall->arg_end() - 1))->getEndLoc()); 5661 5662 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5663 5664 if (OrigArg->isTypeDependent()) 5665 return false; 5666 5667 // This operation requires a non-_Complex floating-point number. 5668 if (!OrigArg->getType()->isRealFloatingType()) 5669 return Diag(OrigArg->getBeginLoc(), 5670 diag::err_typecheck_call_invalid_unary_fp) 5671 << OrigArg->getType() << OrigArg->getSourceRange(); 5672 5673 // If this is an implicit conversion from float -> float, double, or 5674 // long double, remove it. 5675 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) { 5676 // Only remove standard FloatCasts, leaving other casts inplace 5677 if (Cast->getCastKind() == CK_FloatingCast) { 5678 Expr *CastArg = Cast->getSubExpr(); 5679 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) { 5680 assert( 5681 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) || 5682 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) || 5683 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) && 5684 "promotion from float to either float, double, or long double is " 5685 "the only expected cast here"); 5686 Cast->setSubExpr(nullptr); 5687 TheCall->setArg(NumArgs-1, CastArg); 5688 } 5689 } 5690 } 5691 5692 return false; 5693 } 5694 5695 // Customized Sema Checking for VSX builtins that have the following signature: 5696 // vector [...] builtinName(vector [...], vector [...], const int); 5697 // Which takes the same type of vectors (any legal vector type) for the first 5698 // two arguments and takes compile time constant for the third argument. 5699 // Example builtins are : 5700 // vector double vec_xxpermdi(vector double, vector double, int); 5701 // vector short vec_xxsldwi(vector short, vector short, int); 5702 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5703 unsigned ExpectedNumArgs = 3; 5704 if (TheCall->getNumArgs() < ExpectedNumArgs) 5705 return Diag(TheCall->getEndLoc(), 5706 diag::err_typecheck_call_too_few_args_at_least) 5707 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5708 << TheCall->getSourceRange(); 5709 5710 if (TheCall->getNumArgs() > ExpectedNumArgs) 5711 return Diag(TheCall->getEndLoc(), 5712 diag::err_typecheck_call_too_many_args_at_most) 5713 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5714 << TheCall->getSourceRange(); 5715 5716 // Check the third argument is a compile time constant 5717 llvm::APSInt Value; 5718 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5719 return Diag(TheCall->getBeginLoc(), 5720 diag::err_vsx_builtin_nonconstant_argument) 5721 << 3 /* argument index */ << TheCall->getDirectCallee() 5722 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5723 TheCall->getArg(2)->getEndLoc()); 5724 5725 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5726 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5727 5728 // Check the type of argument 1 and argument 2 are vectors. 5729 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5730 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5731 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5732 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5733 << TheCall->getDirectCallee() 5734 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5735 TheCall->getArg(1)->getEndLoc()); 5736 } 5737 5738 // Check the first two arguments are the same type. 5739 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5740 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5741 << TheCall->getDirectCallee() 5742 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5743 TheCall->getArg(1)->getEndLoc()); 5744 } 5745 5746 // When default clang type checking is turned off and the customized type 5747 // checking is used, the returning type of the function must be explicitly 5748 // set. Otherwise it is _Bool by default. 5749 TheCall->setType(Arg1Ty); 5750 5751 return false; 5752 } 5753 5754 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5755 // This is declared to take (...), so we have to check everything. 5756 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5757 if (TheCall->getNumArgs() < 2) 5758 return ExprError(Diag(TheCall->getEndLoc(), 5759 diag::err_typecheck_call_too_few_args_at_least) 5760 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5761 << TheCall->getSourceRange()); 5762 5763 // Determine which of the following types of shufflevector we're checking: 5764 // 1) unary, vector mask: (lhs, mask) 5765 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5766 QualType resType = TheCall->getArg(0)->getType(); 5767 unsigned numElements = 0; 5768 5769 if (!TheCall->getArg(0)->isTypeDependent() && 5770 !TheCall->getArg(1)->isTypeDependent()) { 5771 QualType LHSType = TheCall->getArg(0)->getType(); 5772 QualType RHSType = TheCall->getArg(1)->getType(); 5773 5774 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5775 return ExprError( 5776 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5777 << TheCall->getDirectCallee() 5778 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5779 TheCall->getArg(1)->getEndLoc())); 5780 5781 numElements = LHSType->getAs<VectorType>()->getNumElements(); 5782 unsigned numResElements = TheCall->getNumArgs() - 2; 5783 5784 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5785 // with mask. If so, verify that RHS is an integer vector type with the 5786 // same number of elts as lhs. 5787 if (TheCall->getNumArgs() == 2) { 5788 if (!RHSType->hasIntegerRepresentation() || 5789 RHSType->getAs<VectorType>()->getNumElements() != numElements) 5790 return ExprError(Diag(TheCall->getBeginLoc(), 5791 diag::err_vec_builtin_incompatible_vector) 5792 << TheCall->getDirectCallee() 5793 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5794 TheCall->getArg(1)->getEndLoc())); 5795 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5796 return ExprError(Diag(TheCall->getBeginLoc(), 5797 diag::err_vec_builtin_incompatible_vector) 5798 << TheCall->getDirectCallee() 5799 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5800 TheCall->getArg(1)->getEndLoc())); 5801 } else if (numElements != numResElements) { 5802 QualType eltType = LHSType->getAs<VectorType>()->getElementType(); 5803 resType = Context.getVectorType(eltType, numResElements, 5804 VectorType::GenericVector); 5805 } 5806 } 5807 5808 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5809 if (TheCall->getArg(i)->isTypeDependent() || 5810 TheCall->getArg(i)->isValueDependent()) 5811 continue; 5812 5813 llvm::APSInt Result(32); 5814 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5815 return ExprError(Diag(TheCall->getBeginLoc(), 5816 diag::err_shufflevector_nonconstant_argument) 5817 << TheCall->getArg(i)->getSourceRange()); 5818 5819 // Allow -1 which will be translated to undef in the IR. 5820 if (Result.isSigned() && Result.isAllOnesValue()) 5821 continue; 5822 5823 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5824 return ExprError(Diag(TheCall->getBeginLoc(), 5825 diag::err_shufflevector_argument_too_large) 5826 << TheCall->getArg(i)->getSourceRange()); 5827 } 5828 5829 SmallVector<Expr*, 32> exprs; 5830 5831 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5832 exprs.push_back(TheCall->getArg(i)); 5833 TheCall->setArg(i, nullptr); 5834 } 5835 5836 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5837 TheCall->getCallee()->getBeginLoc(), 5838 TheCall->getRParenLoc()); 5839 } 5840 5841 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5842 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5843 SourceLocation BuiltinLoc, 5844 SourceLocation RParenLoc) { 5845 ExprValueKind VK = VK_RValue; 5846 ExprObjectKind OK = OK_Ordinary; 5847 QualType DstTy = TInfo->getType(); 5848 QualType SrcTy = E->getType(); 5849 5850 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5851 return ExprError(Diag(BuiltinLoc, 5852 diag::err_convertvector_non_vector) 5853 << E->getSourceRange()); 5854 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5855 return ExprError(Diag(BuiltinLoc, 5856 diag::err_convertvector_non_vector_type)); 5857 5858 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5859 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements(); 5860 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements(); 5861 if (SrcElts != DstElts) 5862 return ExprError(Diag(BuiltinLoc, 5863 diag::err_convertvector_incompatible_vector) 5864 << E->getSourceRange()); 5865 } 5866 5867 return new (Context) 5868 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5869 } 5870 5871 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5872 // This is declared to take (const void*, ...) and can take two 5873 // optional constant int args. 5874 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5875 unsigned NumArgs = TheCall->getNumArgs(); 5876 5877 if (NumArgs > 3) 5878 return Diag(TheCall->getEndLoc(), 5879 diag::err_typecheck_call_too_many_args_at_most) 5880 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5881 5882 // Argument 0 is checked for us and the remaining arguments must be 5883 // constant integers. 5884 for (unsigned i = 1; i != NumArgs; ++i) 5885 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5886 return true; 5887 5888 return false; 5889 } 5890 5891 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5892 // __assume does not evaluate its arguments, and should warn if its argument 5893 // has side effects. 5894 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5895 Expr *Arg = TheCall->getArg(0); 5896 if (Arg->isInstantiationDependent()) return false; 5897 5898 if (Arg->HasSideEffects(Context)) 5899 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5900 << Arg->getSourceRange() 5901 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5902 5903 return false; 5904 } 5905 5906 /// Handle __builtin_alloca_with_align. This is declared 5907 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5908 /// than 8. 5909 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5910 // The alignment must be a constant integer. 5911 Expr *Arg = TheCall->getArg(1); 5912 5913 // We can't check the value of a dependent argument. 5914 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5915 if (const auto *UE = 5916 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5917 if (UE->getKind() == UETT_AlignOf || 5918 UE->getKind() == UETT_PreferredAlignOf) 5919 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5920 << Arg->getSourceRange(); 5921 5922 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5923 5924 if (!Result.isPowerOf2()) 5925 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5926 << Arg->getSourceRange(); 5927 5928 if (Result < Context.getCharWidth()) 5929 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5930 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5931 5932 if (Result > std::numeric_limits<int32_t>::max()) 5933 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5934 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5935 } 5936 5937 return false; 5938 } 5939 5940 /// Handle __builtin_assume_aligned. This is declared 5941 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5942 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5943 unsigned NumArgs = TheCall->getNumArgs(); 5944 5945 if (NumArgs > 3) 5946 return Diag(TheCall->getEndLoc(), 5947 diag::err_typecheck_call_too_many_args_at_most) 5948 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5949 5950 // The alignment must be a constant integer. 5951 Expr *Arg = TheCall->getArg(1); 5952 5953 // We can't check the value of a dependent argument. 5954 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5955 llvm::APSInt Result; 5956 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5957 return true; 5958 5959 if (!Result.isPowerOf2()) 5960 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5961 << Arg->getSourceRange(); 5962 } 5963 5964 if (NumArgs > 2) { 5965 ExprResult Arg(TheCall->getArg(2)); 5966 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5967 Context.getSizeType(), false); 5968 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5969 if (Arg.isInvalid()) return true; 5970 TheCall->setArg(2, Arg.get()); 5971 } 5972 5973 return false; 5974 } 5975 5976 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5977 unsigned BuiltinID = 5978 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5979 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5980 5981 unsigned NumArgs = TheCall->getNumArgs(); 5982 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5983 if (NumArgs < NumRequiredArgs) { 5984 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5985 << 0 /* function call */ << NumRequiredArgs << NumArgs 5986 << TheCall->getSourceRange(); 5987 } 5988 if (NumArgs >= NumRequiredArgs + 0x100) { 5989 return Diag(TheCall->getEndLoc(), 5990 diag::err_typecheck_call_too_many_args_at_most) 5991 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5992 << TheCall->getSourceRange(); 5993 } 5994 unsigned i = 0; 5995 5996 // For formatting call, check buffer arg. 5997 if (!IsSizeCall) { 5998 ExprResult Arg(TheCall->getArg(i)); 5999 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6000 Context, Context.VoidPtrTy, false); 6001 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6002 if (Arg.isInvalid()) 6003 return true; 6004 TheCall->setArg(i, Arg.get()); 6005 i++; 6006 } 6007 6008 // Check string literal arg. 6009 unsigned FormatIdx = i; 6010 { 6011 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6012 if (Arg.isInvalid()) 6013 return true; 6014 TheCall->setArg(i, Arg.get()); 6015 i++; 6016 } 6017 6018 // Make sure variadic args are scalar. 6019 unsigned FirstDataArg = i; 6020 while (i < NumArgs) { 6021 ExprResult Arg = DefaultVariadicArgumentPromotion( 6022 TheCall->getArg(i), VariadicFunction, nullptr); 6023 if (Arg.isInvalid()) 6024 return true; 6025 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6026 if (ArgSize.getQuantity() >= 0x100) { 6027 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6028 << i << (int)ArgSize.getQuantity() << 0xff 6029 << TheCall->getSourceRange(); 6030 } 6031 TheCall->setArg(i, Arg.get()); 6032 i++; 6033 } 6034 6035 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6036 // call to avoid duplicate diagnostics. 6037 if (!IsSizeCall) { 6038 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6039 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6040 bool Success = CheckFormatArguments( 6041 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6042 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6043 CheckedVarArgs); 6044 if (!Success) 6045 return true; 6046 } 6047 6048 if (IsSizeCall) { 6049 TheCall->setType(Context.getSizeType()); 6050 } else { 6051 TheCall->setType(Context.VoidPtrTy); 6052 } 6053 return false; 6054 } 6055 6056 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6057 /// TheCall is a constant expression. 6058 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6059 llvm::APSInt &Result) { 6060 Expr *Arg = TheCall->getArg(ArgNum); 6061 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6062 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6063 6064 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6065 6066 if (!Arg->isIntegerConstantExpr(Result, Context)) 6067 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6068 << FDecl->getDeclName() << Arg->getSourceRange(); 6069 6070 return false; 6071 } 6072 6073 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6074 /// TheCall is a constant expression in the range [Low, High]. 6075 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6076 int Low, int High, bool RangeIsError) { 6077 if (isConstantEvaluated()) 6078 return false; 6079 llvm::APSInt Result; 6080 6081 // We can't check the value of a dependent argument. 6082 Expr *Arg = TheCall->getArg(ArgNum); 6083 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6084 return false; 6085 6086 // Check constant-ness first. 6087 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6088 return true; 6089 6090 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6091 if (RangeIsError) 6092 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6093 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6094 else 6095 // Defer the warning until we know if the code will be emitted so that 6096 // dead code can ignore this. 6097 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6098 PDiag(diag::warn_argument_invalid_range) 6099 << Result.toString(10) << Low << High 6100 << Arg->getSourceRange()); 6101 } 6102 6103 return false; 6104 } 6105 6106 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6107 /// TheCall is a constant expression is a multiple of Num.. 6108 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6109 unsigned Num) { 6110 llvm::APSInt Result; 6111 6112 // We can't check the value of a dependent argument. 6113 Expr *Arg = TheCall->getArg(ArgNum); 6114 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6115 return false; 6116 6117 // Check constant-ness first. 6118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6119 return true; 6120 6121 if (Result.getSExtValue() % Num != 0) 6122 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6123 << Num << Arg->getSourceRange(); 6124 6125 return false; 6126 } 6127 6128 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6129 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6130 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6131 if (checkArgCount(*this, TheCall, 2)) 6132 return true; 6133 Expr *Arg0 = TheCall->getArg(0); 6134 Expr *Arg1 = TheCall->getArg(1); 6135 6136 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6137 if (FirstArg.isInvalid()) 6138 return true; 6139 QualType FirstArgType = FirstArg.get()->getType(); 6140 if (!FirstArgType->isAnyPointerType()) 6141 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6142 << "first" << FirstArgType << Arg0->getSourceRange(); 6143 TheCall->setArg(0, FirstArg.get()); 6144 6145 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6146 if (SecArg.isInvalid()) 6147 return true; 6148 QualType SecArgType = SecArg.get()->getType(); 6149 if (!SecArgType->isIntegerType()) 6150 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6151 << "second" << SecArgType << Arg1->getSourceRange(); 6152 6153 // Derive the return type from the pointer argument. 6154 TheCall->setType(FirstArgType); 6155 return false; 6156 } 6157 6158 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6159 if (checkArgCount(*this, TheCall, 2)) 6160 return true; 6161 6162 Expr *Arg0 = TheCall->getArg(0); 6163 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6164 if (FirstArg.isInvalid()) 6165 return true; 6166 QualType FirstArgType = FirstArg.get()->getType(); 6167 if (!FirstArgType->isAnyPointerType()) 6168 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6169 << "first" << FirstArgType << Arg0->getSourceRange(); 6170 TheCall->setArg(0, FirstArg.get()); 6171 6172 // Derive the return type from the pointer argument. 6173 TheCall->setType(FirstArgType); 6174 6175 // Second arg must be an constant in range [0,15] 6176 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6177 } 6178 6179 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6180 if (checkArgCount(*this, TheCall, 2)) 6181 return true; 6182 Expr *Arg0 = TheCall->getArg(0); 6183 Expr *Arg1 = TheCall->getArg(1); 6184 6185 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6186 if (FirstArg.isInvalid()) 6187 return true; 6188 QualType FirstArgType = FirstArg.get()->getType(); 6189 if (!FirstArgType->isAnyPointerType()) 6190 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6191 << "first" << FirstArgType << Arg0->getSourceRange(); 6192 6193 QualType SecArgType = Arg1->getType(); 6194 if (!SecArgType->isIntegerType()) 6195 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6196 << "second" << SecArgType << Arg1->getSourceRange(); 6197 TheCall->setType(Context.IntTy); 6198 return false; 6199 } 6200 6201 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6202 BuiltinID == AArch64::BI__builtin_arm_stg) { 6203 if (checkArgCount(*this, TheCall, 1)) 6204 return true; 6205 Expr *Arg0 = TheCall->getArg(0); 6206 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6207 if (FirstArg.isInvalid()) 6208 return true; 6209 6210 QualType FirstArgType = FirstArg.get()->getType(); 6211 if (!FirstArgType->isAnyPointerType()) 6212 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6213 << "first" << FirstArgType << Arg0->getSourceRange(); 6214 TheCall->setArg(0, FirstArg.get()); 6215 6216 // Derive the return type from the pointer argument. 6217 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6218 TheCall->setType(FirstArgType); 6219 return false; 6220 } 6221 6222 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6223 Expr *ArgA = TheCall->getArg(0); 6224 Expr *ArgB = TheCall->getArg(1); 6225 6226 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6227 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6228 6229 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6230 return true; 6231 6232 QualType ArgTypeA = ArgExprA.get()->getType(); 6233 QualType ArgTypeB = ArgExprB.get()->getType(); 6234 6235 auto isNull = [&] (Expr *E) -> bool { 6236 return E->isNullPointerConstant( 6237 Context, Expr::NPC_ValueDependentIsNotNull); }; 6238 6239 // argument should be either a pointer or null 6240 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6241 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6242 << "first" << ArgTypeA << ArgA->getSourceRange(); 6243 6244 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6245 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6246 << "second" << ArgTypeB << ArgB->getSourceRange(); 6247 6248 // Ensure Pointee types are compatible 6249 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6250 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6251 QualType pointeeA = ArgTypeA->getPointeeType(); 6252 QualType pointeeB = ArgTypeB->getPointeeType(); 6253 if (!Context.typesAreCompatible( 6254 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6255 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6256 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6257 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6258 << ArgB->getSourceRange(); 6259 } 6260 } 6261 6262 // at least one argument should be pointer type 6263 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6264 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6265 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6266 6267 if (isNull(ArgA)) // adopt type of the other pointer 6268 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6269 6270 if (isNull(ArgB)) 6271 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6272 6273 TheCall->setArg(0, ArgExprA.get()); 6274 TheCall->setArg(1, ArgExprB.get()); 6275 TheCall->setType(Context.LongLongTy); 6276 return false; 6277 } 6278 assert(false && "Unhandled ARM MTE intrinsic"); 6279 return true; 6280 } 6281 6282 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6283 /// TheCall is an ARM/AArch64 special register string literal. 6284 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6285 int ArgNum, unsigned ExpectedFieldNum, 6286 bool AllowName) { 6287 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6288 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6289 BuiltinID == ARM::BI__builtin_arm_rsr || 6290 BuiltinID == ARM::BI__builtin_arm_rsrp || 6291 BuiltinID == ARM::BI__builtin_arm_wsr || 6292 BuiltinID == ARM::BI__builtin_arm_wsrp; 6293 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6294 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6295 BuiltinID == AArch64::BI__builtin_arm_rsr || 6296 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6297 BuiltinID == AArch64::BI__builtin_arm_wsr || 6298 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6299 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6300 6301 // We can't check the value of a dependent argument. 6302 Expr *Arg = TheCall->getArg(ArgNum); 6303 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6304 return false; 6305 6306 // Check if the argument is a string literal. 6307 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6308 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6309 << Arg->getSourceRange(); 6310 6311 // Check the type of special register given. 6312 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6313 SmallVector<StringRef, 6> Fields; 6314 Reg.split(Fields, ":"); 6315 6316 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6317 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6318 << Arg->getSourceRange(); 6319 6320 // If the string is the name of a register then we cannot check that it is 6321 // valid here but if the string is of one the forms described in ACLE then we 6322 // can check that the supplied fields are integers and within the valid 6323 // ranges. 6324 if (Fields.size() > 1) { 6325 bool FiveFields = Fields.size() == 5; 6326 6327 bool ValidString = true; 6328 if (IsARMBuiltin) { 6329 ValidString &= Fields[0].startswith_lower("cp") || 6330 Fields[0].startswith_lower("p"); 6331 if (ValidString) 6332 Fields[0] = 6333 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6334 6335 ValidString &= Fields[2].startswith_lower("c"); 6336 if (ValidString) 6337 Fields[2] = Fields[2].drop_front(1); 6338 6339 if (FiveFields) { 6340 ValidString &= Fields[3].startswith_lower("c"); 6341 if (ValidString) 6342 Fields[3] = Fields[3].drop_front(1); 6343 } 6344 } 6345 6346 SmallVector<int, 5> Ranges; 6347 if (FiveFields) 6348 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6349 else 6350 Ranges.append({15, 7, 15}); 6351 6352 for (unsigned i=0; i<Fields.size(); ++i) { 6353 int IntField; 6354 ValidString &= !Fields[i].getAsInteger(10, IntField); 6355 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6356 } 6357 6358 if (!ValidString) 6359 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6360 << Arg->getSourceRange(); 6361 } else if (IsAArch64Builtin && Fields.size() == 1) { 6362 // If the register name is one of those that appear in the condition below 6363 // and the special register builtin being used is one of the write builtins, 6364 // then we require that the argument provided for writing to the register 6365 // is an integer constant expression. This is because it will be lowered to 6366 // an MSR (immediate) instruction, so we need to know the immediate at 6367 // compile time. 6368 if (TheCall->getNumArgs() != 2) 6369 return false; 6370 6371 std::string RegLower = Reg.lower(); 6372 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6373 RegLower != "pan" && RegLower != "uao") 6374 return false; 6375 6376 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6377 } 6378 6379 return false; 6380 } 6381 6382 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6383 /// This checks that the target supports __builtin_longjmp and 6384 /// that val is a constant 1. 6385 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6386 if (!Context.getTargetInfo().hasSjLjLowering()) 6387 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6388 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6389 6390 Expr *Arg = TheCall->getArg(1); 6391 llvm::APSInt Result; 6392 6393 // TODO: This is less than ideal. Overload this to take a value. 6394 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6395 return true; 6396 6397 if (Result != 1) 6398 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6399 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6400 6401 return false; 6402 } 6403 6404 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6405 /// This checks that the target supports __builtin_setjmp. 6406 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6407 if (!Context.getTargetInfo().hasSjLjLowering()) 6408 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6409 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6410 return false; 6411 } 6412 6413 namespace { 6414 6415 class UncoveredArgHandler { 6416 enum { Unknown = -1, AllCovered = -2 }; 6417 6418 signed FirstUncoveredArg = Unknown; 6419 SmallVector<const Expr *, 4> DiagnosticExprs; 6420 6421 public: 6422 UncoveredArgHandler() = default; 6423 6424 bool hasUncoveredArg() const { 6425 return (FirstUncoveredArg >= 0); 6426 } 6427 6428 unsigned getUncoveredArg() const { 6429 assert(hasUncoveredArg() && "no uncovered argument"); 6430 return FirstUncoveredArg; 6431 } 6432 6433 void setAllCovered() { 6434 // A string has been found with all arguments covered, so clear out 6435 // the diagnostics. 6436 DiagnosticExprs.clear(); 6437 FirstUncoveredArg = AllCovered; 6438 } 6439 6440 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6441 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6442 6443 // Don't update if a previous string covers all arguments. 6444 if (FirstUncoveredArg == AllCovered) 6445 return; 6446 6447 // UncoveredArgHandler tracks the highest uncovered argument index 6448 // and with it all the strings that match this index. 6449 if (NewFirstUncoveredArg == FirstUncoveredArg) 6450 DiagnosticExprs.push_back(StrExpr); 6451 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6452 DiagnosticExprs.clear(); 6453 DiagnosticExprs.push_back(StrExpr); 6454 FirstUncoveredArg = NewFirstUncoveredArg; 6455 } 6456 } 6457 6458 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6459 }; 6460 6461 enum StringLiteralCheckType { 6462 SLCT_NotALiteral, 6463 SLCT_UncheckedLiteral, 6464 SLCT_CheckedLiteral 6465 }; 6466 6467 } // namespace 6468 6469 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6470 BinaryOperatorKind BinOpKind, 6471 bool AddendIsRight) { 6472 unsigned BitWidth = Offset.getBitWidth(); 6473 unsigned AddendBitWidth = Addend.getBitWidth(); 6474 // There might be negative interim results. 6475 if (Addend.isUnsigned()) { 6476 Addend = Addend.zext(++AddendBitWidth); 6477 Addend.setIsSigned(true); 6478 } 6479 // Adjust the bit width of the APSInts. 6480 if (AddendBitWidth > BitWidth) { 6481 Offset = Offset.sext(AddendBitWidth); 6482 BitWidth = AddendBitWidth; 6483 } else if (BitWidth > AddendBitWidth) { 6484 Addend = Addend.sext(BitWidth); 6485 } 6486 6487 bool Ov = false; 6488 llvm::APSInt ResOffset = Offset; 6489 if (BinOpKind == BO_Add) 6490 ResOffset = Offset.sadd_ov(Addend, Ov); 6491 else { 6492 assert(AddendIsRight && BinOpKind == BO_Sub && 6493 "operator must be add or sub with addend on the right"); 6494 ResOffset = Offset.ssub_ov(Addend, Ov); 6495 } 6496 6497 // We add an offset to a pointer here so we should support an offset as big as 6498 // possible. 6499 if (Ov) { 6500 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6501 "index (intermediate) result too big"); 6502 Offset = Offset.sext(2 * BitWidth); 6503 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6504 return; 6505 } 6506 6507 Offset = ResOffset; 6508 } 6509 6510 namespace { 6511 6512 // This is a wrapper class around StringLiteral to support offsetted string 6513 // literals as format strings. It takes the offset into account when returning 6514 // the string and its length or the source locations to display notes correctly. 6515 class FormatStringLiteral { 6516 const StringLiteral *FExpr; 6517 int64_t Offset; 6518 6519 public: 6520 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6521 : FExpr(fexpr), Offset(Offset) {} 6522 6523 StringRef getString() const { 6524 return FExpr->getString().drop_front(Offset); 6525 } 6526 6527 unsigned getByteLength() const { 6528 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6529 } 6530 6531 unsigned getLength() const { return FExpr->getLength() - Offset; } 6532 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6533 6534 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6535 6536 QualType getType() const { return FExpr->getType(); } 6537 6538 bool isAscii() const { return FExpr->isAscii(); } 6539 bool isWide() const { return FExpr->isWide(); } 6540 bool isUTF8() const { return FExpr->isUTF8(); } 6541 bool isUTF16() const { return FExpr->isUTF16(); } 6542 bool isUTF32() const { return FExpr->isUTF32(); } 6543 bool isPascal() const { return FExpr->isPascal(); } 6544 6545 SourceLocation getLocationOfByte( 6546 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6547 const TargetInfo &Target, unsigned *StartToken = nullptr, 6548 unsigned *StartTokenByteOffset = nullptr) const { 6549 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6550 StartToken, StartTokenByteOffset); 6551 } 6552 6553 SourceLocation getBeginLoc() const LLVM_READONLY { 6554 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6555 } 6556 6557 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6558 }; 6559 6560 } // namespace 6561 6562 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6563 const Expr *OrigFormatExpr, 6564 ArrayRef<const Expr *> Args, 6565 bool HasVAListArg, unsigned format_idx, 6566 unsigned firstDataArg, 6567 Sema::FormatStringType Type, 6568 bool inFunctionCall, 6569 Sema::VariadicCallType CallType, 6570 llvm::SmallBitVector &CheckedVarArgs, 6571 UncoveredArgHandler &UncoveredArg); 6572 6573 // Determine if an expression is a string literal or constant string. 6574 // If this function returns false on the arguments to a function expecting a 6575 // format string, we will usually need to emit a warning. 6576 // True string literals are then checked by CheckFormatString. 6577 static StringLiteralCheckType 6578 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6579 bool HasVAListArg, unsigned format_idx, 6580 unsigned firstDataArg, Sema::FormatStringType Type, 6581 Sema::VariadicCallType CallType, bool InFunctionCall, 6582 llvm::SmallBitVector &CheckedVarArgs, 6583 UncoveredArgHandler &UncoveredArg, 6584 llvm::APSInt Offset) { 6585 if (S.isConstantEvaluated()) 6586 return SLCT_NotALiteral; 6587 tryAgain: 6588 assert(Offset.isSigned() && "invalid offset"); 6589 6590 if (E->isTypeDependent() || E->isValueDependent()) 6591 return SLCT_NotALiteral; 6592 6593 E = E->IgnoreParenCasts(); 6594 6595 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6596 // Technically -Wformat-nonliteral does not warn about this case. 6597 // The behavior of printf and friends in this case is implementation 6598 // dependent. Ideally if the format string cannot be null then 6599 // it should have a 'nonnull' attribute in the function prototype. 6600 return SLCT_UncheckedLiteral; 6601 6602 switch (E->getStmtClass()) { 6603 case Stmt::BinaryConditionalOperatorClass: 6604 case Stmt::ConditionalOperatorClass: { 6605 // The expression is a literal if both sub-expressions were, and it was 6606 // completely checked only if both sub-expressions were checked. 6607 const AbstractConditionalOperator *C = 6608 cast<AbstractConditionalOperator>(E); 6609 6610 // Determine whether it is necessary to check both sub-expressions, for 6611 // example, because the condition expression is a constant that can be 6612 // evaluated at compile time. 6613 bool CheckLeft = true, CheckRight = true; 6614 6615 bool Cond; 6616 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6617 S.isConstantEvaluated())) { 6618 if (Cond) 6619 CheckRight = false; 6620 else 6621 CheckLeft = false; 6622 } 6623 6624 // We need to maintain the offsets for the right and the left hand side 6625 // separately to check if every possible indexed expression is a valid 6626 // string literal. They might have different offsets for different string 6627 // literals in the end. 6628 StringLiteralCheckType Left; 6629 if (!CheckLeft) 6630 Left = SLCT_UncheckedLiteral; 6631 else { 6632 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6633 HasVAListArg, format_idx, firstDataArg, 6634 Type, CallType, InFunctionCall, 6635 CheckedVarArgs, UncoveredArg, Offset); 6636 if (Left == SLCT_NotALiteral || !CheckRight) { 6637 return Left; 6638 } 6639 } 6640 6641 StringLiteralCheckType Right = 6642 checkFormatStringExpr(S, C->getFalseExpr(), Args, 6643 HasVAListArg, format_idx, firstDataArg, 6644 Type, CallType, InFunctionCall, CheckedVarArgs, 6645 UncoveredArg, Offset); 6646 6647 return (CheckLeft && Left < Right) ? Left : Right; 6648 } 6649 6650 case Stmt::ImplicitCastExprClass: 6651 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6652 goto tryAgain; 6653 6654 case Stmt::OpaqueValueExprClass: 6655 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6656 E = src; 6657 goto tryAgain; 6658 } 6659 return SLCT_NotALiteral; 6660 6661 case Stmt::PredefinedExprClass: 6662 // While __func__, etc., are technically not string literals, they 6663 // cannot contain format specifiers and thus are not a security 6664 // liability. 6665 return SLCT_UncheckedLiteral; 6666 6667 case Stmt::DeclRefExprClass: { 6668 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6669 6670 // As an exception, do not flag errors for variables binding to 6671 // const string literals. 6672 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6673 bool isConstant = false; 6674 QualType T = DR->getType(); 6675 6676 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6677 isConstant = AT->getElementType().isConstant(S.Context); 6678 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6679 isConstant = T.isConstant(S.Context) && 6680 PT->getPointeeType().isConstant(S.Context); 6681 } else if (T->isObjCObjectPointerType()) { 6682 // In ObjC, there is usually no "const ObjectPointer" type, 6683 // so don't check if the pointee type is constant. 6684 isConstant = T.isConstant(S.Context); 6685 } 6686 6687 if (isConstant) { 6688 if (const Expr *Init = VD->getAnyInitializer()) { 6689 // Look through initializers like const char c[] = { "foo" } 6690 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6691 if (InitList->isStringLiteralInit()) 6692 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6693 } 6694 return checkFormatStringExpr(S, Init, Args, 6695 HasVAListArg, format_idx, 6696 firstDataArg, Type, CallType, 6697 /*InFunctionCall*/ false, CheckedVarArgs, 6698 UncoveredArg, Offset); 6699 } 6700 } 6701 6702 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6703 // special check to see if the format string is a function parameter 6704 // of the function calling the printf function. If the function 6705 // has an attribute indicating it is a printf-like function, then we 6706 // should suppress warnings concerning non-literals being used in a call 6707 // to a vprintf function. For example: 6708 // 6709 // void 6710 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6711 // va_list ap; 6712 // va_start(ap, fmt); 6713 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6714 // ... 6715 // } 6716 if (HasVAListArg) { 6717 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6718 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6719 int PVIndex = PV->getFunctionScopeIndex() + 1; 6720 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6721 // adjust for implicit parameter 6722 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6723 if (MD->isInstance()) 6724 ++PVIndex; 6725 // We also check if the formats are compatible. 6726 // We can't pass a 'scanf' string to a 'printf' function. 6727 if (PVIndex == PVFormat->getFormatIdx() && 6728 Type == S.GetFormatStringType(PVFormat)) 6729 return SLCT_UncheckedLiteral; 6730 } 6731 } 6732 } 6733 } 6734 } 6735 6736 return SLCT_NotALiteral; 6737 } 6738 6739 case Stmt::CallExprClass: 6740 case Stmt::CXXMemberCallExprClass: { 6741 const CallExpr *CE = cast<CallExpr>(E); 6742 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6743 bool IsFirst = true; 6744 StringLiteralCheckType CommonResult; 6745 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6746 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6747 StringLiteralCheckType Result = checkFormatStringExpr( 6748 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6749 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6750 if (IsFirst) { 6751 CommonResult = Result; 6752 IsFirst = false; 6753 } 6754 } 6755 if (!IsFirst) 6756 return CommonResult; 6757 6758 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6759 unsigned BuiltinID = FD->getBuiltinID(); 6760 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6761 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6762 const Expr *Arg = CE->getArg(0); 6763 return checkFormatStringExpr(S, Arg, Args, 6764 HasVAListArg, format_idx, 6765 firstDataArg, Type, CallType, 6766 InFunctionCall, CheckedVarArgs, 6767 UncoveredArg, Offset); 6768 } 6769 } 6770 } 6771 6772 return SLCT_NotALiteral; 6773 } 6774 case Stmt::ObjCMessageExprClass: { 6775 const auto *ME = cast<ObjCMessageExpr>(E); 6776 if (const auto *ND = ME->getMethodDecl()) { 6777 if (const auto *FA = ND->getAttr<FormatArgAttr>()) { 6778 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6779 return checkFormatStringExpr( 6780 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6781 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset); 6782 } 6783 } 6784 6785 return SLCT_NotALiteral; 6786 } 6787 case Stmt::ObjCStringLiteralClass: 6788 case Stmt::StringLiteralClass: { 6789 const StringLiteral *StrE = nullptr; 6790 6791 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6792 StrE = ObjCFExpr->getString(); 6793 else 6794 StrE = cast<StringLiteral>(E); 6795 6796 if (StrE) { 6797 if (Offset.isNegative() || Offset > StrE->getLength()) { 6798 // TODO: It would be better to have an explicit warning for out of 6799 // bounds literals. 6800 return SLCT_NotALiteral; 6801 } 6802 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6803 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6804 firstDataArg, Type, InFunctionCall, CallType, 6805 CheckedVarArgs, UncoveredArg); 6806 return SLCT_CheckedLiteral; 6807 } 6808 6809 return SLCT_NotALiteral; 6810 } 6811 case Stmt::BinaryOperatorClass: { 6812 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6813 6814 // A string literal + an int offset is still a string literal. 6815 if (BinOp->isAdditiveOp()) { 6816 Expr::EvalResult LResult, RResult; 6817 6818 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6819 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6820 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6821 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6822 6823 if (LIsInt != RIsInt) { 6824 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6825 6826 if (LIsInt) { 6827 if (BinOpKind == BO_Add) { 6828 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6829 E = BinOp->getRHS(); 6830 goto tryAgain; 6831 } 6832 } else { 6833 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6834 E = BinOp->getLHS(); 6835 goto tryAgain; 6836 } 6837 } 6838 } 6839 6840 return SLCT_NotALiteral; 6841 } 6842 case Stmt::UnaryOperatorClass: { 6843 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6844 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6845 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6846 Expr::EvalResult IndexResult; 6847 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6848 Expr::SE_NoSideEffects, 6849 S.isConstantEvaluated())) { 6850 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6851 /*RHS is int*/ true); 6852 E = ASE->getBase(); 6853 goto tryAgain; 6854 } 6855 } 6856 6857 return SLCT_NotALiteral; 6858 } 6859 6860 default: 6861 return SLCT_NotALiteral; 6862 } 6863 } 6864 6865 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6866 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6867 .Case("scanf", FST_Scanf) 6868 .Cases("printf", "printf0", FST_Printf) 6869 .Cases("NSString", "CFString", FST_NSString) 6870 .Case("strftime", FST_Strftime) 6871 .Case("strfmon", FST_Strfmon) 6872 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6873 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6874 .Case("os_trace", FST_OSLog) 6875 .Case("os_log", FST_OSLog) 6876 .Default(FST_Unknown); 6877 } 6878 6879 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6880 /// functions) for correct use of format strings. 6881 /// Returns true if a format string has been fully checked. 6882 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6883 ArrayRef<const Expr *> Args, 6884 bool IsCXXMember, 6885 VariadicCallType CallType, 6886 SourceLocation Loc, SourceRange Range, 6887 llvm::SmallBitVector &CheckedVarArgs) { 6888 FormatStringInfo FSI; 6889 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6890 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6891 FSI.FirstDataArg, GetFormatStringType(Format), 6892 CallType, Loc, Range, CheckedVarArgs); 6893 return false; 6894 } 6895 6896 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6897 bool HasVAListArg, unsigned format_idx, 6898 unsigned firstDataArg, FormatStringType Type, 6899 VariadicCallType CallType, 6900 SourceLocation Loc, SourceRange Range, 6901 llvm::SmallBitVector &CheckedVarArgs) { 6902 // CHECK: printf/scanf-like function is called with no format string. 6903 if (format_idx >= Args.size()) { 6904 Diag(Loc, diag::warn_missing_format_string) << Range; 6905 return false; 6906 } 6907 6908 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6909 6910 // CHECK: format string is not a string literal. 6911 // 6912 // Dynamically generated format strings are difficult to 6913 // automatically vet at compile time. Requiring that format strings 6914 // are string literals: (1) permits the checking of format strings by 6915 // the compiler and thereby (2) can practically remove the source of 6916 // many format string exploits. 6917 6918 // Format string can be either ObjC string (e.g. @"%d") or 6919 // C string (e.g. "%d") 6920 // ObjC string uses the same format specifiers as C string, so we can use 6921 // the same format string checking logic for both ObjC and C strings. 6922 UncoveredArgHandler UncoveredArg; 6923 StringLiteralCheckType CT = 6924 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6925 format_idx, firstDataArg, Type, CallType, 6926 /*IsFunctionCall*/ true, CheckedVarArgs, 6927 UncoveredArg, 6928 /*no string offset*/ llvm::APSInt(64, false) = 0); 6929 6930 // Generate a diagnostic where an uncovered argument is detected. 6931 if (UncoveredArg.hasUncoveredArg()) { 6932 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6933 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6934 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6935 } 6936 6937 if (CT != SLCT_NotALiteral) 6938 // Literal format string found, check done! 6939 return CT == SLCT_CheckedLiteral; 6940 6941 // Strftime is particular as it always uses a single 'time' argument, 6942 // so it is safe to pass a non-literal string. 6943 if (Type == FST_Strftime) 6944 return false; 6945 6946 // Do not emit diag when the string param is a macro expansion and the 6947 // format is either NSString or CFString. This is a hack to prevent 6948 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6949 // which are usually used in place of NS and CF string literals. 6950 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6951 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6952 return false; 6953 6954 // If there are no arguments specified, warn with -Wformat-security, otherwise 6955 // warn only with -Wformat-nonliteral. 6956 if (Args.size() == firstDataArg) { 6957 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6958 << OrigFormatExpr->getSourceRange(); 6959 switch (Type) { 6960 default: 6961 break; 6962 case FST_Kprintf: 6963 case FST_FreeBSDKPrintf: 6964 case FST_Printf: 6965 Diag(FormatLoc, diag::note_format_security_fixit) 6966 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6967 break; 6968 case FST_NSString: 6969 Diag(FormatLoc, diag::note_format_security_fixit) 6970 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6971 break; 6972 } 6973 } else { 6974 Diag(FormatLoc, diag::warn_format_nonliteral) 6975 << OrigFormatExpr->getSourceRange(); 6976 } 6977 return false; 6978 } 6979 6980 namespace { 6981 6982 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6983 protected: 6984 Sema &S; 6985 const FormatStringLiteral *FExpr; 6986 const Expr *OrigFormatExpr; 6987 const Sema::FormatStringType FSType; 6988 const unsigned FirstDataArg; 6989 const unsigned NumDataArgs; 6990 const char *Beg; // Start of format string. 6991 const bool HasVAListArg; 6992 ArrayRef<const Expr *> Args; 6993 unsigned FormatIdx; 6994 llvm::SmallBitVector CoveredArgs; 6995 bool usesPositionalArgs = false; 6996 bool atFirstArg = true; 6997 bool inFunctionCall; 6998 Sema::VariadicCallType CallType; 6999 llvm::SmallBitVector &CheckedVarArgs; 7000 UncoveredArgHandler &UncoveredArg; 7001 7002 public: 7003 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7004 const Expr *origFormatExpr, 7005 const Sema::FormatStringType type, unsigned firstDataArg, 7006 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7007 ArrayRef<const Expr *> Args, unsigned formatIdx, 7008 bool inFunctionCall, Sema::VariadicCallType callType, 7009 llvm::SmallBitVector &CheckedVarArgs, 7010 UncoveredArgHandler &UncoveredArg) 7011 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7012 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7013 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7014 inFunctionCall(inFunctionCall), CallType(callType), 7015 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7016 CoveredArgs.resize(numDataArgs); 7017 CoveredArgs.reset(); 7018 } 7019 7020 void DoneProcessing(); 7021 7022 void HandleIncompleteSpecifier(const char *startSpecifier, 7023 unsigned specifierLen) override; 7024 7025 void HandleInvalidLengthModifier( 7026 const analyze_format_string::FormatSpecifier &FS, 7027 const analyze_format_string::ConversionSpecifier &CS, 7028 const char *startSpecifier, unsigned specifierLen, 7029 unsigned DiagID); 7030 7031 void HandleNonStandardLengthModifier( 7032 const analyze_format_string::FormatSpecifier &FS, 7033 const char *startSpecifier, unsigned specifierLen); 7034 7035 void HandleNonStandardConversionSpecifier( 7036 const analyze_format_string::ConversionSpecifier &CS, 7037 const char *startSpecifier, unsigned specifierLen); 7038 7039 void HandlePosition(const char *startPos, unsigned posLen) override; 7040 7041 void HandleInvalidPosition(const char *startSpecifier, 7042 unsigned specifierLen, 7043 analyze_format_string::PositionContext p) override; 7044 7045 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7046 7047 void HandleNullChar(const char *nullCharacter) override; 7048 7049 template <typename Range> 7050 static void 7051 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7052 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7053 bool IsStringLocation, Range StringRange, 7054 ArrayRef<FixItHint> Fixit = None); 7055 7056 protected: 7057 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7058 const char *startSpec, 7059 unsigned specifierLen, 7060 const char *csStart, unsigned csLen); 7061 7062 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7063 const char *startSpec, 7064 unsigned specifierLen); 7065 7066 SourceRange getFormatStringRange(); 7067 CharSourceRange getSpecifierRange(const char *startSpecifier, 7068 unsigned specifierLen); 7069 SourceLocation getLocationOfByte(const char *x); 7070 7071 const Expr *getDataArg(unsigned i) const; 7072 7073 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7074 const analyze_format_string::ConversionSpecifier &CS, 7075 const char *startSpecifier, unsigned specifierLen, 7076 unsigned argIndex); 7077 7078 template <typename Range> 7079 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7080 bool IsStringLocation, Range StringRange, 7081 ArrayRef<FixItHint> Fixit = None); 7082 }; 7083 7084 } // namespace 7085 7086 SourceRange CheckFormatHandler::getFormatStringRange() { 7087 return OrigFormatExpr->getSourceRange(); 7088 } 7089 7090 CharSourceRange CheckFormatHandler:: 7091 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7092 SourceLocation Start = getLocationOfByte(startSpecifier); 7093 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7094 7095 // Advance the end SourceLocation by one due to half-open ranges. 7096 End = End.getLocWithOffset(1); 7097 7098 return CharSourceRange::getCharRange(Start, End); 7099 } 7100 7101 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7102 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7103 S.getLangOpts(), S.Context.getTargetInfo()); 7104 } 7105 7106 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7107 unsigned specifierLen){ 7108 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7109 getLocationOfByte(startSpecifier), 7110 /*IsStringLocation*/true, 7111 getSpecifierRange(startSpecifier, specifierLen)); 7112 } 7113 7114 void CheckFormatHandler::HandleInvalidLengthModifier( 7115 const analyze_format_string::FormatSpecifier &FS, 7116 const analyze_format_string::ConversionSpecifier &CS, 7117 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7118 using namespace analyze_format_string; 7119 7120 const LengthModifier &LM = FS.getLengthModifier(); 7121 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7122 7123 // See if we know how to fix this length modifier. 7124 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7125 if (FixedLM) { 7126 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7127 getLocationOfByte(LM.getStart()), 7128 /*IsStringLocation*/true, 7129 getSpecifierRange(startSpecifier, specifierLen)); 7130 7131 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7132 << FixedLM->toString() 7133 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7134 7135 } else { 7136 FixItHint Hint; 7137 if (DiagID == diag::warn_format_nonsensical_length) 7138 Hint = FixItHint::CreateRemoval(LMRange); 7139 7140 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7141 getLocationOfByte(LM.getStart()), 7142 /*IsStringLocation*/true, 7143 getSpecifierRange(startSpecifier, specifierLen), 7144 Hint); 7145 } 7146 } 7147 7148 void CheckFormatHandler::HandleNonStandardLengthModifier( 7149 const analyze_format_string::FormatSpecifier &FS, 7150 const char *startSpecifier, unsigned specifierLen) { 7151 using namespace analyze_format_string; 7152 7153 const LengthModifier &LM = FS.getLengthModifier(); 7154 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7155 7156 // See if we know how to fix this length modifier. 7157 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7158 if (FixedLM) { 7159 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7160 << LM.toString() << 0, 7161 getLocationOfByte(LM.getStart()), 7162 /*IsStringLocation*/true, 7163 getSpecifierRange(startSpecifier, specifierLen)); 7164 7165 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7166 << FixedLM->toString() 7167 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7168 7169 } else { 7170 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7171 << LM.toString() << 0, 7172 getLocationOfByte(LM.getStart()), 7173 /*IsStringLocation*/true, 7174 getSpecifierRange(startSpecifier, specifierLen)); 7175 } 7176 } 7177 7178 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7179 const analyze_format_string::ConversionSpecifier &CS, 7180 const char *startSpecifier, unsigned specifierLen) { 7181 using namespace analyze_format_string; 7182 7183 // See if we know how to fix this conversion specifier. 7184 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7185 if (FixedCS) { 7186 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7187 << CS.toString() << /*conversion specifier*/1, 7188 getLocationOfByte(CS.getStart()), 7189 /*IsStringLocation*/true, 7190 getSpecifierRange(startSpecifier, specifierLen)); 7191 7192 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7193 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7194 << FixedCS->toString() 7195 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7196 } else { 7197 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7198 << CS.toString() << /*conversion specifier*/1, 7199 getLocationOfByte(CS.getStart()), 7200 /*IsStringLocation*/true, 7201 getSpecifierRange(startSpecifier, specifierLen)); 7202 } 7203 } 7204 7205 void CheckFormatHandler::HandlePosition(const char *startPos, 7206 unsigned posLen) { 7207 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7208 getLocationOfByte(startPos), 7209 /*IsStringLocation*/true, 7210 getSpecifierRange(startPos, posLen)); 7211 } 7212 7213 void 7214 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7215 analyze_format_string::PositionContext p) { 7216 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7217 << (unsigned) p, 7218 getLocationOfByte(startPos), /*IsStringLocation*/true, 7219 getSpecifierRange(startPos, posLen)); 7220 } 7221 7222 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7223 unsigned posLen) { 7224 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7225 getLocationOfByte(startPos), 7226 /*IsStringLocation*/true, 7227 getSpecifierRange(startPos, posLen)); 7228 } 7229 7230 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7231 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7232 // The presence of a null character is likely an error. 7233 EmitFormatDiagnostic( 7234 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7235 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7236 getFormatStringRange()); 7237 } 7238 } 7239 7240 // Note that this may return NULL if there was an error parsing or building 7241 // one of the argument expressions. 7242 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7243 return Args[FirstDataArg + i]; 7244 } 7245 7246 void CheckFormatHandler::DoneProcessing() { 7247 // Does the number of data arguments exceed the number of 7248 // format conversions in the format string? 7249 if (!HasVAListArg) { 7250 // Find any arguments that weren't covered. 7251 CoveredArgs.flip(); 7252 signed notCoveredArg = CoveredArgs.find_first(); 7253 if (notCoveredArg >= 0) { 7254 assert((unsigned)notCoveredArg < NumDataArgs); 7255 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7256 } else { 7257 UncoveredArg.setAllCovered(); 7258 } 7259 } 7260 } 7261 7262 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7263 const Expr *ArgExpr) { 7264 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7265 "Invalid state"); 7266 7267 if (!ArgExpr) 7268 return; 7269 7270 SourceLocation Loc = ArgExpr->getBeginLoc(); 7271 7272 if (S.getSourceManager().isInSystemMacro(Loc)) 7273 return; 7274 7275 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7276 for (auto E : DiagnosticExprs) 7277 PDiag << E->getSourceRange(); 7278 7279 CheckFormatHandler::EmitFormatDiagnostic( 7280 S, IsFunctionCall, DiagnosticExprs[0], 7281 PDiag, Loc, /*IsStringLocation*/false, 7282 DiagnosticExprs[0]->getSourceRange()); 7283 } 7284 7285 bool 7286 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7287 SourceLocation Loc, 7288 const char *startSpec, 7289 unsigned specifierLen, 7290 const char *csStart, 7291 unsigned csLen) { 7292 bool keepGoing = true; 7293 if (argIndex < NumDataArgs) { 7294 // Consider the argument coverered, even though the specifier doesn't 7295 // make sense. 7296 CoveredArgs.set(argIndex); 7297 } 7298 else { 7299 // If argIndex exceeds the number of data arguments we 7300 // don't issue a warning because that is just a cascade of warnings (and 7301 // they may have intended '%%' anyway). We don't want to continue processing 7302 // the format string after this point, however, as we will like just get 7303 // gibberish when trying to match arguments. 7304 keepGoing = false; 7305 } 7306 7307 StringRef Specifier(csStart, csLen); 7308 7309 // If the specifier in non-printable, it could be the first byte of a UTF-8 7310 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7311 // hex value. 7312 std::string CodePointStr; 7313 if (!llvm::sys::locale::isPrint(*csStart)) { 7314 llvm::UTF32 CodePoint; 7315 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7316 const llvm::UTF8 *E = 7317 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7318 llvm::ConversionResult Result = 7319 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7320 7321 if (Result != llvm::conversionOK) { 7322 unsigned char FirstChar = *csStart; 7323 CodePoint = (llvm::UTF32)FirstChar; 7324 } 7325 7326 llvm::raw_string_ostream OS(CodePointStr); 7327 if (CodePoint < 256) 7328 OS << "\\x" << llvm::format("%02x", CodePoint); 7329 else if (CodePoint <= 0xFFFF) 7330 OS << "\\u" << llvm::format("%04x", CodePoint); 7331 else 7332 OS << "\\U" << llvm::format("%08x", CodePoint); 7333 OS.flush(); 7334 Specifier = CodePointStr; 7335 } 7336 7337 EmitFormatDiagnostic( 7338 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7339 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7340 7341 return keepGoing; 7342 } 7343 7344 void 7345 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7346 const char *startSpec, 7347 unsigned specifierLen) { 7348 EmitFormatDiagnostic( 7349 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7350 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7351 } 7352 7353 bool 7354 CheckFormatHandler::CheckNumArgs( 7355 const analyze_format_string::FormatSpecifier &FS, 7356 const analyze_format_string::ConversionSpecifier &CS, 7357 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7358 7359 if (argIndex >= NumDataArgs) { 7360 PartialDiagnostic PDiag = FS.usesPositionalArg() 7361 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7362 << (argIndex+1) << NumDataArgs) 7363 : S.PDiag(diag::warn_printf_insufficient_data_args); 7364 EmitFormatDiagnostic( 7365 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7366 getSpecifierRange(startSpecifier, specifierLen)); 7367 7368 // Since more arguments than conversion tokens are given, by extension 7369 // all arguments are covered, so mark this as so. 7370 UncoveredArg.setAllCovered(); 7371 return false; 7372 } 7373 return true; 7374 } 7375 7376 template<typename Range> 7377 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7378 SourceLocation Loc, 7379 bool IsStringLocation, 7380 Range StringRange, 7381 ArrayRef<FixItHint> FixIt) { 7382 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7383 Loc, IsStringLocation, StringRange, FixIt); 7384 } 7385 7386 /// If the format string is not within the function call, emit a note 7387 /// so that the function call and string are in diagnostic messages. 7388 /// 7389 /// \param InFunctionCall if true, the format string is within the function 7390 /// call and only one diagnostic message will be produced. Otherwise, an 7391 /// extra note will be emitted pointing to location of the format string. 7392 /// 7393 /// \param ArgumentExpr the expression that is passed as the format string 7394 /// argument in the function call. Used for getting locations when two 7395 /// diagnostics are emitted. 7396 /// 7397 /// \param PDiag the callee should already have provided any strings for the 7398 /// diagnostic message. This function only adds locations and fixits 7399 /// to diagnostics. 7400 /// 7401 /// \param Loc primary location for diagnostic. If two diagnostics are 7402 /// required, one will be at Loc and a new SourceLocation will be created for 7403 /// the other one. 7404 /// 7405 /// \param IsStringLocation if true, Loc points to the format string should be 7406 /// used for the note. Otherwise, Loc points to the argument list and will 7407 /// be used with PDiag. 7408 /// 7409 /// \param StringRange some or all of the string to highlight. This is 7410 /// templated so it can accept either a CharSourceRange or a SourceRange. 7411 /// 7412 /// \param FixIt optional fix it hint for the format string. 7413 template <typename Range> 7414 void CheckFormatHandler::EmitFormatDiagnostic( 7415 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7416 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7417 Range StringRange, ArrayRef<FixItHint> FixIt) { 7418 if (InFunctionCall) { 7419 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7420 D << StringRange; 7421 D << FixIt; 7422 } else { 7423 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7424 << ArgumentExpr->getSourceRange(); 7425 7426 const Sema::SemaDiagnosticBuilder &Note = 7427 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7428 diag::note_format_string_defined); 7429 7430 Note << StringRange; 7431 Note << FixIt; 7432 } 7433 } 7434 7435 //===--- CHECK: Printf format string checking ------------------------------===// 7436 7437 namespace { 7438 7439 class CheckPrintfHandler : public CheckFormatHandler { 7440 public: 7441 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7442 const Expr *origFormatExpr, 7443 const Sema::FormatStringType type, unsigned firstDataArg, 7444 unsigned numDataArgs, bool isObjC, const char *beg, 7445 bool hasVAListArg, ArrayRef<const Expr *> Args, 7446 unsigned formatIdx, bool inFunctionCall, 7447 Sema::VariadicCallType CallType, 7448 llvm::SmallBitVector &CheckedVarArgs, 7449 UncoveredArgHandler &UncoveredArg) 7450 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7451 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7452 inFunctionCall, CallType, CheckedVarArgs, 7453 UncoveredArg) {} 7454 7455 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7456 7457 /// Returns true if '%@' specifiers are allowed in the format string. 7458 bool allowsObjCArg() const { 7459 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7460 FSType == Sema::FST_OSTrace; 7461 } 7462 7463 bool HandleInvalidPrintfConversionSpecifier( 7464 const analyze_printf::PrintfSpecifier &FS, 7465 const char *startSpecifier, 7466 unsigned specifierLen) override; 7467 7468 void handleInvalidMaskType(StringRef MaskType) override; 7469 7470 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7471 const char *startSpecifier, 7472 unsigned specifierLen) override; 7473 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7474 const char *StartSpecifier, 7475 unsigned SpecifierLen, 7476 const Expr *E); 7477 7478 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7479 const char *startSpecifier, unsigned specifierLen); 7480 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7481 const analyze_printf::OptionalAmount &Amt, 7482 unsigned type, 7483 const char *startSpecifier, unsigned specifierLen); 7484 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7485 const analyze_printf::OptionalFlag &flag, 7486 const char *startSpecifier, unsigned specifierLen); 7487 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7488 const analyze_printf::OptionalFlag &ignoredFlag, 7489 const analyze_printf::OptionalFlag &flag, 7490 const char *startSpecifier, unsigned specifierLen); 7491 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7492 const Expr *E); 7493 7494 void HandleEmptyObjCModifierFlag(const char *startFlag, 7495 unsigned flagLen) override; 7496 7497 void HandleInvalidObjCModifierFlag(const char *startFlag, 7498 unsigned flagLen) override; 7499 7500 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7501 const char *flagsEnd, 7502 const char *conversionPosition) 7503 override; 7504 }; 7505 7506 } // namespace 7507 7508 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7509 const analyze_printf::PrintfSpecifier &FS, 7510 const char *startSpecifier, 7511 unsigned specifierLen) { 7512 const analyze_printf::PrintfConversionSpecifier &CS = 7513 FS.getConversionSpecifier(); 7514 7515 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7516 getLocationOfByte(CS.getStart()), 7517 startSpecifier, specifierLen, 7518 CS.getStart(), CS.getLength()); 7519 } 7520 7521 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7522 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7523 } 7524 7525 bool CheckPrintfHandler::HandleAmount( 7526 const analyze_format_string::OptionalAmount &Amt, 7527 unsigned k, const char *startSpecifier, 7528 unsigned specifierLen) { 7529 if (Amt.hasDataArgument()) { 7530 if (!HasVAListArg) { 7531 unsigned argIndex = Amt.getArgIndex(); 7532 if (argIndex >= NumDataArgs) { 7533 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7534 << k, 7535 getLocationOfByte(Amt.getStart()), 7536 /*IsStringLocation*/true, 7537 getSpecifierRange(startSpecifier, specifierLen)); 7538 // Don't do any more checking. We will just emit 7539 // spurious errors. 7540 return false; 7541 } 7542 7543 // Type check the data argument. It should be an 'int'. 7544 // Although not in conformance with C99, we also allow the argument to be 7545 // an 'unsigned int' as that is a reasonably safe case. GCC also 7546 // doesn't emit a warning for that case. 7547 CoveredArgs.set(argIndex); 7548 const Expr *Arg = getDataArg(argIndex); 7549 if (!Arg) 7550 return false; 7551 7552 QualType T = Arg->getType(); 7553 7554 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7555 assert(AT.isValid()); 7556 7557 if (!AT.matchesType(S.Context, T)) { 7558 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7559 << k << AT.getRepresentativeTypeName(S.Context) 7560 << T << Arg->getSourceRange(), 7561 getLocationOfByte(Amt.getStart()), 7562 /*IsStringLocation*/true, 7563 getSpecifierRange(startSpecifier, specifierLen)); 7564 // Don't do any more checking. We will just emit 7565 // spurious errors. 7566 return false; 7567 } 7568 } 7569 } 7570 return true; 7571 } 7572 7573 void CheckPrintfHandler::HandleInvalidAmount( 7574 const analyze_printf::PrintfSpecifier &FS, 7575 const analyze_printf::OptionalAmount &Amt, 7576 unsigned type, 7577 const char *startSpecifier, 7578 unsigned specifierLen) { 7579 const analyze_printf::PrintfConversionSpecifier &CS = 7580 FS.getConversionSpecifier(); 7581 7582 FixItHint fixit = 7583 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7584 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7585 Amt.getConstantLength())) 7586 : FixItHint(); 7587 7588 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7589 << type << CS.toString(), 7590 getLocationOfByte(Amt.getStart()), 7591 /*IsStringLocation*/true, 7592 getSpecifierRange(startSpecifier, specifierLen), 7593 fixit); 7594 } 7595 7596 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7597 const analyze_printf::OptionalFlag &flag, 7598 const char *startSpecifier, 7599 unsigned specifierLen) { 7600 // Warn about pointless flag with a fixit removal. 7601 const analyze_printf::PrintfConversionSpecifier &CS = 7602 FS.getConversionSpecifier(); 7603 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7604 << flag.toString() << CS.toString(), 7605 getLocationOfByte(flag.getPosition()), 7606 /*IsStringLocation*/true, 7607 getSpecifierRange(startSpecifier, specifierLen), 7608 FixItHint::CreateRemoval( 7609 getSpecifierRange(flag.getPosition(), 1))); 7610 } 7611 7612 void CheckPrintfHandler::HandleIgnoredFlag( 7613 const analyze_printf::PrintfSpecifier &FS, 7614 const analyze_printf::OptionalFlag &ignoredFlag, 7615 const analyze_printf::OptionalFlag &flag, 7616 const char *startSpecifier, 7617 unsigned specifierLen) { 7618 // Warn about ignored flag with a fixit removal. 7619 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7620 << ignoredFlag.toString() << flag.toString(), 7621 getLocationOfByte(ignoredFlag.getPosition()), 7622 /*IsStringLocation*/true, 7623 getSpecifierRange(startSpecifier, specifierLen), 7624 FixItHint::CreateRemoval( 7625 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7626 } 7627 7628 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7629 unsigned flagLen) { 7630 // Warn about an empty flag. 7631 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7632 getLocationOfByte(startFlag), 7633 /*IsStringLocation*/true, 7634 getSpecifierRange(startFlag, flagLen)); 7635 } 7636 7637 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7638 unsigned flagLen) { 7639 // Warn about an invalid flag. 7640 auto Range = getSpecifierRange(startFlag, flagLen); 7641 StringRef flag(startFlag, flagLen); 7642 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7643 getLocationOfByte(startFlag), 7644 /*IsStringLocation*/true, 7645 Range, FixItHint::CreateRemoval(Range)); 7646 } 7647 7648 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7649 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7650 // Warn about using '[...]' without a '@' conversion. 7651 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7652 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7653 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7654 getLocationOfByte(conversionPosition), 7655 /*IsStringLocation*/true, 7656 Range, FixItHint::CreateRemoval(Range)); 7657 } 7658 7659 // Determines if the specified is a C++ class or struct containing 7660 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7661 // "c_str()"). 7662 template<typename MemberKind> 7663 static llvm::SmallPtrSet<MemberKind*, 1> 7664 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7665 const RecordType *RT = Ty->getAs<RecordType>(); 7666 llvm::SmallPtrSet<MemberKind*, 1> Results; 7667 7668 if (!RT) 7669 return Results; 7670 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7671 if (!RD || !RD->getDefinition()) 7672 return Results; 7673 7674 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7675 Sema::LookupMemberName); 7676 R.suppressDiagnostics(); 7677 7678 // We just need to include all members of the right kind turned up by the 7679 // filter, at this point. 7680 if (S.LookupQualifiedName(R, RT->getDecl())) 7681 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7682 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7683 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7684 Results.insert(FK); 7685 } 7686 return Results; 7687 } 7688 7689 /// Check if we could call '.c_str()' on an object. 7690 /// 7691 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7692 /// allow the call, or if it would be ambiguous). 7693 bool Sema::hasCStrMethod(const Expr *E) { 7694 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7695 7696 MethodSet Results = 7697 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7698 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7699 MI != ME; ++MI) 7700 if ((*MI)->getMinRequiredArguments() == 0) 7701 return true; 7702 return false; 7703 } 7704 7705 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7706 // better diagnostic if so. AT is assumed to be valid. 7707 // Returns true when a c_str() conversion method is found. 7708 bool CheckPrintfHandler::checkForCStrMembers( 7709 const analyze_printf::ArgType &AT, const Expr *E) { 7710 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7711 7712 MethodSet Results = 7713 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7714 7715 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7716 MI != ME; ++MI) { 7717 const CXXMethodDecl *Method = *MI; 7718 if (Method->getMinRequiredArguments() == 0 && 7719 AT.matchesType(S.Context, Method->getReturnType())) { 7720 // FIXME: Suggest parens if the expression needs them. 7721 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7722 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7723 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7724 return true; 7725 } 7726 } 7727 7728 return false; 7729 } 7730 7731 bool 7732 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7733 &FS, 7734 const char *startSpecifier, 7735 unsigned specifierLen) { 7736 using namespace analyze_format_string; 7737 using namespace analyze_printf; 7738 7739 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7740 7741 if (FS.consumesDataArgument()) { 7742 if (atFirstArg) { 7743 atFirstArg = false; 7744 usesPositionalArgs = FS.usesPositionalArg(); 7745 } 7746 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7747 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7748 startSpecifier, specifierLen); 7749 return false; 7750 } 7751 } 7752 7753 // First check if the field width, precision, and conversion specifier 7754 // have matching data arguments. 7755 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7756 startSpecifier, specifierLen)) { 7757 return false; 7758 } 7759 7760 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7761 startSpecifier, specifierLen)) { 7762 return false; 7763 } 7764 7765 if (!CS.consumesDataArgument()) { 7766 // FIXME: Technically specifying a precision or field width here 7767 // makes no sense. Worth issuing a warning at some point. 7768 return true; 7769 } 7770 7771 // Consume the argument. 7772 unsigned argIndex = FS.getArgIndex(); 7773 if (argIndex < NumDataArgs) { 7774 // The check to see if the argIndex is valid will come later. 7775 // We set the bit here because we may exit early from this 7776 // function if we encounter some other error. 7777 CoveredArgs.set(argIndex); 7778 } 7779 7780 // FreeBSD kernel extensions. 7781 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7782 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7783 // We need at least two arguments. 7784 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7785 return false; 7786 7787 // Claim the second argument. 7788 CoveredArgs.set(argIndex + 1); 7789 7790 // Type check the first argument (int for %b, pointer for %D) 7791 const Expr *Ex = getDataArg(argIndex); 7792 const analyze_printf::ArgType &AT = 7793 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7794 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7795 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7796 EmitFormatDiagnostic( 7797 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7798 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7799 << false << Ex->getSourceRange(), 7800 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7801 getSpecifierRange(startSpecifier, specifierLen)); 7802 7803 // Type check the second argument (char * for both %b and %D) 7804 Ex = getDataArg(argIndex + 1); 7805 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7806 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7807 EmitFormatDiagnostic( 7808 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7809 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7810 << false << Ex->getSourceRange(), 7811 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7812 getSpecifierRange(startSpecifier, specifierLen)); 7813 7814 return true; 7815 } 7816 7817 // Check for using an Objective-C specific conversion specifier 7818 // in a non-ObjC literal. 7819 if (!allowsObjCArg() && CS.isObjCArg()) { 7820 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7821 specifierLen); 7822 } 7823 7824 // %P can only be used with os_log. 7825 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7826 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7827 specifierLen); 7828 } 7829 7830 // %n is not allowed with os_log. 7831 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7832 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7833 getLocationOfByte(CS.getStart()), 7834 /*IsStringLocation*/ false, 7835 getSpecifierRange(startSpecifier, specifierLen)); 7836 7837 return true; 7838 } 7839 7840 // Only scalars are allowed for os_trace. 7841 if (FSType == Sema::FST_OSTrace && 7842 (CS.getKind() == ConversionSpecifier::PArg || 7843 CS.getKind() == ConversionSpecifier::sArg || 7844 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7845 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7846 specifierLen); 7847 } 7848 7849 // Check for use of public/private annotation outside of os_log(). 7850 if (FSType != Sema::FST_OSLog) { 7851 if (FS.isPublic().isSet()) { 7852 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7853 << "public", 7854 getLocationOfByte(FS.isPublic().getPosition()), 7855 /*IsStringLocation*/ false, 7856 getSpecifierRange(startSpecifier, specifierLen)); 7857 } 7858 if (FS.isPrivate().isSet()) { 7859 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7860 << "private", 7861 getLocationOfByte(FS.isPrivate().getPosition()), 7862 /*IsStringLocation*/ false, 7863 getSpecifierRange(startSpecifier, specifierLen)); 7864 } 7865 } 7866 7867 // Check for invalid use of field width 7868 if (!FS.hasValidFieldWidth()) { 7869 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7870 startSpecifier, specifierLen); 7871 } 7872 7873 // Check for invalid use of precision 7874 if (!FS.hasValidPrecision()) { 7875 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7876 startSpecifier, specifierLen); 7877 } 7878 7879 // Precision is mandatory for %P specifier. 7880 if (CS.getKind() == ConversionSpecifier::PArg && 7881 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7882 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7883 getLocationOfByte(startSpecifier), 7884 /*IsStringLocation*/ false, 7885 getSpecifierRange(startSpecifier, specifierLen)); 7886 } 7887 7888 // Check each flag does not conflict with any other component. 7889 if (!FS.hasValidThousandsGroupingPrefix()) 7890 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7891 if (!FS.hasValidLeadingZeros()) 7892 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7893 if (!FS.hasValidPlusPrefix()) 7894 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7895 if (!FS.hasValidSpacePrefix()) 7896 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7897 if (!FS.hasValidAlternativeForm()) 7898 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7899 if (!FS.hasValidLeftJustified()) 7900 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7901 7902 // Check that flags are not ignored by another flag 7903 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7904 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7905 startSpecifier, specifierLen); 7906 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7907 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7908 startSpecifier, specifierLen); 7909 7910 // Check the length modifier is valid with the given conversion specifier. 7911 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7912 S.getLangOpts())) 7913 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7914 diag::warn_format_nonsensical_length); 7915 else if (!FS.hasStandardLengthModifier()) 7916 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7917 else if (!FS.hasStandardLengthConversionCombination()) 7918 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7919 diag::warn_format_non_standard_conversion_spec); 7920 7921 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7922 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7923 7924 // The remaining checks depend on the data arguments. 7925 if (HasVAListArg) 7926 return true; 7927 7928 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7929 return false; 7930 7931 const Expr *Arg = getDataArg(argIndex); 7932 if (!Arg) 7933 return true; 7934 7935 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7936 } 7937 7938 static bool requiresParensToAddCast(const Expr *E) { 7939 // FIXME: We should have a general way to reason about operator 7940 // precedence and whether parens are actually needed here. 7941 // Take care of a few common cases where they aren't. 7942 const Expr *Inside = E->IgnoreImpCasts(); 7943 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7944 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7945 7946 switch (Inside->getStmtClass()) { 7947 case Stmt::ArraySubscriptExprClass: 7948 case Stmt::CallExprClass: 7949 case Stmt::CharacterLiteralClass: 7950 case Stmt::CXXBoolLiteralExprClass: 7951 case Stmt::DeclRefExprClass: 7952 case Stmt::FloatingLiteralClass: 7953 case Stmt::IntegerLiteralClass: 7954 case Stmt::MemberExprClass: 7955 case Stmt::ObjCArrayLiteralClass: 7956 case Stmt::ObjCBoolLiteralExprClass: 7957 case Stmt::ObjCBoxedExprClass: 7958 case Stmt::ObjCDictionaryLiteralClass: 7959 case Stmt::ObjCEncodeExprClass: 7960 case Stmt::ObjCIvarRefExprClass: 7961 case Stmt::ObjCMessageExprClass: 7962 case Stmt::ObjCPropertyRefExprClass: 7963 case Stmt::ObjCStringLiteralClass: 7964 case Stmt::ObjCSubscriptRefExprClass: 7965 case Stmt::ParenExprClass: 7966 case Stmt::StringLiteralClass: 7967 case Stmt::UnaryOperatorClass: 7968 return false; 7969 default: 7970 return true; 7971 } 7972 } 7973 7974 static std::pair<QualType, StringRef> 7975 shouldNotPrintDirectly(const ASTContext &Context, 7976 QualType IntendedTy, 7977 const Expr *E) { 7978 // Use a 'while' to peel off layers of typedefs. 7979 QualType TyTy = IntendedTy; 7980 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7981 StringRef Name = UserTy->getDecl()->getName(); 7982 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7983 .Case("CFIndex", Context.getNSIntegerType()) 7984 .Case("NSInteger", Context.getNSIntegerType()) 7985 .Case("NSUInteger", Context.getNSUIntegerType()) 7986 .Case("SInt32", Context.IntTy) 7987 .Case("UInt32", Context.UnsignedIntTy) 7988 .Default(QualType()); 7989 7990 if (!CastTy.isNull()) 7991 return std::make_pair(CastTy, Name); 7992 7993 TyTy = UserTy->desugar(); 7994 } 7995 7996 // Strip parens if necessary. 7997 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7998 return shouldNotPrintDirectly(Context, 7999 PE->getSubExpr()->getType(), 8000 PE->getSubExpr()); 8001 8002 // If this is a conditional expression, then its result type is constructed 8003 // via usual arithmetic conversions and thus there might be no necessary 8004 // typedef sugar there. Recurse to operands to check for NSInteger & 8005 // Co. usage condition. 8006 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8007 QualType TrueTy, FalseTy; 8008 StringRef TrueName, FalseName; 8009 8010 std::tie(TrueTy, TrueName) = 8011 shouldNotPrintDirectly(Context, 8012 CO->getTrueExpr()->getType(), 8013 CO->getTrueExpr()); 8014 std::tie(FalseTy, FalseName) = 8015 shouldNotPrintDirectly(Context, 8016 CO->getFalseExpr()->getType(), 8017 CO->getFalseExpr()); 8018 8019 if (TrueTy == FalseTy) 8020 return std::make_pair(TrueTy, TrueName); 8021 else if (TrueTy.isNull()) 8022 return std::make_pair(FalseTy, FalseName); 8023 else if (FalseTy.isNull()) 8024 return std::make_pair(TrueTy, TrueName); 8025 } 8026 8027 return std::make_pair(QualType(), StringRef()); 8028 } 8029 8030 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8031 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8032 /// type do not count. 8033 static bool 8034 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8035 QualType From = ICE->getSubExpr()->getType(); 8036 QualType To = ICE->getType(); 8037 // It's an integer promotion if the destination type is the promoted 8038 // source type. 8039 if (ICE->getCastKind() == CK_IntegralCast && 8040 From->isPromotableIntegerType() && 8041 S.Context.getPromotedIntegerType(From) == To) 8042 return true; 8043 // Look through vector types, since we do default argument promotion for 8044 // those in OpenCL. 8045 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8046 From = VecTy->getElementType(); 8047 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8048 To = VecTy->getElementType(); 8049 // It's a floating promotion if the source type is a lower rank. 8050 return ICE->getCastKind() == CK_FloatingCast && 8051 S.Context.getFloatingTypeOrder(From, To) < 0; 8052 } 8053 8054 bool 8055 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8056 const char *StartSpecifier, 8057 unsigned SpecifierLen, 8058 const Expr *E) { 8059 using namespace analyze_format_string; 8060 using namespace analyze_printf; 8061 8062 // Now type check the data expression that matches the 8063 // format specifier. 8064 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8065 if (!AT.isValid()) 8066 return true; 8067 8068 QualType ExprTy = E->getType(); 8069 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8070 ExprTy = TET->getUnderlyingExpr()->getType(); 8071 } 8072 8073 const analyze_printf::ArgType::MatchKind Match = 8074 AT.matchesType(S.Context, ExprTy); 8075 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic; 8076 if (Match == analyze_printf::ArgType::Match) 8077 return true; 8078 8079 // Look through argument promotions for our error message's reported type. 8080 // This includes the integral and floating promotions, but excludes array 8081 // and function pointer decay (seeing that an argument intended to be a 8082 // string has type 'char [6]' is probably more confusing than 'char *') and 8083 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8084 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8085 if (isArithmeticArgumentPromotion(S, ICE)) { 8086 E = ICE->getSubExpr(); 8087 ExprTy = E->getType(); 8088 8089 // Check if we didn't match because of an implicit cast from a 'char' 8090 // or 'short' to an 'int'. This is done because printf is a varargs 8091 // function. 8092 if (ICE->getType() == S.Context.IntTy || 8093 ICE->getType() == S.Context.UnsignedIntTy) { 8094 // All further checking is done on the subexpression. 8095 if (AT.matchesType(S.Context, ExprTy)) 8096 return true; 8097 } 8098 } 8099 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8100 // Special case for 'a', which has type 'int' in C. 8101 // Note, however, that we do /not/ want to treat multibyte constants like 8102 // 'MooV' as characters! This form is deprecated but still exists. 8103 if (ExprTy == S.Context.IntTy) 8104 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8105 ExprTy = S.Context.CharTy; 8106 } 8107 8108 // Look through enums to their underlying type. 8109 bool IsEnum = false; 8110 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8111 ExprTy = EnumTy->getDecl()->getIntegerType(); 8112 IsEnum = true; 8113 } 8114 8115 // %C in an Objective-C context prints a unichar, not a wchar_t. 8116 // If the argument is an integer of some kind, believe the %C and suggest 8117 // a cast instead of changing the conversion specifier. 8118 QualType IntendedTy = ExprTy; 8119 if (isObjCContext() && 8120 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8121 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8122 !ExprTy->isCharType()) { 8123 // 'unichar' is defined as a typedef of unsigned short, but we should 8124 // prefer using the typedef if it is visible. 8125 IntendedTy = S.Context.UnsignedShortTy; 8126 8127 // While we are here, check if the value is an IntegerLiteral that happens 8128 // to be within the valid range. 8129 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8130 const llvm::APInt &V = IL->getValue(); 8131 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8132 return true; 8133 } 8134 8135 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8136 Sema::LookupOrdinaryName); 8137 if (S.LookupName(Result, S.getCurScope())) { 8138 NamedDecl *ND = Result.getFoundDecl(); 8139 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8140 if (TD->getUnderlyingType() == IntendedTy) 8141 IntendedTy = S.Context.getTypedefType(TD); 8142 } 8143 } 8144 } 8145 8146 // Special-case some of Darwin's platform-independence types by suggesting 8147 // casts to primitive types that are known to be large enough. 8148 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8149 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8150 QualType CastTy; 8151 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8152 if (!CastTy.isNull()) { 8153 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8154 // (long in ASTContext). Only complain to pedants. 8155 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8156 (AT.isSizeT() || AT.isPtrdiffT()) && 8157 AT.matchesType(S.Context, CastTy)) 8158 Pedantic = true; 8159 IntendedTy = CastTy; 8160 ShouldNotPrintDirectly = true; 8161 } 8162 } 8163 8164 // We may be able to offer a FixItHint if it is a supported type. 8165 PrintfSpecifier fixedFS = FS; 8166 bool Success = 8167 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8168 8169 if (Success) { 8170 // Get the fix string from the fixed format specifier 8171 SmallString<16> buf; 8172 llvm::raw_svector_ostream os(buf); 8173 fixedFS.toString(os); 8174 8175 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8176 8177 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8178 unsigned Diag = 8179 Pedantic 8180 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8181 : diag::warn_format_conversion_argument_type_mismatch; 8182 // In this case, the specifier is wrong and should be changed to match 8183 // the argument. 8184 EmitFormatDiagnostic(S.PDiag(Diag) 8185 << AT.getRepresentativeTypeName(S.Context) 8186 << IntendedTy << IsEnum << E->getSourceRange(), 8187 E->getBeginLoc(), 8188 /*IsStringLocation*/ false, SpecRange, 8189 FixItHint::CreateReplacement(SpecRange, os.str())); 8190 } else { 8191 // The canonical type for formatting this value is different from the 8192 // actual type of the expression. (This occurs, for example, with Darwin's 8193 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8194 // should be printed as 'long' for 64-bit compatibility.) 8195 // Rather than emitting a normal format/argument mismatch, we want to 8196 // add a cast to the recommended type (and correct the format string 8197 // if necessary). 8198 SmallString<16> CastBuf; 8199 llvm::raw_svector_ostream CastFix(CastBuf); 8200 CastFix << "("; 8201 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8202 CastFix << ")"; 8203 8204 SmallVector<FixItHint,4> Hints; 8205 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8206 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8207 8208 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8209 // If there's already a cast present, just replace it. 8210 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8211 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8212 8213 } else if (!requiresParensToAddCast(E)) { 8214 // If the expression has high enough precedence, 8215 // just write the C-style cast. 8216 Hints.push_back( 8217 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8218 } else { 8219 // Otherwise, add parens around the expression as well as the cast. 8220 CastFix << "("; 8221 Hints.push_back( 8222 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8223 8224 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8225 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8226 } 8227 8228 if (ShouldNotPrintDirectly) { 8229 // The expression has a type that should not be printed directly. 8230 // We extract the name from the typedef because we don't want to show 8231 // the underlying type in the diagnostic. 8232 StringRef Name; 8233 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8234 Name = TypedefTy->getDecl()->getName(); 8235 else 8236 Name = CastTyName; 8237 unsigned Diag = Pedantic 8238 ? diag::warn_format_argument_needs_cast_pedantic 8239 : diag::warn_format_argument_needs_cast; 8240 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8241 << E->getSourceRange(), 8242 E->getBeginLoc(), /*IsStringLocation=*/false, 8243 SpecRange, Hints); 8244 } else { 8245 // In this case, the expression could be printed using a different 8246 // specifier, but we've decided that the specifier is probably correct 8247 // and we should cast instead. Just use the normal warning message. 8248 EmitFormatDiagnostic( 8249 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8250 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8251 << E->getSourceRange(), 8252 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8253 } 8254 } 8255 } else { 8256 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8257 SpecifierLen); 8258 // Since the warning for passing non-POD types to variadic functions 8259 // was deferred until now, we emit a warning for non-POD 8260 // arguments here. 8261 switch (S.isValidVarArgType(ExprTy)) { 8262 case Sema::VAK_Valid: 8263 case Sema::VAK_ValidInCXX11: { 8264 unsigned Diag = 8265 Pedantic 8266 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8267 : diag::warn_format_conversion_argument_type_mismatch; 8268 8269 EmitFormatDiagnostic( 8270 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8271 << IsEnum << CSR << E->getSourceRange(), 8272 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8273 break; 8274 } 8275 case Sema::VAK_Undefined: 8276 case Sema::VAK_MSVCUndefined: 8277 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8278 << S.getLangOpts().CPlusPlus11 << ExprTy 8279 << CallType 8280 << AT.getRepresentativeTypeName(S.Context) << CSR 8281 << E->getSourceRange(), 8282 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8283 checkForCStrMembers(AT, E); 8284 break; 8285 8286 case Sema::VAK_Invalid: 8287 if (ExprTy->isObjCObjectType()) 8288 EmitFormatDiagnostic( 8289 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8290 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8291 << AT.getRepresentativeTypeName(S.Context) << CSR 8292 << E->getSourceRange(), 8293 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8294 else 8295 // FIXME: If this is an initializer list, suggest removing the braces 8296 // or inserting a cast to the target type. 8297 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8298 << isa<InitListExpr>(E) << ExprTy << CallType 8299 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8300 break; 8301 } 8302 8303 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8304 "format string specifier index out of range"); 8305 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8306 } 8307 8308 return true; 8309 } 8310 8311 //===--- CHECK: Scanf format string checking ------------------------------===// 8312 8313 namespace { 8314 8315 class CheckScanfHandler : public CheckFormatHandler { 8316 public: 8317 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8318 const Expr *origFormatExpr, Sema::FormatStringType type, 8319 unsigned firstDataArg, unsigned numDataArgs, 8320 const char *beg, bool hasVAListArg, 8321 ArrayRef<const Expr *> Args, unsigned formatIdx, 8322 bool inFunctionCall, Sema::VariadicCallType CallType, 8323 llvm::SmallBitVector &CheckedVarArgs, 8324 UncoveredArgHandler &UncoveredArg) 8325 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8326 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8327 inFunctionCall, CallType, CheckedVarArgs, 8328 UncoveredArg) {} 8329 8330 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8331 const char *startSpecifier, 8332 unsigned specifierLen) override; 8333 8334 bool HandleInvalidScanfConversionSpecifier( 8335 const analyze_scanf::ScanfSpecifier &FS, 8336 const char *startSpecifier, 8337 unsigned specifierLen) override; 8338 8339 void HandleIncompleteScanList(const char *start, const char *end) override; 8340 }; 8341 8342 } // namespace 8343 8344 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8345 const char *end) { 8346 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8347 getLocationOfByte(end), /*IsStringLocation*/true, 8348 getSpecifierRange(start, end - start)); 8349 } 8350 8351 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8352 const analyze_scanf::ScanfSpecifier &FS, 8353 const char *startSpecifier, 8354 unsigned specifierLen) { 8355 const analyze_scanf::ScanfConversionSpecifier &CS = 8356 FS.getConversionSpecifier(); 8357 8358 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8359 getLocationOfByte(CS.getStart()), 8360 startSpecifier, specifierLen, 8361 CS.getStart(), CS.getLength()); 8362 } 8363 8364 bool CheckScanfHandler::HandleScanfSpecifier( 8365 const analyze_scanf::ScanfSpecifier &FS, 8366 const char *startSpecifier, 8367 unsigned specifierLen) { 8368 using namespace analyze_scanf; 8369 using namespace analyze_format_string; 8370 8371 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8372 8373 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8374 // be used to decide if we are using positional arguments consistently. 8375 if (FS.consumesDataArgument()) { 8376 if (atFirstArg) { 8377 atFirstArg = false; 8378 usesPositionalArgs = FS.usesPositionalArg(); 8379 } 8380 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8381 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8382 startSpecifier, specifierLen); 8383 return false; 8384 } 8385 } 8386 8387 // Check if the field with is non-zero. 8388 const OptionalAmount &Amt = FS.getFieldWidth(); 8389 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8390 if (Amt.getConstantAmount() == 0) { 8391 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8392 Amt.getConstantLength()); 8393 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8394 getLocationOfByte(Amt.getStart()), 8395 /*IsStringLocation*/true, R, 8396 FixItHint::CreateRemoval(R)); 8397 } 8398 } 8399 8400 if (!FS.consumesDataArgument()) { 8401 // FIXME: Technically specifying a precision or field width here 8402 // makes no sense. Worth issuing a warning at some point. 8403 return true; 8404 } 8405 8406 // Consume the argument. 8407 unsigned argIndex = FS.getArgIndex(); 8408 if (argIndex < NumDataArgs) { 8409 // The check to see if the argIndex is valid will come later. 8410 // We set the bit here because we may exit early from this 8411 // function if we encounter some other error. 8412 CoveredArgs.set(argIndex); 8413 } 8414 8415 // Check the length modifier is valid with the given conversion specifier. 8416 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8417 S.getLangOpts())) 8418 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8419 diag::warn_format_nonsensical_length); 8420 else if (!FS.hasStandardLengthModifier()) 8421 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8422 else if (!FS.hasStandardLengthConversionCombination()) 8423 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8424 diag::warn_format_non_standard_conversion_spec); 8425 8426 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8427 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8428 8429 // The remaining checks depend on the data arguments. 8430 if (HasVAListArg) 8431 return true; 8432 8433 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8434 return false; 8435 8436 // Check that the argument type matches the format specifier. 8437 const Expr *Ex = getDataArg(argIndex); 8438 if (!Ex) 8439 return true; 8440 8441 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8442 8443 if (!AT.isValid()) { 8444 return true; 8445 } 8446 8447 analyze_format_string::ArgType::MatchKind Match = 8448 AT.matchesType(S.Context, Ex->getType()); 8449 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8450 if (Match == analyze_format_string::ArgType::Match) 8451 return true; 8452 8453 ScanfSpecifier fixedFS = FS; 8454 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8455 S.getLangOpts(), S.Context); 8456 8457 unsigned Diag = 8458 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8459 : diag::warn_format_conversion_argument_type_mismatch; 8460 8461 if (Success) { 8462 // Get the fix string from the fixed format specifier. 8463 SmallString<128> buf; 8464 llvm::raw_svector_ostream os(buf); 8465 fixedFS.toString(os); 8466 8467 EmitFormatDiagnostic( 8468 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8469 << Ex->getType() << false << Ex->getSourceRange(), 8470 Ex->getBeginLoc(), 8471 /*IsStringLocation*/ false, 8472 getSpecifierRange(startSpecifier, specifierLen), 8473 FixItHint::CreateReplacement( 8474 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8475 } else { 8476 EmitFormatDiagnostic(S.PDiag(Diag) 8477 << AT.getRepresentativeTypeName(S.Context) 8478 << Ex->getType() << false << Ex->getSourceRange(), 8479 Ex->getBeginLoc(), 8480 /*IsStringLocation*/ false, 8481 getSpecifierRange(startSpecifier, specifierLen)); 8482 } 8483 8484 return true; 8485 } 8486 8487 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8488 const Expr *OrigFormatExpr, 8489 ArrayRef<const Expr *> Args, 8490 bool HasVAListArg, unsigned format_idx, 8491 unsigned firstDataArg, 8492 Sema::FormatStringType Type, 8493 bool inFunctionCall, 8494 Sema::VariadicCallType CallType, 8495 llvm::SmallBitVector &CheckedVarArgs, 8496 UncoveredArgHandler &UncoveredArg) { 8497 // CHECK: is the format string a wide literal? 8498 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8499 CheckFormatHandler::EmitFormatDiagnostic( 8500 S, inFunctionCall, Args[format_idx], 8501 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8502 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8503 return; 8504 } 8505 8506 // Str - The format string. NOTE: this is NOT null-terminated! 8507 StringRef StrRef = FExpr->getString(); 8508 const char *Str = StrRef.data(); 8509 // Account for cases where the string literal is truncated in a declaration. 8510 const ConstantArrayType *T = 8511 S.Context.getAsConstantArrayType(FExpr->getType()); 8512 assert(T && "String literal not of constant array type!"); 8513 size_t TypeSize = T->getSize().getZExtValue(); 8514 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8515 const unsigned numDataArgs = Args.size() - firstDataArg; 8516 8517 // Emit a warning if the string literal is truncated and does not contain an 8518 // embedded null character. 8519 if (TypeSize <= StrRef.size() && 8520 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8521 CheckFormatHandler::EmitFormatDiagnostic( 8522 S, inFunctionCall, Args[format_idx], 8523 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8524 FExpr->getBeginLoc(), 8525 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8526 return; 8527 } 8528 8529 // CHECK: empty format string? 8530 if (StrLen == 0 && numDataArgs > 0) { 8531 CheckFormatHandler::EmitFormatDiagnostic( 8532 S, inFunctionCall, Args[format_idx], 8533 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8534 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8535 return; 8536 } 8537 8538 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8539 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8540 Type == Sema::FST_OSTrace) { 8541 CheckPrintfHandler H( 8542 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8543 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8544 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8545 CheckedVarArgs, UncoveredArg); 8546 8547 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8548 S.getLangOpts(), 8549 S.Context.getTargetInfo(), 8550 Type == Sema::FST_FreeBSDKPrintf)) 8551 H.DoneProcessing(); 8552 } else if (Type == Sema::FST_Scanf) { 8553 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8554 numDataArgs, Str, HasVAListArg, Args, format_idx, 8555 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8556 8557 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8558 S.getLangOpts(), 8559 S.Context.getTargetInfo())) 8560 H.DoneProcessing(); 8561 } // TODO: handle other formats 8562 } 8563 8564 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8565 // Str - The format string. NOTE: this is NOT null-terminated! 8566 StringRef StrRef = FExpr->getString(); 8567 const char *Str = StrRef.data(); 8568 // Account for cases where the string literal is truncated in a declaration. 8569 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8570 assert(T && "String literal not of constant array type!"); 8571 size_t TypeSize = T->getSize().getZExtValue(); 8572 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8573 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8574 getLangOpts(), 8575 Context.getTargetInfo()); 8576 } 8577 8578 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8579 8580 // Returns the related absolute value function that is larger, of 0 if one 8581 // does not exist. 8582 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8583 switch (AbsFunction) { 8584 default: 8585 return 0; 8586 8587 case Builtin::BI__builtin_abs: 8588 return Builtin::BI__builtin_labs; 8589 case Builtin::BI__builtin_labs: 8590 return Builtin::BI__builtin_llabs; 8591 case Builtin::BI__builtin_llabs: 8592 return 0; 8593 8594 case Builtin::BI__builtin_fabsf: 8595 return Builtin::BI__builtin_fabs; 8596 case Builtin::BI__builtin_fabs: 8597 return Builtin::BI__builtin_fabsl; 8598 case Builtin::BI__builtin_fabsl: 8599 return 0; 8600 8601 case Builtin::BI__builtin_cabsf: 8602 return Builtin::BI__builtin_cabs; 8603 case Builtin::BI__builtin_cabs: 8604 return Builtin::BI__builtin_cabsl; 8605 case Builtin::BI__builtin_cabsl: 8606 return 0; 8607 8608 case Builtin::BIabs: 8609 return Builtin::BIlabs; 8610 case Builtin::BIlabs: 8611 return Builtin::BIllabs; 8612 case Builtin::BIllabs: 8613 return 0; 8614 8615 case Builtin::BIfabsf: 8616 return Builtin::BIfabs; 8617 case Builtin::BIfabs: 8618 return Builtin::BIfabsl; 8619 case Builtin::BIfabsl: 8620 return 0; 8621 8622 case Builtin::BIcabsf: 8623 return Builtin::BIcabs; 8624 case Builtin::BIcabs: 8625 return Builtin::BIcabsl; 8626 case Builtin::BIcabsl: 8627 return 0; 8628 } 8629 } 8630 8631 // Returns the argument type of the absolute value function. 8632 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8633 unsigned AbsType) { 8634 if (AbsType == 0) 8635 return QualType(); 8636 8637 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8638 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8639 if (Error != ASTContext::GE_None) 8640 return QualType(); 8641 8642 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8643 if (!FT) 8644 return QualType(); 8645 8646 if (FT->getNumParams() != 1) 8647 return QualType(); 8648 8649 return FT->getParamType(0); 8650 } 8651 8652 // Returns the best absolute value function, or zero, based on type and 8653 // current absolute value function. 8654 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8655 unsigned AbsFunctionKind) { 8656 unsigned BestKind = 0; 8657 uint64_t ArgSize = Context.getTypeSize(ArgType); 8658 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8659 Kind = getLargerAbsoluteValueFunction(Kind)) { 8660 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8661 if (Context.getTypeSize(ParamType) >= ArgSize) { 8662 if (BestKind == 0) 8663 BestKind = Kind; 8664 else if (Context.hasSameType(ParamType, ArgType)) { 8665 BestKind = Kind; 8666 break; 8667 } 8668 } 8669 } 8670 return BestKind; 8671 } 8672 8673 enum AbsoluteValueKind { 8674 AVK_Integer, 8675 AVK_Floating, 8676 AVK_Complex 8677 }; 8678 8679 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8680 if (T->isIntegralOrEnumerationType()) 8681 return AVK_Integer; 8682 if (T->isRealFloatingType()) 8683 return AVK_Floating; 8684 if (T->isAnyComplexType()) 8685 return AVK_Complex; 8686 8687 llvm_unreachable("Type not integer, floating, or complex"); 8688 } 8689 8690 // Changes the absolute value function to a different type. Preserves whether 8691 // the function is a builtin. 8692 static unsigned changeAbsFunction(unsigned AbsKind, 8693 AbsoluteValueKind ValueKind) { 8694 switch (ValueKind) { 8695 case AVK_Integer: 8696 switch (AbsKind) { 8697 default: 8698 return 0; 8699 case Builtin::BI__builtin_fabsf: 8700 case Builtin::BI__builtin_fabs: 8701 case Builtin::BI__builtin_fabsl: 8702 case Builtin::BI__builtin_cabsf: 8703 case Builtin::BI__builtin_cabs: 8704 case Builtin::BI__builtin_cabsl: 8705 return Builtin::BI__builtin_abs; 8706 case Builtin::BIfabsf: 8707 case Builtin::BIfabs: 8708 case Builtin::BIfabsl: 8709 case Builtin::BIcabsf: 8710 case Builtin::BIcabs: 8711 case Builtin::BIcabsl: 8712 return Builtin::BIabs; 8713 } 8714 case AVK_Floating: 8715 switch (AbsKind) { 8716 default: 8717 return 0; 8718 case Builtin::BI__builtin_abs: 8719 case Builtin::BI__builtin_labs: 8720 case Builtin::BI__builtin_llabs: 8721 case Builtin::BI__builtin_cabsf: 8722 case Builtin::BI__builtin_cabs: 8723 case Builtin::BI__builtin_cabsl: 8724 return Builtin::BI__builtin_fabsf; 8725 case Builtin::BIabs: 8726 case Builtin::BIlabs: 8727 case Builtin::BIllabs: 8728 case Builtin::BIcabsf: 8729 case Builtin::BIcabs: 8730 case Builtin::BIcabsl: 8731 return Builtin::BIfabsf; 8732 } 8733 case AVK_Complex: 8734 switch (AbsKind) { 8735 default: 8736 return 0; 8737 case Builtin::BI__builtin_abs: 8738 case Builtin::BI__builtin_labs: 8739 case Builtin::BI__builtin_llabs: 8740 case Builtin::BI__builtin_fabsf: 8741 case Builtin::BI__builtin_fabs: 8742 case Builtin::BI__builtin_fabsl: 8743 return Builtin::BI__builtin_cabsf; 8744 case Builtin::BIabs: 8745 case Builtin::BIlabs: 8746 case Builtin::BIllabs: 8747 case Builtin::BIfabsf: 8748 case Builtin::BIfabs: 8749 case Builtin::BIfabsl: 8750 return Builtin::BIcabsf; 8751 } 8752 } 8753 llvm_unreachable("Unable to convert function"); 8754 } 8755 8756 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8757 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8758 if (!FnInfo) 8759 return 0; 8760 8761 switch (FDecl->getBuiltinID()) { 8762 default: 8763 return 0; 8764 case Builtin::BI__builtin_abs: 8765 case Builtin::BI__builtin_fabs: 8766 case Builtin::BI__builtin_fabsf: 8767 case Builtin::BI__builtin_fabsl: 8768 case Builtin::BI__builtin_labs: 8769 case Builtin::BI__builtin_llabs: 8770 case Builtin::BI__builtin_cabs: 8771 case Builtin::BI__builtin_cabsf: 8772 case Builtin::BI__builtin_cabsl: 8773 case Builtin::BIabs: 8774 case Builtin::BIlabs: 8775 case Builtin::BIllabs: 8776 case Builtin::BIfabs: 8777 case Builtin::BIfabsf: 8778 case Builtin::BIfabsl: 8779 case Builtin::BIcabs: 8780 case Builtin::BIcabsf: 8781 case Builtin::BIcabsl: 8782 return FDecl->getBuiltinID(); 8783 } 8784 llvm_unreachable("Unknown Builtin type"); 8785 } 8786 8787 // If the replacement is valid, emit a note with replacement function. 8788 // Additionally, suggest including the proper header if not already included. 8789 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8790 unsigned AbsKind, QualType ArgType) { 8791 bool EmitHeaderHint = true; 8792 const char *HeaderName = nullptr; 8793 const char *FunctionName = nullptr; 8794 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8795 FunctionName = "std::abs"; 8796 if (ArgType->isIntegralOrEnumerationType()) { 8797 HeaderName = "cstdlib"; 8798 } else if (ArgType->isRealFloatingType()) { 8799 HeaderName = "cmath"; 8800 } else { 8801 llvm_unreachable("Invalid Type"); 8802 } 8803 8804 // Lookup all std::abs 8805 if (NamespaceDecl *Std = S.getStdNamespace()) { 8806 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8807 R.suppressDiagnostics(); 8808 S.LookupQualifiedName(R, Std); 8809 8810 for (const auto *I : R) { 8811 const FunctionDecl *FDecl = nullptr; 8812 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8813 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8814 } else { 8815 FDecl = dyn_cast<FunctionDecl>(I); 8816 } 8817 if (!FDecl) 8818 continue; 8819 8820 // Found std::abs(), check that they are the right ones. 8821 if (FDecl->getNumParams() != 1) 8822 continue; 8823 8824 // Check that the parameter type can handle the argument. 8825 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8826 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8827 S.Context.getTypeSize(ArgType) <= 8828 S.Context.getTypeSize(ParamType)) { 8829 // Found a function, don't need the header hint. 8830 EmitHeaderHint = false; 8831 break; 8832 } 8833 } 8834 } 8835 } else { 8836 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8837 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8838 8839 if (HeaderName) { 8840 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8841 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8842 R.suppressDiagnostics(); 8843 S.LookupName(R, S.getCurScope()); 8844 8845 if (R.isSingleResult()) { 8846 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8847 if (FD && FD->getBuiltinID() == AbsKind) { 8848 EmitHeaderHint = false; 8849 } else { 8850 return; 8851 } 8852 } else if (!R.empty()) { 8853 return; 8854 } 8855 } 8856 } 8857 8858 S.Diag(Loc, diag::note_replace_abs_function) 8859 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8860 8861 if (!HeaderName) 8862 return; 8863 8864 if (!EmitHeaderHint) 8865 return; 8866 8867 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8868 << FunctionName; 8869 } 8870 8871 template <std::size_t StrLen> 8872 static bool IsStdFunction(const FunctionDecl *FDecl, 8873 const char (&Str)[StrLen]) { 8874 if (!FDecl) 8875 return false; 8876 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8877 return false; 8878 if (!FDecl->isInStdNamespace()) 8879 return false; 8880 8881 return true; 8882 } 8883 8884 // Warn when using the wrong abs() function. 8885 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8886 const FunctionDecl *FDecl) { 8887 if (Call->getNumArgs() != 1) 8888 return; 8889 8890 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8891 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8892 if (AbsKind == 0 && !IsStdAbs) 8893 return; 8894 8895 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8896 QualType ParamType = Call->getArg(0)->getType(); 8897 8898 // Unsigned types cannot be negative. Suggest removing the absolute value 8899 // function call. 8900 if (ArgType->isUnsignedIntegerType()) { 8901 const char *FunctionName = 8902 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8903 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8904 Diag(Call->getExprLoc(), diag::note_remove_abs) 8905 << FunctionName 8906 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8907 return; 8908 } 8909 8910 // Taking the absolute value of a pointer is very suspicious, they probably 8911 // wanted to index into an array, dereference a pointer, call a function, etc. 8912 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8913 unsigned DiagType = 0; 8914 if (ArgType->isFunctionType()) 8915 DiagType = 1; 8916 else if (ArgType->isArrayType()) 8917 DiagType = 2; 8918 8919 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8920 return; 8921 } 8922 8923 // std::abs has overloads which prevent most of the absolute value problems 8924 // from occurring. 8925 if (IsStdAbs) 8926 return; 8927 8928 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8929 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8930 8931 // The argument and parameter are the same kind. Check if they are the right 8932 // size. 8933 if (ArgValueKind == ParamValueKind) { 8934 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8935 return; 8936 8937 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8938 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8939 << FDecl << ArgType << ParamType; 8940 8941 if (NewAbsKind == 0) 8942 return; 8943 8944 emitReplacement(*this, Call->getExprLoc(), 8945 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8946 return; 8947 } 8948 8949 // ArgValueKind != ParamValueKind 8950 // The wrong type of absolute value function was used. Attempt to find the 8951 // proper one. 8952 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8953 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8954 if (NewAbsKind == 0) 8955 return; 8956 8957 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8958 << FDecl << ParamValueKind << ArgValueKind; 8959 8960 emitReplacement(*this, Call->getExprLoc(), 8961 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8962 } 8963 8964 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8965 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8966 const FunctionDecl *FDecl) { 8967 if (!Call || !FDecl) return; 8968 8969 // Ignore template specializations and macros. 8970 if (inTemplateInstantiation()) return; 8971 if (Call->getExprLoc().isMacroID()) return; 8972 8973 // Only care about the one template argument, two function parameter std::max 8974 if (Call->getNumArgs() != 2) return; 8975 if (!IsStdFunction(FDecl, "max")) return; 8976 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8977 if (!ArgList) return; 8978 if (ArgList->size() != 1) return; 8979 8980 // Check that template type argument is unsigned integer. 8981 const auto& TA = ArgList->get(0); 8982 if (TA.getKind() != TemplateArgument::Type) return; 8983 QualType ArgType = TA.getAsType(); 8984 if (!ArgType->isUnsignedIntegerType()) return; 8985 8986 // See if either argument is a literal zero. 8987 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8988 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8989 if (!MTE) return false; 8990 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr()); 8991 if (!Num) return false; 8992 if (Num->getValue() != 0) return false; 8993 return true; 8994 }; 8995 8996 const Expr *FirstArg = Call->getArg(0); 8997 const Expr *SecondArg = Call->getArg(1); 8998 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8999 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9000 9001 // Only warn when exactly one argument is zero. 9002 if (IsFirstArgZero == IsSecondArgZero) return; 9003 9004 SourceRange FirstRange = FirstArg->getSourceRange(); 9005 SourceRange SecondRange = SecondArg->getSourceRange(); 9006 9007 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9008 9009 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9010 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9011 9012 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9013 SourceRange RemovalRange; 9014 if (IsFirstArgZero) { 9015 RemovalRange = SourceRange(FirstRange.getBegin(), 9016 SecondRange.getBegin().getLocWithOffset(-1)); 9017 } else { 9018 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9019 SecondRange.getEnd()); 9020 } 9021 9022 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9023 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9024 << FixItHint::CreateRemoval(RemovalRange); 9025 } 9026 9027 //===--- CHECK: Standard memory functions ---------------------------------===// 9028 9029 /// Takes the expression passed to the size_t parameter of functions 9030 /// such as memcmp, strncat, etc and warns if it's a comparison. 9031 /// 9032 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9033 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9034 IdentifierInfo *FnName, 9035 SourceLocation FnLoc, 9036 SourceLocation RParenLoc) { 9037 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9038 if (!Size) 9039 return false; 9040 9041 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9042 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9043 return false; 9044 9045 SourceRange SizeRange = Size->getSourceRange(); 9046 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9047 << SizeRange << FnName; 9048 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9049 << FnName 9050 << FixItHint::CreateInsertion( 9051 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9052 << FixItHint::CreateRemoval(RParenLoc); 9053 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9054 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9055 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9056 ")"); 9057 9058 return true; 9059 } 9060 9061 /// Determine whether the given type is or contains a dynamic class type 9062 /// (e.g., whether it has a vtable). 9063 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9064 bool &IsContained) { 9065 // Look through array types while ignoring qualifiers. 9066 const Type *Ty = T->getBaseElementTypeUnsafe(); 9067 IsContained = false; 9068 9069 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9070 RD = RD ? RD->getDefinition() : nullptr; 9071 if (!RD || RD->isInvalidDecl()) 9072 return nullptr; 9073 9074 if (RD->isDynamicClass()) 9075 return RD; 9076 9077 // Check all the fields. If any bases were dynamic, the class is dynamic. 9078 // It's impossible for a class to transitively contain itself by value, so 9079 // infinite recursion is impossible. 9080 for (auto *FD : RD->fields()) { 9081 bool SubContained; 9082 if (const CXXRecordDecl *ContainedRD = 9083 getContainedDynamicClass(FD->getType(), SubContained)) { 9084 IsContained = true; 9085 return ContainedRD; 9086 } 9087 } 9088 9089 return nullptr; 9090 } 9091 9092 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9093 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9094 if (Unary->getKind() == UETT_SizeOf) 9095 return Unary; 9096 return nullptr; 9097 } 9098 9099 /// If E is a sizeof expression, returns its argument expression, 9100 /// otherwise returns NULL. 9101 static const Expr *getSizeOfExprArg(const Expr *E) { 9102 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9103 if (!SizeOf->isArgumentType()) 9104 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9105 return nullptr; 9106 } 9107 9108 /// If E is a sizeof expression, returns its argument type. 9109 static QualType getSizeOfArgType(const Expr *E) { 9110 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9111 return SizeOf->getTypeOfArgument(); 9112 return QualType(); 9113 } 9114 9115 namespace { 9116 9117 struct SearchNonTrivialToInitializeField 9118 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9119 using Super = 9120 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9121 9122 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9123 9124 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9125 SourceLocation SL) { 9126 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9127 asDerived().visitArray(PDIK, AT, SL); 9128 return; 9129 } 9130 9131 Super::visitWithKind(PDIK, FT, SL); 9132 } 9133 9134 void visitARCStrong(QualType FT, SourceLocation SL) { 9135 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9136 } 9137 void visitARCWeak(QualType FT, SourceLocation SL) { 9138 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9139 } 9140 void visitStruct(QualType FT, SourceLocation SL) { 9141 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9142 visit(FD->getType(), FD->getLocation()); 9143 } 9144 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9145 const ArrayType *AT, SourceLocation SL) { 9146 visit(getContext().getBaseElementType(AT), SL); 9147 } 9148 void visitTrivial(QualType FT, SourceLocation SL) {} 9149 9150 static void diag(QualType RT, const Expr *E, Sema &S) { 9151 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9152 } 9153 9154 ASTContext &getContext() { return S.getASTContext(); } 9155 9156 const Expr *E; 9157 Sema &S; 9158 }; 9159 9160 struct SearchNonTrivialToCopyField 9161 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9162 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9163 9164 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9165 9166 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9167 SourceLocation SL) { 9168 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9169 asDerived().visitArray(PCK, AT, SL); 9170 return; 9171 } 9172 9173 Super::visitWithKind(PCK, FT, SL); 9174 } 9175 9176 void visitARCStrong(QualType FT, SourceLocation SL) { 9177 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9178 } 9179 void visitARCWeak(QualType FT, SourceLocation SL) { 9180 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9181 } 9182 void visitStruct(QualType FT, SourceLocation SL) { 9183 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9184 visit(FD->getType(), FD->getLocation()); 9185 } 9186 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9187 SourceLocation SL) { 9188 visit(getContext().getBaseElementType(AT), SL); 9189 } 9190 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9191 SourceLocation SL) {} 9192 void visitTrivial(QualType FT, SourceLocation SL) {} 9193 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9194 9195 static void diag(QualType RT, const Expr *E, Sema &S) { 9196 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9197 } 9198 9199 ASTContext &getContext() { return S.getASTContext(); } 9200 9201 const Expr *E; 9202 Sema &S; 9203 }; 9204 9205 } 9206 9207 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9208 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9209 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9210 9211 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9212 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9213 return false; 9214 9215 return doesExprLikelyComputeSize(BO->getLHS()) || 9216 doesExprLikelyComputeSize(BO->getRHS()); 9217 } 9218 9219 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9220 } 9221 9222 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9223 /// 9224 /// \code 9225 /// #define MACRO 0 9226 /// foo(MACRO); 9227 /// foo(0); 9228 /// \endcode 9229 /// 9230 /// This should return true for the first call to foo, but not for the second 9231 /// (regardless of whether foo is a macro or function). 9232 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9233 SourceLocation CallLoc, 9234 SourceLocation ArgLoc) { 9235 if (!CallLoc.isMacroID()) 9236 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9237 9238 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9239 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9240 } 9241 9242 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9243 /// last two arguments transposed. 9244 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9245 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9246 return; 9247 9248 const Expr *SizeArg = 9249 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9250 9251 auto isLiteralZero = [](const Expr *E) { 9252 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9253 }; 9254 9255 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9256 SourceLocation CallLoc = Call->getRParenLoc(); 9257 SourceManager &SM = S.getSourceManager(); 9258 if (isLiteralZero(SizeArg) && 9259 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9260 9261 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9262 9263 // Some platforms #define bzero to __builtin_memset. See if this is the 9264 // case, and if so, emit a better diagnostic. 9265 if (BId == Builtin::BIbzero || 9266 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9267 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9268 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9269 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9270 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9271 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9272 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9273 } 9274 return; 9275 } 9276 9277 // If the second argument to a memset is a sizeof expression and the third 9278 // isn't, this is also likely an error. This should catch 9279 // 'memset(buf, sizeof(buf), 0xff)'. 9280 if (BId == Builtin::BImemset && 9281 doesExprLikelyComputeSize(Call->getArg(1)) && 9282 !doesExprLikelyComputeSize(Call->getArg(2))) { 9283 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9284 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9285 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9286 return; 9287 } 9288 } 9289 9290 /// Check for dangerous or invalid arguments to memset(). 9291 /// 9292 /// This issues warnings on known problematic, dangerous or unspecified 9293 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9294 /// function calls. 9295 /// 9296 /// \param Call The call expression to diagnose. 9297 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9298 unsigned BId, 9299 IdentifierInfo *FnName) { 9300 assert(BId != 0); 9301 9302 // It is possible to have a non-standard definition of memset. Validate 9303 // we have enough arguments, and if not, abort further checking. 9304 unsigned ExpectedNumArgs = 9305 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9306 if (Call->getNumArgs() < ExpectedNumArgs) 9307 return; 9308 9309 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9310 BId == Builtin::BIstrndup ? 1 : 2); 9311 unsigned LenArg = 9312 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9313 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9314 9315 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9316 Call->getBeginLoc(), Call->getRParenLoc())) 9317 return; 9318 9319 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9320 CheckMemaccessSize(*this, BId, Call); 9321 9322 // We have special checking when the length is a sizeof expression. 9323 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9324 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9325 llvm::FoldingSetNodeID SizeOfArgID; 9326 9327 // Although widely used, 'bzero' is not a standard function. Be more strict 9328 // with the argument types before allowing diagnostics and only allow the 9329 // form bzero(ptr, sizeof(...)). 9330 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9331 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9332 return; 9333 9334 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9335 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9336 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9337 9338 QualType DestTy = Dest->getType(); 9339 QualType PointeeTy; 9340 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9341 PointeeTy = DestPtrTy->getPointeeType(); 9342 9343 // Never warn about void type pointers. This can be used to suppress 9344 // false positives. 9345 if (PointeeTy->isVoidType()) 9346 continue; 9347 9348 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9349 // actually comparing the expressions for equality. Because computing the 9350 // expression IDs can be expensive, we only do this if the diagnostic is 9351 // enabled. 9352 if (SizeOfArg && 9353 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9354 SizeOfArg->getExprLoc())) { 9355 // We only compute IDs for expressions if the warning is enabled, and 9356 // cache the sizeof arg's ID. 9357 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9358 SizeOfArg->Profile(SizeOfArgID, Context, true); 9359 llvm::FoldingSetNodeID DestID; 9360 Dest->Profile(DestID, Context, true); 9361 if (DestID == SizeOfArgID) { 9362 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9363 // over sizeof(src) as well. 9364 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9365 StringRef ReadableName = FnName->getName(); 9366 9367 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9368 if (UnaryOp->getOpcode() == UO_AddrOf) 9369 ActionIdx = 1; // If its an address-of operator, just remove it. 9370 if (!PointeeTy->isIncompleteType() && 9371 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9372 ActionIdx = 2; // If the pointee's size is sizeof(char), 9373 // suggest an explicit length. 9374 9375 // If the function is defined as a builtin macro, do not show macro 9376 // expansion. 9377 SourceLocation SL = SizeOfArg->getExprLoc(); 9378 SourceRange DSR = Dest->getSourceRange(); 9379 SourceRange SSR = SizeOfArg->getSourceRange(); 9380 SourceManager &SM = getSourceManager(); 9381 9382 if (SM.isMacroArgExpansion(SL)) { 9383 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9384 SL = SM.getSpellingLoc(SL); 9385 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9386 SM.getSpellingLoc(DSR.getEnd())); 9387 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9388 SM.getSpellingLoc(SSR.getEnd())); 9389 } 9390 9391 DiagRuntimeBehavior(SL, SizeOfArg, 9392 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9393 << ReadableName 9394 << PointeeTy 9395 << DestTy 9396 << DSR 9397 << SSR); 9398 DiagRuntimeBehavior(SL, SizeOfArg, 9399 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9400 << ActionIdx 9401 << SSR); 9402 9403 break; 9404 } 9405 } 9406 9407 // Also check for cases where the sizeof argument is the exact same 9408 // type as the memory argument, and where it points to a user-defined 9409 // record type. 9410 if (SizeOfArgTy != QualType()) { 9411 if (PointeeTy->isRecordType() && 9412 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9413 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9414 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9415 << FnName << SizeOfArgTy << ArgIdx 9416 << PointeeTy << Dest->getSourceRange() 9417 << LenExpr->getSourceRange()); 9418 break; 9419 } 9420 } 9421 } else if (DestTy->isArrayType()) { 9422 PointeeTy = DestTy; 9423 } 9424 9425 if (PointeeTy == QualType()) 9426 continue; 9427 9428 // Always complain about dynamic classes. 9429 bool IsContained; 9430 if (const CXXRecordDecl *ContainedRD = 9431 getContainedDynamicClass(PointeeTy, IsContained)) { 9432 9433 unsigned OperationType = 0; 9434 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9435 // "overwritten" if we're warning about the destination for any call 9436 // but memcmp; otherwise a verb appropriate to the call. 9437 if (ArgIdx != 0 || IsCmp) { 9438 if (BId == Builtin::BImemcpy) 9439 OperationType = 1; 9440 else if(BId == Builtin::BImemmove) 9441 OperationType = 2; 9442 else if (IsCmp) 9443 OperationType = 3; 9444 } 9445 9446 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9447 PDiag(diag::warn_dyn_class_memaccess) 9448 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9449 << IsContained << ContainedRD << OperationType 9450 << Call->getCallee()->getSourceRange()); 9451 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9452 BId != Builtin::BImemset) 9453 DiagRuntimeBehavior( 9454 Dest->getExprLoc(), Dest, 9455 PDiag(diag::warn_arc_object_memaccess) 9456 << ArgIdx << FnName << PointeeTy 9457 << Call->getCallee()->getSourceRange()); 9458 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9459 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9460 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9461 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9462 PDiag(diag::warn_cstruct_memaccess) 9463 << ArgIdx << FnName << PointeeTy << 0); 9464 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9465 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9466 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9467 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9468 PDiag(diag::warn_cstruct_memaccess) 9469 << ArgIdx << FnName << PointeeTy << 1); 9470 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9471 } else { 9472 continue; 9473 } 9474 } else 9475 continue; 9476 9477 DiagRuntimeBehavior( 9478 Dest->getExprLoc(), Dest, 9479 PDiag(diag::note_bad_memaccess_silence) 9480 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9481 break; 9482 } 9483 } 9484 9485 // A little helper routine: ignore addition and subtraction of integer literals. 9486 // This intentionally does not ignore all integer constant expressions because 9487 // we don't want to remove sizeof(). 9488 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9489 Ex = Ex->IgnoreParenCasts(); 9490 9491 while (true) { 9492 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9493 if (!BO || !BO->isAdditiveOp()) 9494 break; 9495 9496 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9497 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9498 9499 if (isa<IntegerLiteral>(RHS)) 9500 Ex = LHS; 9501 else if (isa<IntegerLiteral>(LHS)) 9502 Ex = RHS; 9503 else 9504 break; 9505 } 9506 9507 return Ex; 9508 } 9509 9510 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9511 ASTContext &Context) { 9512 // Only handle constant-sized or VLAs, but not flexible members. 9513 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9514 // Only issue the FIXIT for arrays of size > 1. 9515 if (CAT->getSize().getSExtValue() <= 1) 9516 return false; 9517 } else if (!Ty->isVariableArrayType()) { 9518 return false; 9519 } 9520 return true; 9521 } 9522 9523 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9524 // be the size of the source, instead of the destination. 9525 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9526 IdentifierInfo *FnName) { 9527 9528 // Don't crash if the user has the wrong number of arguments 9529 unsigned NumArgs = Call->getNumArgs(); 9530 if ((NumArgs != 3) && (NumArgs != 4)) 9531 return; 9532 9533 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9534 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9535 const Expr *CompareWithSrc = nullptr; 9536 9537 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9538 Call->getBeginLoc(), Call->getRParenLoc())) 9539 return; 9540 9541 // Look for 'strlcpy(dst, x, sizeof(x))' 9542 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9543 CompareWithSrc = Ex; 9544 else { 9545 // Look for 'strlcpy(dst, x, strlen(x))' 9546 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9547 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9548 SizeCall->getNumArgs() == 1) 9549 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9550 } 9551 } 9552 9553 if (!CompareWithSrc) 9554 return; 9555 9556 // Determine if the argument to sizeof/strlen is equal to the source 9557 // argument. In principle there's all kinds of things you could do 9558 // here, for instance creating an == expression and evaluating it with 9559 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9560 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9561 if (!SrcArgDRE) 9562 return; 9563 9564 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9565 if (!CompareWithSrcDRE || 9566 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9567 return; 9568 9569 const Expr *OriginalSizeArg = Call->getArg(2); 9570 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9571 << OriginalSizeArg->getSourceRange() << FnName; 9572 9573 // Output a FIXIT hint if the destination is an array (rather than a 9574 // pointer to an array). This could be enhanced to handle some 9575 // pointers if we know the actual size, like if DstArg is 'array+2' 9576 // we could say 'sizeof(array)-2'. 9577 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9578 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9579 return; 9580 9581 SmallString<128> sizeString; 9582 llvm::raw_svector_ostream OS(sizeString); 9583 OS << "sizeof("; 9584 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9585 OS << ")"; 9586 9587 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9588 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9589 OS.str()); 9590 } 9591 9592 /// Check if two expressions refer to the same declaration. 9593 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9594 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9595 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9596 return D1->getDecl() == D2->getDecl(); 9597 return false; 9598 } 9599 9600 static const Expr *getStrlenExprArg(const Expr *E) { 9601 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9602 const FunctionDecl *FD = CE->getDirectCallee(); 9603 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9604 return nullptr; 9605 return CE->getArg(0)->IgnoreParenCasts(); 9606 } 9607 return nullptr; 9608 } 9609 9610 // Warn on anti-patterns as the 'size' argument to strncat. 9611 // The correct size argument should look like following: 9612 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9613 void Sema::CheckStrncatArguments(const CallExpr *CE, 9614 IdentifierInfo *FnName) { 9615 // Don't crash if the user has the wrong number of arguments. 9616 if (CE->getNumArgs() < 3) 9617 return; 9618 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9619 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9620 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9621 9622 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9623 CE->getRParenLoc())) 9624 return; 9625 9626 // Identify common expressions, which are wrongly used as the size argument 9627 // to strncat and may lead to buffer overflows. 9628 unsigned PatternType = 0; 9629 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9630 // - sizeof(dst) 9631 if (referToTheSameDecl(SizeOfArg, DstArg)) 9632 PatternType = 1; 9633 // - sizeof(src) 9634 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9635 PatternType = 2; 9636 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9637 if (BE->getOpcode() == BO_Sub) { 9638 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9639 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9640 // - sizeof(dst) - strlen(dst) 9641 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9642 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9643 PatternType = 1; 9644 // - sizeof(src) - (anything) 9645 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9646 PatternType = 2; 9647 } 9648 } 9649 9650 if (PatternType == 0) 9651 return; 9652 9653 // Generate the diagnostic. 9654 SourceLocation SL = LenArg->getBeginLoc(); 9655 SourceRange SR = LenArg->getSourceRange(); 9656 SourceManager &SM = getSourceManager(); 9657 9658 // If the function is defined as a builtin macro, do not show macro expansion. 9659 if (SM.isMacroArgExpansion(SL)) { 9660 SL = SM.getSpellingLoc(SL); 9661 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9662 SM.getSpellingLoc(SR.getEnd())); 9663 } 9664 9665 // Check if the destination is an array (rather than a pointer to an array). 9666 QualType DstTy = DstArg->getType(); 9667 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9668 Context); 9669 if (!isKnownSizeArray) { 9670 if (PatternType == 1) 9671 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9672 else 9673 Diag(SL, diag::warn_strncat_src_size) << SR; 9674 return; 9675 } 9676 9677 if (PatternType == 1) 9678 Diag(SL, diag::warn_strncat_large_size) << SR; 9679 else 9680 Diag(SL, diag::warn_strncat_src_size) << SR; 9681 9682 SmallString<128> sizeString; 9683 llvm::raw_svector_ostream OS(sizeString); 9684 OS << "sizeof("; 9685 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9686 OS << ") - "; 9687 OS << "strlen("; 9688 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9689 OS << ") - 1"; 9690 9691 Diag(SL, diag::note_strncat_wrong_size) 9692 << FixItHint::CreateReplacement(SR, OS.str()); 9693 } 9694 9695 void 9696 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9697 SourceLocation ReturnLoc, 9698 bool isObjCMethod, 9699 const AttrVec *Attrs, 9700 const FunctionDecl *FD) { 9701 // Check if the return value is null but should not be. 9702 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9703 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9704 CheckNonNullExpr(*this, RetValExp)) 9705 Diag(ReturnLoc, diag::warn_null_ret) 9706 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9707 9708 // C++11 [basic.stc.dynamic.allocation]p4: 9709 // If an allocation function declared with a non-throwing 9710 // exception-specification fails to allocate storage, it shall return 9711 // a null pointer. Any other allocation function that fails to allocate 9712 // storage shall indicate failure only by throwing an exception [...] 9713 if (FD) { 9714 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9715 if (Op == OO_New || Op == OO_Array_New) { 9716 const FunctionProtoType *Proto 9717 = FD->getType()->castAs<FunctionProtoType>(); 9718 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9719 CheckNonNullExpr(*this, RetValExp)) 9720 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9721 << FD << getLangOpts().CPlusPlus11; 9722 } 9723 } 9724 } 9725 9726 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9727 9728 /// Check for comparisons of floating point operands using != and ==. 9729 /// Issue a warning if these are no self-comparisons, as they are not likely 9730 /// to do what the programmer intended. 9731 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9732 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9733 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9734 9735 // Special case: check for x == x (which is OK). 9736 // Do not emit warnings for such cases. 9737 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9738 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9739 if (DRL->getDecl() == DRR->getDecl()) 9740 return; 9741 9742 // Special case: check for comparisons against literals that can be exactly 9743 // represented by APFloat. In such cases, do not emit a warning. This 9744 // is a heuristic: often comparison against such literals are used to 9745 // detect if a value in a variable has not changed. This clearly can 9746 // lead to false negatives. 9747 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9748 if (FLL->isExact()) 9749 return; 9750 } else 9751 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9752 if (FLR->isExact()) 9753 return; 9754 9755 // Check for comparisons with builtin types. 9756 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9757 if (CL->getBuiltinCallee()) 9758 return; 9759 9760 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9761 if (CR->getBuiltinCallee()) 9762 return; 9763 9764 // Emit the diagnostic. 9765 Diag(Loc, diag::warn_floatingpoint_eq) 9766 << LHS->getSourceRange() << RHS->getSourceRange(); 9767 } 9768 9769 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9770 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9771 9772 namespace { 9773 9774 /// Structure recording the 'active' range of an integer-valued 9775 /// expression. 9776 struct IntRange { 9777 /// The number of bits active in the int. 9778 unsigned Width; 9779 9780 /// True if the int is known not to have negative values. 9781 bool NonNegative; 9782 9783 IntRange(unsigned Width, bool NonNegative) 9784 : Width(Width), NonNegative(NonNegative) {} 9785 9786 /// Returns the range of the bool type. 9787 static IntRange forBoolType() { 9788 return IntRange(1, true); 9789 } 9790 9791 /// Returns the range of an opaque value of the given integral type. 9792 static IntRange forValueOfType(ASTContext &C, QualType T) { 9793 return forValueOfCanonicalType(C, 9794 T->getCanonicalTypeInternal().getTypePtr()); 9795 } 9796 9797 /// Returns the range of an opaque value of a canonical integral type. 9798 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9799 assert(T->isCanonicalUnqualified()); 9800 9801 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9802 T = VT->getElementType().getTypePtr(); 9803 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9804 T = CT->getElementType().getTypePtr(); 9805 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9806 T = AT->getValueType().getTypePtr(); 9807 9808 if (!C.getLangOpts().CPlusPlus) { 9809 // For enum types in C code, use the underlying datatype. 9810 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9811 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9812 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9813 // For enum types in C++, use the known bit width of the enumerators. 9814 EnumDecl *Enum = ET->getDecl(); 9815 // In C++11, enums can have a fixed underlying type. Use this type to 9816 // compute the range. 9817 if (Enum->isFixed()) { 9818 return IntRange(C.getIntWidth(QualType(T, 0)), 9819 !ET->isSignedIntegerOrEnumerationType()); 9820 } 9821 9822 unsigned NumPositive = Enum->getNumPositiveBits(); 9823 unsigned NumNegative = Enum->getNumNegativeBits(); 9824 9825 if (NumNegative == 0) 9826 return IntRange(NumPositive, true/*NonNegative*/); 9827 else 9828 return IntRange(std::max(NumPositive + 1, NumNegative), 9829 false/*NonNegative*/); 9830 } 9831 9832 const BuiltinType *BT = cast<BuiltinType>(T); 9833 assert(BT->isInteger()); 9834 9835 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9836 } 9837 9838 /// Returns the "target" range of a canonical integral type, i.e. 9839 /// the range of values expressible in the type. 9840 /// 9841 /// This matches forValueOfCanonicalType except that enums have the 9842 /// full range of their type, not the range of their enumerators. 9843 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9844 assert(T->isCanonicalUnqualified()); 9845 9846 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9847 T = VT->getElementType().getTypePtr(); 9848 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9849 T = CT->getElementType().getTypePtr(); 9850 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9851 T = AT->getValueType().getTypePtr(); 9852 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9853 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9854 9855 const BuiltinType *BT = cast<BuiltinType>(T); 9856 assert(BT->isInteger()); 9857 9858 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9859 } 9860 9861 /// Returns the supremum of two ranges: i.e. their conservative merge. 9862 static IntRange join(IntRange L, IntRange R) { 9863 return IntRange(std::max(L.Width, R.Width), 9864 L.NonNegative && R.NonNegative); 9865 } 9866 9867 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9868 static IntRange meet(IntRange L, IntRange R) { 9869 return IntRange(std::min(L.Width, R.Width), 9870 L.NonNegative || R.NonNegative); 9871 } 9872 }; 9873 9874 } // namespace 9875 9876 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9877 unsigned MaxWidth) { 9878 if (value.isSigned() && value.isNegative()) 9879 return IntRange(value.getMinSignedBits(), false); 9880 9881 if (value.getBitWidth() > MaxWidth) 9882 value = value.trunc(MaxWidth); 9883 9884 // isNonNegative() just checks the sign bit without considering 9885 // signedness. 9886 return IntRange(value.getActiveBits(), true); 9887 } 9888 9889 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9890 unsigned MaxWidth) { 9891 if (result.isInt()) 9892 return GetValueRange(C, result.getInt(), MaxWidth); 9893 9894 if (result.isVector()) { 9895 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9896 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9897 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9898 R = IntRange::join(R, El); 9899 } 9900 return R; 9901 } 9902 9903 if (result.isComplexInt()) { 9904 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9905 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9906 return IntRange::join(R, I); 9907 } 9908 9909 // This can happen with lossless casts to intptr_t of "based" lvalues. 9910 // Assume it might use arbitrary bits. 9911 // FIXME: The only reason we need to pass the type in here is to get 9912 // the sign right on this one case. It would be nice if APValue 9913 // preserved this. 9914 assert(result.isLValue() || result.isAddrLabelDiff()); 9915 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9916 } 9917 9918 static QualType GetExprType(const Expr *E) { 9919 QualType Ty = E->getType(); 9920 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9921 Ty = AtomicRHS->getValueType(); 9922 return Ty; 9923 } 9924 9925 /// Pseudo-evaluate the given integer expression, estimating the 9926 /// range of values it might take. 9927 /// 9928 /// \param MaxWidth - the width to which the value will be truncated 9929 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 9930 bool InConstantContext) { 9931 E = E->IgnoreParens(); 9932 9933 // Try a full evaluation first. 9934 Expr::EvalResult result; 9935 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9936 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9937 9938 // I think we only want to look through implicit casts here; if the 9939 // user has an explicit widening cast, we should treat the value as 9940 // being of the new, wider type. 9941 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9942 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9943 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 9944 9945 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9946 9947 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9948 CE->getCastKind() == CK_BooleanToSignedIntegral; 9949 9950 // Assume that non-integer casts can span the full range of the type. 9951 if (!isIntegerCast) 9952 return OutputTypeRange; 9953 9954 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 9955 std::min(MaxWidth, OutputTypeRange.Width), 9956 InConstantContext); 9957 9958 // Bail out if the subexpr's range is as wide as the cast type. 9959 if (SubRange.Width >= OutputTypeRange.Width) 9960 return OutputTypeRange; 9961 9962 // Otherwise, we take the smaller width, and we're non-negative if 9963 // either the output type or the subexpr is. 9964 return IntRange(SubRange.Width, 9965 SubRange.NonNegative || OutputTypeRange.NonNegative); 9966 } 9967 9968 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9969 // If we can fold the condition, just take that operand. 9970 bool CondResult; 9971 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9972 return GetExprRange(C, 9973 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 9974 MaxWidth, InConstantContext); 9975 9976 // Otherwise, conservatively merge. 9977 IntRange L = 9978 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 9979 IntRange R = 9980 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 9981 return IntRange::join(L, R); 9982 } 9983 9984 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9985 switch (BO->getOpcode()) { 9986 case BO_Cmp: 9987 llvm_unreachable("builtin <=> should have class type"); 9988 9989 // Boolean-valued operations are single-bit and positive. 9990 case BO_LAnd: 9991 case BO_LOr: 9992 case BO_LT: 9993 case BO_GT: 9994 case BO_LE: 9995 case BO_GE: 9996 case BO_EQ: 9997 case BO_NE: 9998 return IntRange::forBoolType(); 9999 10000 // The type of the assignments is the type of the LHS, so the RHS 10001 // is not necessarily the same type. 10002 case BO_MulAssign: 10003 case BO_DivAssign: 10004 case BO_RemAssign: 10005 case BO_AddAssign: 10006 case BO_SubAssign: 10007 case BO_XorAssign: 10008 case BO_OrAssign: 10009 // TODO: bitfields? 10010 return IntRange::forValueOfType(C, GetExprType(E)); 10011 10012 // Simple assignments just pass through the RHS, which will have 10013 // been coerced to the LHS type. 10014 case BO_Assign: 10015 // TODO: bitfields? 10016 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10017 10018 // Operations with opaque sources are black-listed. 10019 case BO_PtrMemD: 10020 case BO_PtrMemI: 10021 return IntRange::forValueOfType(C, GetExprType(E)); 10022 10023 // Bitwise-and uses the *infinum* of the two source ranges. 10024 case BO_And: 10025 case BO_AndAssign: 10026 return IntRange::meet( 10027 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10028 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10029 10030 // Left shift gets black-listed based on a judgement call. 10031 case BO_Shl: 10032 // ...except that we want to treat '1 << (blah)' as logically 10033 // positive. It's an important idiom. 10034 if (IntegerLiteral *I 10035 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10036 if (I->getValue() == 1) { 10037 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10038 return IntRange(R.Width, /*NonNegative*/ true); 10039 } 10040 } 10041 LLVM_FALLTHROUGH; 10042 10043 case BO_ShlAssign: 10044 return IntRange::forValueOfType(C, GetExprType(E)); 10045 10046 // Right shift by a constant can narrow its left argument. 10047 case BO_Shr: 10048 case BO_ShrAssign: { 10049 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10050 10051 // If the shift amount is a positive constant, drop the width by 10052 // that much. 10053 llvm::APSInt shift; 10054 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10055 shift.isNonNegative()) { 10056 unsigned zext = shift.getZExtValue(); 10057 if (zext >= L.Width) 10058 L.Width = (L.NonNegative ? 0 : 1); 10059 else 10060 L.Width -= zext; 10061 } 10062 10063 return L; 10064 } 10065 10066 // Comma acts as its right operand. 10067 case BO_Comma: 10068 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10069 10070 // Black-list pointer subtractions. 10071 case BO_Sub: 10072 if (BO->getLHS()->getType()->isPointerType()) 10073 return IntRange::forValueOfType(C, GetExprType(E)); 10074 break; 10075 10076 // The width of a division result is mostly determined by the size 10077 // of the LHS. 10078 case BO_Div: { 10079 // Don't 'pre-truncate' the operands. 10080 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10081 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10082 10083 // If the divisor is constant, use that. 10084 llvm::APSInt divisor; 10085 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10086 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10087 if (log2 >= L.Width) 10088 L.Width = (L.NonNegative ? 0 : 1); 10089 else 10090 L.Width = std::min(L.Width - log2, MaxWidth); 10091 return L; 10092 } 10093 10094 // Otherwise, just use the LHS's width. 10095 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10096 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10097 } 10098 10099 // The result of a remainder can't be larger than the result of 10100 // either side. 10101 case BO_Rem: { 10102 // Don't 'pre-truncate' the operands. 10103 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10104 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10105 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10106 10107 IntRange meet = IntRange::meet(L, R); 10108 meet.Width = std::min(meet.Width, MaxWidth); 10109 return meet; 10110 } 10111 10112 // The default behavior is okay for these. 10113 case BO_Mul: 10114 case BO_Add: 10115 case BO_Xor: 10116 case BO_Or: 10117 break; 10118 } 10119 10120 // The default case is to treat the operation as if it were closed 10121 // on the narrowest type that encompasses both operands. 10122 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10123 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10124 return IntRange::join(L, R); 10125 } 10126 10127 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10128 switch (UO->getOpcode()) { 10129 // Boolean-valued operations are white-listed. 10130 case UO_LNot: 10131 return IntRange::forBoolType(); 10132 10133 // Operations with opaque sources are black-listed. 10134 case UO_Deref: 10135 case UO_AddrOf: // should be impossible 10136 return IntRange::forValueOfType(C, GetExprType(E)); 10137 10138 default: 10139 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10140 } 10141 } 10142 10143 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10144 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10145 10146 if (const auto *BitField = E->getSourceBitField()) 10147 return IntRange(BitField->getBitWidthValue(C), 10148 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10149 10150 return IntRange::forValueOfType(C, GetExprType(E)); 10151 } 10152 10153 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10154 bool InConstantContext) { 10155 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10156 } 10157 10158 /// Checks whether the given value, which currently has the given 10159 /// source semantics, has the same value when coerced through the 10160 /// target semantics. 10161 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10162 const llvm::fltSemantics &Src, 10163 const llvm::fltSemantics &Tgt) { 10164 llvm::APFloat truncated = value; 10165 10166 bool ignored; 10167 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10168 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10169 10170 return truncated.bitwiseIsEqual(value); 10171 } 10172 10173 /// Checks whether the given value, which currently has the given 10174 /// source semantics, has the same value when coerced through the 10175 /// target semantics. 10176 /// 10177 /// The value might be a vector of floats (or a complex number). 10178 static bool IsSameFloatAfterCast(const APValue &value, 10179 const llvm::fltSemantics &Src, 10180 const llvm::fltSemantics &Tgt) { 10181 if (value.isFloat()) 10182 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10183 10184 if (value.isVector()) { 10185 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10186 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10187 return false; 10188 return true; 10189 } 10190 10191 assert(value.isComplexFloat()); 10192 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10193 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10194 } 10195 10196 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC); 10197 10198 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10199 // Suppress cases where we are comparing against an enum constant. 10200 if (const DeclRefExpr *DR = 10201 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10202 if (isa<EnumConstantDecl>(DR->getDecl())) 10203 return true; 10204 10205 // Suppress cases where the value is expanded from a macro, unless that macro 10206 // is how a language represents a boolean literal. This is the case in both C 10207 // and Objective-C. 10208 SourceLocation BeginLoc = E->getBeginLoc(); 10209 if (BeginLoc.isMacroID()) { 10210 StringRef MacroName = Lexer::getImmediateMacroName( 10211 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10212 return MacroName != "YES" && MacroName != "NO" && 10213 MacroName != "true" && MacroName != "false"; 10214 } 10215 10216 return false; 10217 } 10218 10219 static bool isKnownToHaveUnsignedValue(Expr *E) { 10220 return E->getType()->isIntegerType() && 10221 (!E->getType()->isSignedIntegerType() || 10222 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10223 } 10224 10225 namespace { 10226 /// The promoted range of values of a type. In general this has the 10227 /// following structure: 10228 /// 10229 /// |-----------| . . . |-----------| 10230 /// ^ ^ ^ ^ 10231 /// Min HoleMin HoleMax Max 10232 /// 10233 /// ... where there is only a hole if a signed type is promoted to unsigned 10234 /// (in which case Min and Max are the smallest and largest representable 10235 /// values). 10236 struct PromotedRange { 10237 // Min, or HoleMax if there is a hole. 10238 llvm::APSInt PromotedMin; 10239 // Max, or HoleMin if there is a hole. 10240 llvm::APSInt PromotedMax; 10241 10242 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10243 if (R.Width == 0) 10244 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10245 else if (R.Width >= BitWidth && !Unsigned) { 10246 // Promotion made the type *narrower*. This happens when promoting 10247 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10248 // Treat all values of 'signed int' as being in range for now. 10249 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10250 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10251 } else { 10252 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10253 .extOrTrunc(BitWidth); 10254 PromotedMin.setIsUnsigned(Unsigned); 10255 10256 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10257 .extOrTrunc(BitWidth); 10258 PromotedMax.setIsUnsigned(Unsigned); 10259 } 10260 } 10261 10262 // Determine whether this range is contiguous (has no hole). 10263 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10264 10265 // Where a constant value is within the range. 10266 enum ComparisonResult { 10267 LT = 0x1, 10268 LE = 0x2, 10269 GT = 0x4, 10270 GE = 0x8, 10271 EQ = 0x10, 10272 NE = 0x20, 10273 InRangeFlag = 0x40, 10274 10275 Less = LE | LT | NE, 10276 Min = LE | InRangeFlag, 10277 InRange = InRangeFlag, 10278 Max = GE | InRangeFlag, 10279 Greater = GE | GT | NE, 10280 10281 OnlyValue = LE | GE | EQ | InRangeFlag, 10282 InHole = NE 10283 }; 10284 10285 ComparisonResult compare(const llvm::APSInt &Value) const { 10286 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10287 Value.isUnsigned() == PromotedMin.isUnsigned()); 10288 if (!isContiguous()) { 10289 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10290 if (Value.isMinValue()) return Min; 10291 if (Value.isMaxValue()) return Max; 10292 if (Value >= PromotedMin) return InRange; 10293 if (Value <= PromotedMax) return InRange; 10294 return InHole; 10295 } 10296 10297 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10298 case -1: return Less; 10299 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10300 case 1: 10301 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10302 case -1: return InRange; 10303 case 0: return Max; 10304 case 1: return Greater; 10305 } 10306 } 10307 10308 llvm_unreachable("impossible compare result"); 10309 } 10310 10311 static llvm::Optional<StringRef> 10312 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10313 if (Op == BO_Cmp) { 10314 ComparisonResult LTFlag = LT, GTFlag = GT; 10315 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10316 10317 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10318 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10319 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10320 return llvm::None; 10321 } 10322 10323 ComparisonResult TrueFlag, FalseFlag; 10324 if (Op == BO_EQ) { 10325 TrueFlag = EQ; 10326 FalseFlag = NE; 10327 } else if (Op == BO_NE) { 10328 TrueFlag = NE; 10329 FalseFlag = EQ; 10330 } else { 10331 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10332 TrueFlag = LT; 10333 FalseFlag = GE; 10334 } else { 10335 TrueFlag = GT; 10336 FalseFlag = LE; 10337 } 10338 if (Op == BO_GE || Op == BO_LE) 10339 std::swap(TrueFlag, FalseFlag); 10340 } 10341 if (R & TrueFlag) 10342 return StringRef("true"); 10343 if (R & FalseFlag) 10344 return StringRef("false"); 10345 return llvm::None; 10346 } 10347 }; 10348 } 10349 10350 static bool HasEnumType(Expr *E) { 10351 // Strip off implicit integral promotions. 10352 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10353 if (ICE->getCastKind() != CK_IntegralCast && 10354 ICE->getCastKind() != CK_NoOp) 10355 break; 10356 E = ICE->getSubExpr(); 10357 } 10358 10359 return E->getType()->isEnumeralType(); 10360 } 10361 10362 static int classifyConstantValue(Expr *Constant) { 10363 // The values of this enumeration are used in the diagnostics 10364 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10365 enum ConstantValueKind { 10366 Miscellaneous = 0, 10367 LiteralTrue, 10368 LiteralFalse 10369 }; 10370 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10371 return BL->getValue() ? ConstantValueKind::LiteralTrue 10372 : ConstantValueKind::LiteralFalse; 10373 return ConstantValueKind::Miscellaneous; 10374 } 10375 10376 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10377 Expr *Constant, Expr *Other, 10378 const llvm::APSInt &Value, 10379 bool RhsConstant) { 10380 if (S.inTemplateInstantiation()) 10381 return false; 10382 10383 Expr *OriginalOther = Other; 10384 10385 Constant = Constant->IgnoreParenImpCasts(); 10386 Other = Other->IgnoreParenImpCasts(); 10387 10388 // Suppress warnings on tautological comparisons between values of the same 10389 // enumeration type. There are only two ways we could warn on this: 10390 // - If the constant is outside the range of representable values of 10391 // the enumeration. In such a case, we should warn about the cast 10392 // to enumeration type, not about the comparison. 10393 // - If the constant is the maximum / minimum in-range value. For an 10394 // enumeratin type, such comparisons can be meaningful and useful. 10395 if (Constant->getType()->isEnumeralType() && 10396 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10397 return false; 10398 10399 // TODO: Investigate using GetExprRange() to get tighter bounds 10400 // on the bit ranges. 10401 QualType OtherT = Other->getType(); 10402 if (const auto *AT = OtherT->getAs<AtomicType>()) 10403 OtherT = AT->getValueType(); 10404 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10405 10406 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10407 // (Namely, macOS). 10408 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10409 S.NSAPIObj->isObjCBOOLType(OtherT) && 10410 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10411 10412 // Whether we're treating Other as being a bool because of the form of 10413 // expression despite it having another type (typically 'int' in C). 10414 bool OtherIsBooleanDespiteType = 10415 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10416 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10417 OtherRange = IntRange::forBoolType(); 10418 10419 // Determine the promoted range of the other type and see if a comparison of 10420 // the constant against that range is tautological. 10421 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10422 Value.isUnsigned()); 10423 auto Cmp = OtherPromotedRange.compare(Value); 10424 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10425 if (!Result) 10426 return false; 10427 10428 // Suppress the diagnostic for an in-range comparison if the constant comes 10429 // from a macro or enumerator. We don't want to diagnose 10430 // 10431 // some_long_value <= INT_MAX 10432 // 10433 // when sizeof(int) == sizeof(long). 10434 bool InRange = Cmp & PromotedRange::InRangeFlag; 10435 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10436 return false; 10437 10438 // If this is a comparison to an enum constant, include that 10439 // constant in the diagnostic. 10440 const EnumConstantDecl *ED = nullptr; 10441 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10442 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10443 10444 // Should be enough for uint128 (39 decimal digits) 10445 SmallString<64> PrettySourceValue; 10446 llvm::raw_svector_ostream OS(PrettySourceValue); 10447 if (ED) { 10448 OS << '\'' << *ED << "' (" << Value << ")"; 10449 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10450 Constant->IgnoreParenImpCasts())) { 10451 OS << (BL->getValue() ? "YES" : "NO"); 10452 } else { 10453 OS << Value; 10454 } 10455 10456 if (IsObjCSignedCharBool) { 10457 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10458 S.PDiag(diag::warn_tautological_compare_objc_bool) 10459 << OS.str() << *Result); 10460 return true; 10461 } 10462 10463 // FIXME: We use a somewhat different formatting for the in-range cases and 10464 // cases involving boolean values for historical reasons. We should pick a 10465 // consistent way of presenting these diagnostics. 10466 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10467 10468 S.DiagRuntimeBehavior( 10469 E->getOperatorLoc(), E, 10470 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10471 : diag::warn_tautological_bool_compare) 10472 << OS.str() << classifyConstantValue(Constant) << OtherT 10473 << OtherIsBooleanDespiteType << *Result 10474 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10475 } else { 10476 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10477 ? (HasEnumType(OriginalOther) 10478 ? diag::warn_unsigned_enum_always_true_comparison 10479 : diag::warn_unsigned_always_true_comparison) 10480 : diag::warn_tautological_constant_compare; 10481 10482 S.Diag(E->getOperatorLoc(), Diag) 10483 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10484 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10485 } 10486 10487 return true; 10488 } 10489 10490 /// Analyze the operands of the given comparison. Implements the 10491 /// fallback case from AnalyzeComparison. 10492 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10493 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10494 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10495 } 10496 10497 /// Implements -Wsign-compare. 10498 /// 10499 /// \param E the binary operator to check for warnings 10500 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10501 // The type the comparison is being performed in. 10502 QualType T = E->getLHS()->getType(); 10503 10504 // Only analyze comparison operators where both sides have been converted to 10505 // the same type. 10506 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10507 return AnalyzeImpConvsInComparison(S, E); 10508 10509 // Don't analyze value-dependent comparisons directly. 10510 if (E->isValueDependent()) 10511 return AnalyzeImpConvsInComparison(S, E); 10512 10513 Expr *LHS = E->getLHS(); 10514 Expr *RHS = E->getRHS(); 10515 10516 if (T->isIntegralType(S.Context)) { 10517 llvm::APSInt RHSValue; 10518 llvm::APSInt LHSValue; 10519 10520 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10521 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10522 10523 // We don't care about expressions whose result is a constant. 10524 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10525 return AnalyzeImpConvsInComparison(S, E); 10526 10527 // We only care about expressions where just one side is literal 10528 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10529 // Is the constant on the RHS or LHS? 10530 const bool RhsConstant = IsRHSIntegralLiteral; 10531 Expr *Const = RhsConstant ? RHS : LHS; 10532 Expr *Other = RhsConstant ? LHS : RHS; 10533 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10534 10535 // Check whether an integer constant comparison results in a value 10536 // of 'true' or 'false'. 10537 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10538 return AnalyzeImpConvsInComparison(S, E); 10539 } 10540 } 10541 10542 if (!T->hasUnsignedIntegerRepresentation()) { 10543 // We don't do anything special if this isn't an unsigned integral 10544 // comparison: we're only interested in integral comparisons, and 10545 // signed comparisons only happen in cases we don't care to warn about. 10546 return AnalyzeImpConvsInComparison(S, E); 10547 } 10548 10549 LHS = LHS->IgnoreParenImpCasts(); 10550 RHS = RHS->IgnoreParenImpCasts(); 10551 10552 if (!S.getLangOpts().CPlusPlus) { 10553 // Avoid warning about comparison of integers with different signs when 10554 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10555 // the type of `E`. 10556 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10557 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10558 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10559 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10560 } 10561 10562 // Check to see if one of the (unmodified) operands is of different 10563 // signedness. 10564 Expr *signedOperand, *unsignedOperand; 10565 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10566 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10567 "unsigned comparison between two signed integer expressions?"); 10568 signedOperand = LHS; 10569 unsignedOperand = RHS; 10570 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10571 signedOperand = RHS; 10572 unsignedOperand = LHS; 10573 } else { 10574 return AnalyzeImpConvsInComparison(S, E); 10575 } 10576 10577 // Otherwise, calculate the effective range of the signed operand. 10578 IntRange signedRange = 10579 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10580 10581 // Go ahead and analyze implicit conversions in the operands. Note 10582 // that we skip the implicit conversions on both sides. 10583 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10584 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10585 10586 // If the signed range is non-negative, -Wsign-compare won't fire. 10587 if (signedRange.NonNegative) 10588 return; 10589 10590 // For (in)equality comparisons, if the unsigned operand is a 10591 // constant which cannot collide with a overflowed signed operand, 10592 // then reinterpreting the signed operand as unsigned will not 10593 // change the result of the comparison. 10594 if (E->isEqualityOp()) { 10595 unsigned comparisonWidth = S.Context.getIntWidth(T); 10596 IntRange unsignedRange = 10597 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10598 10599 // We should never be unable to prove that the unsigned operand is 10600 // non-negative. 10601 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10602 10603 if (unsignedRange.Width < comparisonWidth) 10604 return; 10605 } 10606 10607 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10608 S.PDiag(diag::warn_mixed_sign_comparison) 10609 << LHS->getType() << RHS->getType() 10610 << LHS->getSourceRange() << RHS->getSourceRange()); 10611 } 10612 10613 /// Analyzes an attempt to assign the given value to a bitfield. 10614 /// 10615 /// Returns true if there was something fishy about the attempt. 10616 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10617 SourceLocation InitLoc) { 10618 assert(Bitfield->isBitField()); 10619 if (Bitfield->isInvalidDecl()) 10620 return false; 10621 10622 // White-list bool bitfields. 10623 QualType BitfieldType = Bitfield->getType(); 10624 if (BitfieldType->isBooleanType()) 10625 return false; 10626 10627 if (BitfieldType->isEnumeralType()) { 10628 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl(); 10629 // If the underlying enum type was not explicitly specified as an unsigned 10630 // type and the enum contain only positive values, MSVC++ will cause an 10631 // inconsistency by storing this as a signed type. 10632 if (S.getLangOpts().CPlusPlus11 && 10633 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10634 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10635 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10636 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10637 << BitfieldEnumDecl->getNameAsString(); 10638 } 10639 } 10640 10641 if (Bitfield->getType()->isBooleanType()) 10642 return false; 10643 10644 // Ignore value- or type-dependent expressions. 10645 if (Bitfield->getBitWidth()->isValueDependent() || 10646 Bitfield->getBitWidth()->isTypeDependent() || 10647 Init->isValueDependent() || 10648 Init->isTypeDependent()) 10649 return false; 10650 10651 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10652 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10653 10654 Expr::EvalResult Result; 10655 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10656 Expr::SE_AllowSideEffects)) { 10657 // The RHS is not constant. If the RHS has an enum type, make sure the 10658 // bitfield is wide enough to hold all the values of the enum without 10659 // truncation. 10660 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10661 EnumDecl *ED = EnumTy->getDecl(); 10662 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10663 10664 // Enum types are implicitly signed on Windows, so check if there are any 10665 // negative enumerators to see if the enum was intended to be signed or 10666 // not. 10667 bool SignedEnum = ED->getNumNegativeBits() > 0; 10668 10669 // Check for surprising sign changes when assigning enum values to a 10670 // bitfield of different signedness. If the bitfield is signed and we 10671 // have exactly the right number of bits to store this unsigned enum, 10672 // suggest changing the enum to an unsigned type. This typically happens 10673 // on Windows where unfixed enums always use an underlying type of 'int'. 10674 unsigned DiagID = 0; 10675 if (SignedEnum && !SignedBitfield) { 10676 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10677 } else if (SignedBitfield && !SignedEnum && 10678 ED->getNumPositiveBits() == FieldWidth) { 10679 DiagID = diag::warn_signed_bitfield_enum_conversion; 10680 } 10681 10682 if (DiagID) { 10683 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10684 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10685 SourceRange TypeRange = 10686 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10687 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10688 << SignedEnum << TypeRange; 10689 } 10690 10691 // Compute the required bitwidth. If the enum has negative values, we need 10692 // one more bit than the normal number of positive bits to represent the 10693 // sign bit. 10694 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10695 ED->getNumNegativeBits()) 10696 : ED->getNumPositiveBits(); 10697 10698 // Check the bitwidth. 10699 if (BitsNeeded > FieldWidth) { 10700 Expr *WidthExpr = Bitfield->getBitWidth(); 10701 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10702 << Bitfield << ED; 10703 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10704 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10705 } 10706 } 10707 10708 return false; 10709 } 10710 10711 llvm::APSInt Value = Result.Val.getInt(); 10712 10713 unsigned OriginalWidth = Value.getBitWidth(); 10714 10715 if (!Value.isSigned() || Value.isNegative()) 10716 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10717 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10718 OriginalWidth = Value.getMinSignedBits(); 10719 10720 if (OriginalWidth <= FieldWidth) 10721 return false; 10722 10723 // Compute the value which the bitfield will contain. 10724 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10725 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10726 10727 // Check whether the stored value is equal to the original value. 10728 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10729 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10730 return false; 10731 10732 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10733 // therefore don't strictly fit into a signed bitfield of width 1. 10734 if (FieldWidth == 1 && Value == 1) 10735 return false; 10736 10737 std::string PrettyValue = Value.toString(10); 10738 std::string PrettyTrunc = TruncatedValue.toString(10); 10739 10740 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10741 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10742 << Init->getSourceRange(); 10743 10744 return true; 10745 } 10746 10747 /// Analyze the given simple or compound assignment for warning-worthy 10748 /// operations. 10749 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10750 // Just recurse on the LHS. 10751 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10752 10753 // We want to recurse on the RHS as normal unless we're assigning to 10754 // a bitfield. 10755 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10756 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10757 E->getOperatorLoc())) { 10758 // Recurse, ignoring any implicit conversions on the RHS. 10759 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10760 E->getOperatorLoc()); 10761 } 10762 } 10763 10764 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10765 10766 // Diagnose implicitly sequentially-consistent atomic assignment. 10767 if (E->getLHS()->getType()->isAtomicType()) 10768 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10769 } 10770 10771 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10772 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10773 SourceLocation CContext, unsigned diag, 10774 bool pruneControlFlow = false) { 10775 if (pruneControlFlow) { 10776 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10777 S.PDiag(diag) 10778 << SourceType << T << E->getSourceRange() 10779 << SourceRange(CContext)); 10780 return; 10781 } 10782 S.Diag(E->getExprLoc(), diag) 10783 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10784 } 10785 10786 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10787 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10788 SourceLocation CContext, 10789 unsigned diag, bool pruneControlFlow = false) { 10790 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10791 } 10792 10793 /// Diagnose an implicit cast from a floating point value to an integer value. 10794 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10795 SourceLocation CContext) { 10796 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10797 const bool PruneWarnings = S.inTemplateInstantiation(); 10798 10799 Expr *InnerE = E->IgnoreParenImpCasts(); 10800 // We also want to warn on, e.g., "int i = -1.234" 10801 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10802 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10803 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10804 10805 const bool IsLiteral = 10806 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10807 10808 llvm::APFloat Value(0.0); 10809 bool IsConstant = 10810 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10811 if (!IsConstant) { 10812 return DiagnoseImpCast(S, E, T, CContext, 10813 diag::warn_impcast_float_integer, PruneWarnings); 10814 } 10815 10816 bool isExact = false; 10817 10818 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10819 T->hasUnsignedIntegerRepresentation()); 10820 llvm::APFloat::opStatus Result = Value.convertToInteger( 10821 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10822 10823 if (Result == llvm::APFloat::opOK && isExact) { 10824 if (IsLiteral) return; 10825 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10826 PruneWarnings); 10827 } 10828 10829 // Conversion of a floating-point value to a non-bool integer where the 10830 // integral part cannot be represented by the integer type is undefined. 10831 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10832 return DiagnoseImpCast( 10833 S, E, T, CContext, 10834 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10835 : diag::warn_impcast_float_to_integer_out_of_range, 10836 PruneWarnings); 10837 10838 unsigned DiagID = 0; 10839 if (IsLiteral) { 10840 // Warn on floating point literal to integer. 10841 DiagID = diag::warn_impcast_literal_float_to_integer; 10842 } else if (IntegerValue == 0) { 10843 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10844 return DiagnoseImpCast(S, E, T, CContext, 10845 diag::warn_impcast_float_integer, PruneWarnings); 10846 } 10847 // Warn on non-zero to zero conversion. 10848 DiagID = diag::warn_impcast_float_to_integer_zero; 10849 } else { 10850 if (IntegerValue.isUnsigned()) { 10851 if (!IntegerValue.isMaxValue()) { 10852 return DiagnoseImpCast(S, E, T, CContext, 10853 diag::warn_impcast_float_integer, PruneWarnings); 10854 } 10855 } else { // IntegerValue.isSigned() 10856 if (!IntegerValue.isMaxSignedValue() && 10857 !IntegerValue.isMinSignedValue()) { 10858 return DiagnoseImpCast(S, E, T, CContext, 10859 diag::warn_impcast_float_integer, PruneWarnings); 10860 } 10861 } 10862 // Warn on evaluatable floating point expression to integer conversion. 10863 DiagID = diag::warn_impcast_float_to_integer; 10864 } 10865 10866 // FIXME: Force the precision of the source value down so we don't print 10867 // digits which are usually useless (we don't really care here if we 10868 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10869 // would automatically print the shortest representation, but it's a bit 10870 // tricky to implement. 10871 SmallString<16> PrettySourceValue; 10872 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10873 precision = (precision * 59 + 195) / 196; 10874 Value.toString(PrettySourceValue, precision); 10875 10876 SmallString<16> PrettyTargetValue; 10877 if (IsBool) 10878 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10879 else 10880 IntegerValue.toString(PrettyTargetValue); 10881 10882 if (PruneWarnings) { 10883 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10884 S.PDiag(DiagID) 10885 << E->getType() << T.getUnqualifiedType() 10886 << PrettySourceValue << PrettyTargetValue 10887 << E->getSourceRange() << SourceRange(CContext)); 10888 } else { 10889 S.Diag(E->getExprLoc(), DiagID) 10890 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10891 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10892 } 10893 } 10894 10895 /// Analyze the given compound assignment for the possible losing of 10896 /// floating-point precision. 10897 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10898 assert(isa<CompoundAssignOperator>(E) && 10899 "Must be compound assignment operation"); 10900 // Recurse on the LHS and RHS in here 10901 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10902 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10903 10904 if (E->getLHS()->getType()->isAtomicType()) 10905 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10906 10907 // Now check the outermost expression 10908 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10909 const auto *RBT = cast<CompoundAssignOperator>(E) 10910 ->getComputationResultType() 10911 ->getAs<BuiltinType>(); 10912 10913 // The below checks assume source is floating point. 10914 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10915 10916 // If source is floating point but target is an integer. 10917 if (ResultBT->isInteger()) 10918 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10919 E->getExprLoc(), diag::warn_impcast_float_integer); 10920 10921 if (!ResultBT->isFloatingPoint()) 10922 return; 10923 10924 // If both source and target are floating points, warn about losing precision. 10925 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10926 QualType(ResultBT, 0), QualType(RBT, 0)); 10927 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10928 // warn about dropping FP rank. 10929 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10930 diag::warn_impcast_float_result_precision); 10931 } 10932 10933 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10934 IntRange Range) { 10935 if (!Range.Width) return "0"; 10936 10937 llvm::APSInt ValueInRange = Value; 10938 ValueInRange.setIsSigned(!Range.NonNegative); 10939 ValueInRange = ValueInRange.trunc(Range.Width); 10940 return ValueInRange.toString(10); 10941 } 10942 10943 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10944 if (!isa<ImplicitCastExpr>(Ex)) 10945 return false; 10946 10947 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10948 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10949 const Type *Source = 10950 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10951 if (Target->isDependentType()) 10952 return false; 10953 10954 const BuiltinType *FloatCandidateBT = 10955 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10956 const Type *BoolCandidateType = ToBool ? Target : Source; 10957 10958 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10959 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10960 } 10961 10962 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10963 SourceLocation CC) { 10964 unsigned NumArgs = TheCall->getNumArgs(); 10965 for (unsigned i = 0; i < NumArgs; ++i) { 10966 Expr *CurrA = TheCall->getArg(i); 10967 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10968 continue; 10969 10970 bool IsSwapped = ((i > 0) && 10971 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10972 IsSwapped |= ((i < (NumArgs - 1)) && 10973 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10974 if (IsSwapped) { 10975 // Warn on this floating-point to bool conversion. 10976 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10977 CurrA->getType(), CC, 10978 diag::warn_impcast_floating_point_to_bool); 10979 } 10980 } 10981 } 10982 10983 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10984 SourceLocation CC) { 10985 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10986 E->getExprLoc())) 10987 return; 10988 10989 // Don't warn on functions which have return type nullptr_t. 10990 if (isa<CallExpr>(E)) 10991 return; 10992 10993 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10994 const Expr::NullPointerConstantKind NullKind = 10995 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10996 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10997 return; 10998 10999 // Return if target type is a safe conversion. 11000 if (T->isAnyPointerType() || T->isBlockPointerType() || 11001 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11002 return; 11003 11004 SourceLocation Loc = E->getSourceRange().getBegin(); 11005 11006 // Venture through the macro stacks to get to the source of macro arguments. 11007 // The new location is a better location than the complete location that was 11008 // passed in. 11009 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11010 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11011 11012 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11013 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11014 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11015 Loc, S.SourceMgr, S.getLangOpts()); 11016 if (MacroName == "NULL") 11017 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11018 } 11019 11020 // Only warn if the null and context location are in the same macro expansion. 11021 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11022 return; 11023 11024 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11025 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11026 << FixItHint::CreateReplacement(Loc, 11027 S.getFixItZeroLiteralForType(T, Loc)); 11028 } 11029 11030 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11031 ObjCArrayLiteral *ArrayLiteral); 11032 11033 static void 11034 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11035 ObjCDictionaryLiteral *DictionaryLiteral); 11036 11037 /// Check a single element within a collection literal against the 11038 /// target element type. 11039 static void checkObjCCollectionLiteralElement(Sema &S, 11040 QualType TargetElementType, 11041 Expr *Element, 11042 unsigned ElementKind) { 11043 // Skip a bitcast to 'id' or qualified 'id'. 11044 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11045 if (ICE->getCastKind() == CK_BitCast && 11046 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11047 Element = ICE->getSubExpr(); 11048 } 11049 11050 QualType ElementType = Element->getType(); 11051 ExprResult ElementResult(Element); 11052 if (ElementType->getAs<ObjCObjectPointerType>() && 11053 S.CheckSingleAssignmentConstraints(TargetElementType, 11054 ElementResult, 11055 false, false) 11056 != Sema::Compatible) { 11057 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11058 << ElementType << ElementKind << TargetElementType 11059 << Element->getSourceRange(); 11060 } 11061 11062 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11063 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11064 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11065 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11066 } 11067 11068 /// Check an Objective-C array literal being converted to the given 11069 /// target type. 11070 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11071 ObjCArrayLiteral *ArrayLiteral) { 11072 if (!S.NSArrayDecl) 11073 return; 11074 11075 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11076 if (!TargetObjCPtr) 11077 return; 11078 11079 if (TargetObjCPtr->isUnspecialized() || 11080 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11081 != S.NSArrayDecl->getCanonicalDecl()) 11082 return; 11083 11084 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11085 if (TypeArgs.size() != 1) 11086 return; 11087 11088 QualType TargetElementType = TypeArgs[0]; 11089 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11090 checkObjCCollectionLiteralElement(S, TargetElementType, 11091 ArrayLiteral->getElement(I), 11092 0); 11093 } 11094 } 11095 11096 /// Check an Objective-C dictionary literal being converted to the given 11097 /// target type. 11098 static void 11099 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11100 ObjCDictionaryLiteral *DictionaryLiteral) { 11101 if (!S.NSDictionaryDecl) 11102 return; 11103 11104 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11105 if (!TargetObjCPtr) 11106 return; 11107 11108 if (TargetObjCPtr->isUnspecialized() || 11109 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11110 != S.NSDictionaryDecl->getCanonicalDecl()) 11111 return; 11112 11113 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11114 if (TypeArgs.size() != 2) 11115 return; 11116 11117 QualType TargetKeyType = TypeArgs[0]; 11118 QualType TargetObjectType = TypeArgs[1]; 11119 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11120 auto Element = DictionaryLiteral->getKeyValueElement(I); 11121 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11122 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11123 } 11124 } 11125 11126 // Helper function to filter out cases for constant width constant conversion. 11127 // Don't warn on char array initialization or for non-decimal values. 11128 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11129 SourceLocation CC) { 11130 // If initializing from a constant, and the constant starts with '0', 11131 // then it is a binary, octal, or hexadecimal. Allow these constants 11132 // to fill all the bits, even if there is a sign change. 11133 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11134 const char FirstLiteralCharacter = 11135 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11136 if (FirstLiteralCharacter == '0') 11137 return false; 11138 } 11139 11140 // If the CC location points to a '{', and the type is char, then assume 11141 // assume it is an array initialization. 11142 if (CC.isValid() && T->isCharType()) { 11143 const char FirstContextCharacter = 11144 S.getSourceManager().getCharacterData(CC)[0]; 11145 if (FirstContextCharacter == '{') 11146 return false; 11147 } 11148 11149 return true; 11150 } 11151 11152 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11153 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11154 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11155 } 11156 11157 static void 11158 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC, 11159 bool *ICContext = nullptr) { 11160 if (E->isTypeDependent() || E->isValueDependent()) return; 11161 11162 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11163 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11164 if (Source == Target) return; 11165 if (Target->isDependentType()) return; 11166 11167 // If the conversion context location is invalid don't complain. We also 11168 // don't want to emit a warning if the issue occurs from the expansion of 11169 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11170 // delay this check as long as possible. Once we detect we are in that 11171 // scenario, we just return. 11172 if (CC.isInvalid()) 11173 return; 11174 11175 if (Source->isAtomicType()) 11176 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11177 11178 // Diagnose implicit casts to bool. 11179 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11180 if (isa<StringLiteral>(E)) 11181 // Warn on string literal to bool. Checks for string literals in logical 11182 // and expressions, for instance, assert(0 && "error here"), are 11183 // prevented by a check in AnalyzeImplicitConversions(). 11184 return DiagnoseImpCast(S, E, T, CC, 11185 diag::warn_impcast_string_literal_to_bool); 11186 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11187 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11188 // This covers the literal expressions that evaluate to Objective-C 11189 // objects. 11190 return DiagnoseImpCast(S, E, T, CC, 11191 diag::warn_impcast_objective_c_literal_to_bool); 11192 } 11193 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11194 // Warn on pointer to bool conversion that is always true. 11195 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11196 SourceRange(CC)); 11197 } 11198 } 11199 11200 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11201 // is a typedef for signed char (macOS), then that constant value has to be 1 11202 // or 0. 11203 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11204 Expr::EvalResult Result; 11205 if (E->EvaluateAsInt(Result, S.getASTContext(), 11206 Expr::SE_AllowSideEffects) && 11207 Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11208 auto Builder = S.Diag(CC, diag::warn_impcast_constant_int_to_objc_bool) 11209 << Result.Val.getInt().toString(10); 11210 Expr *Ignored = E->IgnoreImplicit(); 11211 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11212 isa<BinaryOperator>(Ignored) || 11213 isa<CXXOperatorCallExpr>(Ignored); 11214 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 11215 if (NeedsParens) 11216 Builder << FixItHint::CreateInsertion(E->getBeginLoc(), "(") 11217 << FixItHint::CreateInsertion(EndLoc, ")"); 11218 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11219 return; 11220 } 11221 } 11222 11223 // Check implicit casts from Objective-C collection literals to specialized 11224 // collection types, e.g., NSArray<NSString *> *. 11225 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11226 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11227 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11228 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11229 11230 // Strip vector types. 11231 if (isa<VectorType>(Source)) { 11232 if (!isa<VectorType>(Target)) { 11233 if (S.SourceMgr.isInSystemMacro(CC)) 11234 return; 11235 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11236 } 11237 11238 // If the vector cast is cast between two vectors of the same size, it is 11239 // a bitcast, not a conversion. 11240 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11241 return; 11242 11243 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11244 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11245 } 11246 if (auto VecTy = dyn_cast<VectorType>(Target)) 11247 Target = VecTy->getElementType().getTypePtr(); 11248 11249 // Strip complex types. 11250 if (isa<ComplexType>(Source)) { 11251 if (!isa<ComplexType>(Target)) { 11252 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11253 return; 11254 11255 return DiagnoseImpCast(S, E, T, CC, 11256 S.getLangOpts().CPlusPlus 11257 ? diag::err_impcast_complex_scalar 11258 : diag::warn_impcast_complex_scalar); 11259 } 11260 11261 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11262 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11263 } 11264 11265 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11266 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11267 11268 // If the source is floating point... 11269 if (SourceBT && SourceBT->isFloatingPoint()) { 11270 // ...and the target is floating point... 11271 if (TargetBT && TargetBT->isFloatingPoint()) { 11272 // ...then warn if we're dropping FP rank. 11273 11274 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11275 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11276 if (Order > 0) { 11277 // Don't warn about float constants that are precisely 11278 // representable in the target type. 11279 Expr::EvalResult result; 11280 if (E->EvaluateAsRValue(result, S.Context)) { 11281 // Value might be a float, a float vector, or a float complex. 11282 if (IsSameFloatAfterCast(result.Val, 11283 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11284 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11285 return; 11286 } 11287 11288 if (S.SourceMgr.isInSystemMacro(CC)) 11289 return; 11290 11291 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11292 } 11293 // ... or possibly if we're increasing rank, too 11294 else if (Order < 0) { 11295 if (S.SourceMgr.isInSystemMacro(CC)) 11296 return; 11297 11298 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11299 } 11300 return; 11301 } 11302 11303 // If the target is integral, always warn. 11304 if (TargetBT && TargetBT->isInteger()) { 11305 if (S.SourceMgr.isInSystemMacro(CC)) 11306 return; 11307 11308 DiagnoseFloatingImpCast(S, E, T, CC); 11309 } 11310 11311 // Detect the case where a call result is converted from floating-point to 11312 // to bool, and the final argument to the call is converted from bool, to 11313 // discover this typo: 11314 // 11315 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11316 // 11317 // FIXME: This is an incredibly special case; is there some more general 11318 // way to detect this class of misplaced-parentheses bug? 11319 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11320 // Check last argument of function call to see if it is an 11321 // implicit cast from a type matching the type the result 11322 // is being cast to. 11323 CallExpr *CEx = cast<CallExpr>(E); 11324 if (unsigned NumArgs = CEx->getNumArgs()) { 11325 Expr *LastA = CEx->getArg(NumArgs - 1); 11326 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11327 if (isa<ImplicitCastExpr>(LastA) && 11328 InnerE->getType()->isBooleanType()) { 11329 // Warn on this floating-point to bool conversion 11330 DiagnoseImpCast(S, E, T, CC, 11331 diag::warn_impcast_floating_point_to_bool); 11332 } 11333 } 11334 } 11335 return; 11336 } 11337 11338 // Valid casts involving fixed point types should be accounted for here. 11339 if (Source->isFixedPointType()) { 11340 if (Target->isUnsaturatedFixedPointType()) { 11341 Expr::EvalResult Result; 11342 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11343 S.isConstantEvaluated())) { 11344 APFixedPoint Value = Result.Val.getFixedPoint(); 11345 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11346 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11347 if (Value > MaxVal || Value < MinVal) { 11348 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11349 S.PDiag(diag::warn_impcast_fixed_point_range) 11350 << Value.toString() << T 11351 << E->getSourceRange() 11352 << clang::SourceRange(CC)); 11353 return; 11354 } 11355 } 11356 } else if (Target->isIntegerType()) { 11357 Expr::EvalResult Result; 11358 if (!S.isConstantEvaluated() && 11359 E->EvaluateAsFixedPoint(Result, S.Context, 11360 Expr::SE_AllowSideEffects)) { 11361 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11362 11363 bool Overflowed; 11364 llvm::APSInt IntResult = FXResult.convertToInt( 11365 S.Context.getIntWidth(T), 11366 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11367 11368 if (Overflowed) { 11369 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11370 S.PDiag(diag::warn_impcast_fixed_point_range) 11371 << FXResult.toString() << T 11372 << E->getSourceRange() 11373 << clang::SourceRange(CC)); 11374 return; 11375 } 11376 } 11377 } 11378 } else if (Target->isUnsaturatedFixedPointType()) { 11379 if (Source->isIntegerType()) { 11380 Expr::EvalResult Result; 11381 if (!S.isConstantEvaluated() && 11382 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11383 llvm::APSInt Value = Result.Val.getInt(); 11384 11385 bool Overflowed; 11386 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11387 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11388 11389 if (Overflowed) { 11390 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11391 S.PDiag(diag::warn_impcast_fixed_point_range) 11392 << Value.toString(/*radix=*/10) << T 11393 << E->getSourceRange() 11394 << clang::SourceRange(CC)); 11395 return; 11396 } 11397 } 11398 } 11399 } 11400 11401 DiagnoseNullConversion(S, E, T, CC); 11402 11403 S.DiscardMisalignedMemberAddress(Target, E); 11404 11405 if (!Source->isIntegerType() || !Target->isIntegerType()) 11406 return; 11407 11408 // TODO: remove this early return once the false positives for constant->bool 11409 // in templates, macros, etc, are reduced or removed. 11410 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11411 return; 11412 11413 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11414 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11415 11416 if (SourceRange.Width > TargetRange.Width) { 11417 // If the source is a constant, use a default-on diagnostic. 11418 // TODO: this should happen for bitfield stores, too. 11419 Expr::EvalResult Result; 11420 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11421 S.isConstantEvaluated())) { 11422 llvm::APSInt Value(32); 11423 Value = Result.Val.getInt(); 11424 11425 if (S.SourceMgr.isInSystemMacro(CC)) 11426 return; 11427 11428 std::string PrettySourceValue = Value.toString(10); 11429 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11430 11431 S.DiagRuntimeBehavior( 11432 E->getExprLoc(), E, 11433 S.PDiag(diag::warn_impcast_integer_precision_constant) 11434 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11435 << E->getSourceRange() << clang::SourceRange(CC)); 11436 return; 11437 } 11438 11439 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11440 if (S.SourceMgr.isInSystemMacro(CC)) 11441 return; 11442 11443 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11444 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11445 /* pruneControlFlow */ true); 11446 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11447 } 11448 11449 if (TargetRange.Width > SourceRange.Width) { 11450 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11451 if (UO->getOpcode() == UO_Minus) 11452 if (Source->isUnsignedIntegerType()) { 11453 if (Target->isUnsignedIntegerType()) 11454 return DiagnoseImpCast(S, E, T, CC, 11455 diag::warn_impcast_high_order_zero_bits); 11456 if (Target->isSignedIntegerType()) 11457 return DiagnoseImpCast(S, E, T, CC, 11458 diag::warn_impcast_nonnegative_result); 11459 } 11460 } 11461 11462 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11463 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11464 // Warn when doing a signed to signed conversion, warn if the positive 11465 // source value is exactly the width of the target type, which will 11466 // cause a negative value to be stored. 11467 11468 Expr::EvalResult Result; 11469 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11470 !S.SourceMgr.isInSystemMacro(CC)) { 11471 llvm::APSInt Value = Result.Val.getInt(); 11472 if (isSameWidthConstantConversion(S, E, T, CC)) { 11473 std::string PrettySourceValue = Value.toString(10); 11474 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11475 11476 S.DiagRuntimeBehavior( 11477 E->getExprLoc(), E, 11478 S.PDiag(diag::warn_impcast_integer_precision_constant) 11479 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11480 << E->getSourceRange() << clang::SourceRange(CC)); 11481 return; 11482 } 11483 } 11484 11485 // Fall through for non-constants to give a sign conversion warning. 11486 } 11487 11488 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11489 (!TargetRange.NonNegative && SourceRange.NonNegative && 11490 SourceRange.Width == TargetRange.Width)) { 11491 if (S.SourceMgr.isInSystemMacro(CC)) 11492 return; 11493 11494 unsigned DiagID = diag::warn_impcast_integer_sign; 11495 11496 // Traditionally, gcc has warned about this under -Wsign-compare. 11497 // We also want to warn about it in -Wconversion. 11498 // So if -Wconversion is off, use a completely identical diagnostic 11499 // in the sign-compare group. 11500 // The conditional-checking code will 11501 if (ICContext) { 11502 DiagID = diag::warn_impcast_integer_sign_conditional; 11503 *ICContext = true; 11504 } 11505 11506 return DiagnoseImpCast(S, E, T, CC, DiagID); 11507 } 11508 11509 // Diagnose conversions between different enumeration types. 11510 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11511 // type, to give us better diagnostics. 11512 QualType SourceType = E->getType(); 11513 if (!S.getLangOpts().CPlusPlus) { 11514 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11515 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11516 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11517 SourceType = S.Context.getTypeDeclType(Enum); 11518 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11519 } 11520 } 11521 11522 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11523 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11524 if (SourceEnum->getDecl()->hasNameForLinkage() && 11525 TargetEnum->getDecl()->hasNameForLinkage() && 11526 SourceEnum != TargetEnum) { 11527 if (S.SourceMgr.isInSystemMacro(CC)) 11528 return; 11529 11530 return DiagnoseImpCast(S, E, SourceType, T, CC, 11531 diag::warn_impcast_different_enum_types); 11532 } 11533 } 11534 11535 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11536 SourceLocation CC, QualType T); 11537 11538 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11539 SourceLocation CC, bool &ICContext) { 11540 E = E->IgnoreParenImpCasts(); 11541 11542 if (isa<ConditionalOperator>(E)) 11543 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11544 11545 AnalyzeImplicitConversions(S, E, CC); 11546 if (E->getType() != T) 11547 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11548 } 11549 11550 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11551 SourceLocation CC, QualType T) { 11552 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11553 11554 bool Suspicious = false; 11555 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11556 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11557 11558 // If -Wconversion would have warned about either of the candidates 11559 // for a signedness conversion to the context type... 11560 if (!Suspicious) return; 11561 11562 // ...but it's currently ignored... 11563 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11564 return; 11565 11566 // ...then check whether it would have warned about either of the 11567 // candidates for a signedness conversion to the condition type. 11568 if (E->getType() == T) return; 11569 11570 Suspicious = false; 11571 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11572 E->getType(), CC, &Suspicious); 11573 if (!Suspicious) 11574 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11575 E->getType(), CC, &Suspicious); 11576 } 11577 11578 /// Check conversion of given expression to boolean. 11579 /// Input argument E is a logical expression. 11580 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11581 if (S.getLangOpts().Bool) 11582 return; 11583 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11584 return; 11585 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11586 } 11587 11588 /// AnalyzeImplicitConversions - Find and report any interesting 11589 /// implicit conversions in the given expression. There are a couple 11590 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11591 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, 11592 SourceLocation CC) { 11593 QualType T = OrigE->getType(); 11594 Expr *E = OrigE->IgnoreParenImpCasts(); 11595 11596 if (E->isTypeDependent() || E->isValueDependent()) 11597 return; 11598 11599 // For conditional operators, we analyze the arguments as if they 11600 // were being fed directly into the output. 11601 if (isa<ConditionalOperator>(E)) { 11602 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11603 CheckConditionalOperator(S, CO, CC, T); 11604 return; 11605 } 11606 11607 // Check implicit argument conversions for function calls. 11608 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11609 CheckImplicitArgumentConversions(S, Call, CC); 11610 11611 // Go ahead and check any implicit conversions we might have skipped. 11612 // The non-canonical typecheck is just an optimization; 11613 // CheckImplicitConversion will filter out dead implicit conversions. 11614 if (E->getType() != T) 11615 CheckImplicitConversion(S, E, T, CC); 11616 11617 // Now continue drilling into this expression. 11618 11619 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11620 // The bound subexpressions in a PseudoObjectExpr are not reachable 11621 // as transitive children. 11622 // FIXME: Use a more uniform representation for this. 11623 for (auto *SE : POE->semantics()) 11624 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11625 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC); 11626 } 11627 11628 // Skip past explicit casts. 11629 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11630 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11631 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11632 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11633 return AnalyzeImplicitConversions(S, E, CC); 11634 } 11635 11636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11637 // Do a somewhat different check with comparison operators. 11638 if (BO->isComparisonOp()) 11639 return AnalyzeComparison(S, BO); 11640 11641 // And with simple assignments. 11642 if (BO->getOpcode() == BO_Assign) 11643 return AnalyzeAssignment(S, BO); 11644 // And with compound assignments. 11645 if (BO->isAssignmentOp()) 11646 return AnalyzeCompoundAssignment(S, BO); 11647 } 11648 11649 // These break the otherwise-useful invariant below. Fortunately, 11650 // we don't really need to recurse into them, because any internal 11651 // expressions should have been analyzed already when they were 11652 // built into statements. 11653 if (isa<StmtExpr>(E)) return; 11654 11655 // Don't descend into unevaluated contexts. 11656 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11657 11658 // Now just recurse over the expression's children. 11659 CC = E->getExprLoc(); 11660 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11661 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11662 for (Stmt *SubStmt : E->children()) { 11663 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11664 if (!ChildExpr) 11665 continue; 11666 11667 if (IsLogicalAndOperator && 11668 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11669 // Ignore checking string literals that are in logical and operators. 11670 // This is a common pattern for asserts. 11671 continue; 11672 AnalyzeImplicitConversions(S, ChildExpr, CC); 11673 } 11674 11675 if (BO && BO->isLogicalOp()) { 11676 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11677 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11678 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11679 11680 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11681 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11682 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11683 } 11684 11685 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11686 if (U->getOpcode() == UO_LNot) { 11687 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11688 } else if (U->getOpcode() != UO_AddrOf) { 11689 if (U->getSubExpr()->getType()->isAtomicType()) 11690 S.Diag(U->getSubExpr()->getBeginLoc(), 11691 diag::warn_atomic_implicit_seq_cst); 11692 } 11693 } 11694 } 11695 11696 /// Diagnose integer type and any valid implicit conversion to it. 11697 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11698 // Taking into account implicit conversions, 11699 // allow any integer. 11700 if (!E->getType()->isIntegerType()) { 11701 S.Diag(E->getBeginLoc(), 11702 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11703 return true; 11704 } 11705 // Potentially emit standard warnings for implicit conversions if enabled 11706 // using -Wconversion. 11707 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11708 return false; 11709 } 11710 11711 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11712 // Returns true when emitting a warning about taking the address of a reference. 11713 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11714 const PartialDiagnostic &PD) { 11715 E = E->IgnoreParenImpCasts(); 11716 11717 const FunctionDecl *FD = nullptr; 11718 11719 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11720 if (!DRE->getDecl()->getType()->isReferenceType()) 11721 return false; 11722 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11723 if (!M->getMemberDecl()->getType()->isReferenceType()) 11724 return false; 11725 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11726 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11727 return false; 11728 FD = Call->getDirectCallee(); 11729 } else { 11730 return false; 11731 } 11732 11733 SemaRef.Diag(E->getExprLoc(), PD); 11734 11735 // If possible, point to location of function. 11736 if (FD) { 11737 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11738 } 11739 11740 return true; 11741 } 11742 11743 // Returns true if the SourceLocation is expanded from any macro body. 11744 // Returns false if the SourceLocation is invalid, is from not in a macro 11745 // expansion, or is from expanded from a top-level macro argument. 11746 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11747 if (Loc.isInvalid()) 11748 return false; 11749 11750 while (Loc.isMacroID()) { 11751 if (SM.isMacroBodyExpansion(Loc)) 11752 return true; 11753 Loc = SM.getImmediateMacroCallerLoc(Loc); 11754 } 11755 11756 return false; 11757 } 11758 11759 /// Diagnose pointers that are always non-null. 11760 /// \param E the expression containing the pointer 11761 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11762 /// compared to a null pointer 11763 /// \param IsEqual True when the comparison is equal to a null pointer 11764 /// \param Range Extra SourceRange to highlight in the diagnostic 11765 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11766 Expr::NullPointerConstantKind NullKind, 11767 bool IsEqual, SourceRange Range) { 11768 if (!E) 11769 return; 11770 11771 // Don't warn inside macros. 11772 if (E->getExprLoc().isMacroID()) { 11773 const SourceManager &SM = getSourceManager(); 11774 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11775 IsInAnyMacroBody(SM, Range.getBegin())) 11776 return; 11777 } 11778 E = E->IgnoreImpCasts(); 11779 11780 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11781 11782 if (isa<CXXThisExpr>(E)) { 11783 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11784 : diag::warn_this_bool_conversion; 11785 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11786 return; 11787 } 11788 11789 bool IsAddressOf = false; 11790 11791 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11792 if (UO->getOpcode() != UO_AddrOf) 11793 return; 11794 IsAddressOf = true; 11795 E = UO->getSubExpr(); 11796 } 11797 11798 if (IsAddressOf) { 11799 unsigned DiagID = IsCompare 11800 ? diag::warn_address_of_reference_null_compare 11801 : diag::warn_address_of_reference_bool_conversion; 11802 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11803 << IsEqual; 11804 if (CheckForReference(*this, E, PD)) { 11805 return; 11806 } 11807 } 11808 11809 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11810 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11811 std::string Str; 11812 llvm::raw_string_ostream S(Str); 11813 E->printPretty(S, nullptr, getPrintingPolicy()); 11814 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11815 : diag::warn_cast_nonnull_to_bool; 11816 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11817 << E->getSourceRange() << Range << IsEqual; 11818 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11819 }; 11820 11821 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11822 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11823 if (auto *Callee = Call->getDirectCallee()) { 11824 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11825 ComplainAboutNonnullParamOrCall(A); 11826 return; 11827 } 11828 } 11829 } 11830 11831 // Expect to find a single Decl. Skip anything more complicated. 11832 ValueDecl *D = nullptr; 11833 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11834 D = R->getDecl(); 11835 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11836 D = M->getMemberDecl(); 11837 } 11838 11839 // Weak Decls can be null. 11840 if (!D || D->isWeak()) 11841 return; 11842 11843 // Check for parameter decl with nonnull attribute 11844 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11845 if (getCurFunction() && 11846 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11847 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11848 ComplainAboutNonnullParamOrCall(A); 11849 return; 11850 } 11851 11852 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11853 // Skip function template not specialized yet. 11854 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11855 return; 11856 auto ParamIter = llvm::find(FD->parameters(), PV); 11857 assert(ParamIter != FD->param_end()); 11858 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11859 11860 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11861 if (!NonNull->args_size()) { 11862 ComplainAboutNonnullParamOrCall(NonNull); 11863 return; 11864 } 11865 11866 for (const ParamIdx &ArgNo : NonNull->args()) { 11867 if (ArgNo.getASTIndex() == ParamNo) { 11868 ComplainAboutNonnullParamOrCall(NonNull); 11869 return; 11870 } 11871 } 11872 } 11873 } 11874 } 11875 } 11876 11877 QualType T = D->getType(); 11878 const bool IsArray = T->isArrayType(); 11879 const bool IsFunction = T->isFunctionType(); 11880 11881 // Address of function is used to silence the function warning. 11882 if (IsAddressOf && IsFunction) { 11883 return; 11884 } 11885 11886 // Found nothing. 11887 if (!IsAddressOf && !IsFunction && !IsArray) 11888 return; 11889 11890 // Pretty print the expression for the diagnostic. 11891 std::string Str; 11892 llvm::raw_string_ostream S(Str); 11893 E->printPretty(S, nullptr, getPrintingPolicy()); 11894 11895 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11896 : diag::warn_impcast_pointer_to_bool; 11897 enum { 11898 AddressOf, 11899 FunctionPointer, 11900 ArrayPointer 11901 } DiagType; 11902 if (IsAddressOf) 11903 DiagType = AddressOf; 11904 else if (IsFunction) 11905 DiagType = FunctionPointer; 11906 else if (IsArray) 11907 DiagType = ArrayPointer; 11908 else 11909 llvm_unreachable("Could not determine diagnostic."); 11910 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11911 << Range << IsEqual; 11912 11913 if (!IsFunction) 11914 return; 11915 11916 // Suggest '&' to silence the function warning. 11917 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11918 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11919 11920 // Check to see if '()' fixit should be emitted. 11921 QualType ReturnType; 11922 UnresolvedSet<4> NonTemplateOverloads; 11923 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11924 if (ReturnType.isNull()) 11925 return; 11926 11927 if (IsCompare) { 11928 // There are two cases here. If there is null constant, the only suggest 11929 // for a pointer return type. If the null is 0, then suggest if the return 11930 // type is a pointer or an integer type. 11931 if (!ReturnType->isPointerType()) { 11932 if (NullKind == Expr::NPCK_ZeroExpression || 11933 NullKind == Expr::NPCK_ZeroLiteral) { 11934 if (!ReturnType->isIntegerType()) 11935 return; 11936 } else { 11937 return; 11938 } 11939 } 11940 } else { // !IsCompare 11941 // For function to bool, only suggest if the function pointer has bool 11942 // return type. 11943 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11944 return; 11945 } 11946 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11947 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11948 } 11949 11950 /// Diagnoses "dangerous" implicit conversions within the given 11951 /// expression (which is a full expression). Implements -Wconversion 11952 /// and -Wsign-compare. 11953 /// 11954 /// \param CC the "context" location of the implicit conversion, i.e. 11955 /// the most location of the syntactic entity requiring the implicit 11956 /// conversion 11957 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11958 // Don't diagnose in unevaluated contexts. 11959 if (isUnevaluatedContext()) 11960 return; 11961 11962 // Don't diagnose for value- or type-dependent expressions. 11963 if (E->isTypeDependent() || E->isValueDependent()) 11964 return; 11965 11966 // Check for array bounds violations in cases where the check isn't triggered 11967 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11968 // ArraySubscriptExpr is on the RHS of a variable initialization. 11969 CheckArrayAccess(E); 11970 11971 // This is not the right CC for (e.g.) a variable initialization. 11972 AnalyzeImplicitConversions(*this, E, CC); 11973 } 11974 11975 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11976 /// Input argument E is a logical expression. 11977 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11978 ::CheckBoolLikeConversion(*this, E, CC); 11979 } 11980 11981 /// Diagnose when expression is an integer constant expression and its evaluation 11982 /// results in integer overflow 11983 void Sema::CheckForIntOverflow (Expr *E) { 11984 // Use a work list to deal with nested struct initializers. 11985 SmallVector<Expr *, 2> Exprs(1, E); 11986 11987 do { 11988 Expr *OriginalE = Exprs.pop_back_val(); 11989 Expr *E = OriginalE->IgnoreParenCasts(); 11990 11991 if (isa<BinaryOperator>(E)) { 11992 E->EvaluateForOverflow(Context); 11993 continue; 11994 } 11995 11996 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11997 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11998 else if (isa<ObjCBoxedExpr>(OriginalE)) 11999 E->EvaluateForOverflow(Context); 12000 else if (auto Call = dyn_cast<CallExpr>(E)) 12001 Exprs.append(Call->arg_begin(), Call->arg_end()); 12002 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12003 Exprs.append(Message->arg_begin(), Message->arg_end()); 12004 } while (!Exprs.empty()); 12005 } 12006 12007 namespace { 12008 12009 /// Visitor for expressions which looks for unsequenced operations on the 12010 /// same object. 12011 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> { 12012 using Base = EvaluatedExprVisitor<SequenceChecker>; 12013 12014 /// A tree of sequenced regions within an expression. Two regions are 12015 /// unsequenced if one is an ancestor or a descendent of the other. When we 12016 /// finish processing an expression with sequencing, such as a comma 12017 /// expression, we fold its tree nodes into its parent, since they are 12018 /// unsequenced with respect to nodes we will visit later. 12019 class SequenceTree { 12020 struct Value { 12021 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12022 unsigned Parent : 31; 12023 unsigned Merged : 1; 12024 }; 12025 SmallVector<Value, 8> Values; 12026 12027 public: 12028 /// A region within an expression which may be sequenced with respect 12029 /// to some other region. 12030 class Seq { 12031 friend class SequenceTree; 12032 12033 unsigned Index; 12034 12035 explicit Seq(unsigned N) : Index(N) {} 12036 12037 public: 12038 Seq() : Index(0) {} 12039 }; 12040 12041 SequenceTree() { Values.push_back(Value(0)); } 12042 Seq root() const { return Seq(0); } 12043 12044 /// Create a new sequence of operations, which is an unsequenced 12045 /// subset of \p Parent. This sequence of operations is sequenced with 12046 /// respect to other children of \p Parent. 12047 Seq allocate(Seq Parent) { 12048 Values.push_back(Value(Parent.Index)); 12049 return Seq(Values.size() - 1); 12050 } 12051 12052 /// Merge a sequence of operations into its parent. 12053 void merge(Seq S) { 12054 Values[S.Index].Merged = true; 12055 } 12056 12057 /// Determine whether two operations are unsequenced. This operation 12058 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12059 /// should have been merged into its parent as appropriate. 12060 bool isUnsequenced(Seq Cur, Seq Old) { 12061 unsigned C = representative(Cur.Index); 12062 unsigned Target = representative(Old.Index); 12063 while (C >= Target) { 12064 if (C == Target) 12065 return true; 12066 C = Values[C].Parent; 12067 } 12068 return false; 12069 } 12070 12071 private: 12072 /// Pick a representative for a sequence. 12073 unsigned representative(unsigned K) { 12074 if (Values[K].Merged) 12075 // Perform path compression as we go. 12076 return Values[K].Parent = representative(Values[K].Parent); 12077 return K; 12078 } 12079 }; 12080 12081 /// An object for which we can track unsequenced uses. 12082 using Object = NamedDecl *; 12083 12084 /// Different flavors of object usage which we track. We only track the 12085 /// least-sequenced usage of each kind. 12086 enum UsageKind { 12087 /// A read of an object. Multiple unsequenced reads are OK. 12088 UK_Use, 12089 12090 /// A modification of an object which is sequenced before the value 12091 /// computation of the expression, such as ++n in C++. 12092 UK_ModAsValue, 12093 12094 /// A modification of an object which is not sequenced before the value 12095 /// computation of the expression, such as n++. 12096 UK_ModAsSideEffect, 12097 12098 UK_Count = UK_ModAsSideEffect + 1 12099 }; 12100 12101 struct Usage { 12102 Expr *Use; 12103 SequenceTree::Seq Seq; 12104 12105 Usage() : Use(nullptr), Seq() {} 12106 }; 12107 12108 struct UsageInfo { 12109 Usage Uses[UK_Count]; 12110 12111 /// Have we issued a diagnostic for this variable already? 12112 bool Diagnosed; 12113 12114 UsageInfo() : Uses(), Diagnosed(false) {} 12115 }; 12116 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12117 12118 Sema &SemaRef; 12119 12120 /// Sequenced regions within the expression. 12121 SequenceTree Tree; 12122 12123 /// Declaration modifications and references which we have seen. 12124 UsageInfoMap UsageMap; 12125 12126 /// The region we are currently within. 12127 SequenceTree::Seq Region; 12128 12129 /// Filled in with declarations which were modified as a side-effect 12130 /// (that is, post-increment operations). 12131 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12132 12133 /// Expressions to check later. We defer checking these to reduce 12134 /// stack usage. 12135 SmallVectorImpl<Expr *> &WorkList; 12136 12137 /// RAII object wrapping the visitation of a sequenced subexpression of an 12138 /// expression. At the end of this process, the side-effects of the evaluation 12139 /// become sequenced with respect to the value computation of the result, so 12140 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12141 /// UK_ModAsValue. 12142 struct SequencedSubexpression { 12143 SequencedSubexpression(SequenceChecker &Self) 12144 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12145 Self.ModAsSideEffect = &ModAsSideEffect; 12146 } 12147 12148 ~SequencedSubexpression() { 12149 for (auto &M : llvm::reverse(ModAsSideEffect)) { 12150 UsageInfo &U = Self.UsageMap[M.first]; 12151 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect]; 12152 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue); 12153 SideEffectUsage = M.second; 12154 } 12155 Self.ModAsSideEffect = OldModAsSideEffect; 12156 } 12157 12158 SequenceChecker &Self; 12159 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12160 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12161 }; 12162 12163 /// RAII object wrapping the visitation of a subexpression which we might 12164 /// choose to evaluate as a constant. If any subexpression is evaluated and 12165 /// found to be non-constant, this allows us to suppress the evaluation of 12166 /// the outer expression. 12167 class EvaluationTracker { 12168 public: 12169 EvaluationTracker(SequenceChecker &Self) 12170 : Self(Self), Prev(Self.EvalTracker) { 12171 Self.EvalTracker = this; 12172 } 12173 12174 ~EvaluationTracker() { 12175 Self.EvalTracker = Prev; 12176 if (Prev) 12177 Prev->EvalOK &= EvalOK; 12178 } 12179 12180 bool evaluate(const Expr *E, bool &Result) { 12181 if (!EvalOK || E->isValueDependent()) 12182 return false; 12183 EvalOK = E->EvaluateAsBooleanCondition( 12184 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12185 return EvalOK; 12186 } 12187 12188 private: 12189 SequenceChecker &Self; 12190 EvaluationTracker *Prev; 12191 bool EvalOK = true; 12192 } *EvalTracker = nullptr; 12193 12194 /// Find the object which is produced by the specified expression, 12195 /// if any. 12196 Object getObject(Expr *E, bool Mod) const { 12197 E = E->IgnoreParenCasts(); 12198 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12199 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12200 return getObject(UO->getSubExpr(), Mod); 12201 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12202 if (BO->getOpcode() == BO_Comma) 12203 return getObject(BO->getRHS(), Mod); 12204 if (Mod && BO->isAssignmentOp()) 12205 return getObject(BO->getLHS(), Mod); 12206 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12207 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12208 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12209 return ME->getMemberDecl(); 12210 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12211 // FIXME: If this is a reference, map through to its value. 12212 return DRE->getDecl(); 12213 return nullptr; 12214 } 12215 12216 /// Note that an object was modified or used by an expression. 12217 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) { 12218 Usage &U = UI.Uses[UK]; 12219 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) { 12220 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12221 ModAsSideEffect->push_back(std::make_pair(O, U)); 12222 U.Use = Ref; 12223 U.Seq = Region; 12224 } 12225 } 12226 12227 /// Check whether a modification or use conflicts with a prior usage. 12228 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind, 12229 bool IsModMod) { 12230 if (UI.Diagnosed) 12231 return; 12232 12233 const Usage &U = UI.Uses[OtherKind]; 12234 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) 12235 return; 12236 12237 Expr *Mod = U.Use; 12238 Expr *ModOrUse = Ref; 12239 if (OtherKind == UK_Use) 12240 std::swap(Mod, ModOrUse); 12241 12242 SemaRef.DiagRuntimeBehavior( 12243 Mod->getExprLoc(), {Mod, ModOrUse}, 12244 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12245 : diag::warn_unsequenced_mod_use) 12246 << O << SourceRange(ModOrUse->getExprLoc())); 12247 UI.Diagnosed = true; 12248 } 12249 12250 void notePreUse(Object O, Expr *Use) { 12251 UsageInfo &U = UsageMap[O]; 12252 // Uses conflict with other modifications. 12253 checkUsage(O, U, Use, UK_ModAsValue, false); 12254 } 12255 12256 void notePostUse(Object O, Expr *Use) { 12257 UsageInfo &U = UsageMap[O]; 12258 checkUsage(O, U, Use, UK_ModAsSideEffect, false); 12259 addUsage(U, O, Use, UK_Use); 12260 } 12261 12262 void notePreMod(Object O, Expr *Mod) { 12263 UsageInfo &U = UsageMap[O]; 12264 // Modifications conflict with other modifications and with uses. 12265 checkUsage(O, U, Mod, UK_ModAsValue, true); 12266 checkUsage(O, U, Mod, UK_Use, false); 12267 } 12268 12269 void notePostMod(Object O, Expr *Use, UsageKind UK) { 12270 UsageInfo &U = UsageMap[O]; 12271 checkUsage(O, U, Use, UK_ModAsSideEffect, true); 12272 addUsage(U, O, Use, UK); 12273 } 12274 12275 public: 12276 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList) 12277 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12278 Visit(E); 12279 } 12280 12281 void VisitStmt(Stmt *S) { 12282 // Skip all statements which aren't expressions for now. 12283 } 12284 12285 void VisitExpr(Expr *E) { 12286 // By default, just recurse to evaluated subexpressions. 12287 Base::VisitStmt(E); 12288 } 12289 12290 void VisitCastExpr(CastExpr *E) { 12291 Object O = Object(); 12292 if (E->getCastKind() == CK_LValueToRValue) 12293 O = getObject(E->getSubExpr(), false); 12294 12295 if (O) 12296 notePreUse(O, E); 12297 VisitExpr(E); 12298 if (O) 12299 notePostUse(O, E); 12300 } 12301 12302 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) { 12303 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12304 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12305 SequenceTree::Seq OldRegion = Region; 12306 12307 { 12308 SequencedSubexpression SeqBefore(*this); 12309 Region = BeforeRegion; 12310 Visit(SequencedBefore); 12311 } 12312 12313 Region = AfterRegion; 12314 Visit(SequencedAfter); 12315 12316 Region = OldRegion; 12317 12318 Tree.merge(BeforeRegion); 12319 Tree.merge(AfterRegion); 12320 } 12321 12322 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) { 12323 // C++17 [expr.sub]p1: 12324 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12325 // expression E1 is sequenced before the expression E2. 12326 if (SemaRef.getLangOpts().CPlusPlus17) 12327 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12328 else 12329 Base::VisitStmt(ASE); 12330 } 12331 12332 void VisitBinComma(BinaryOperator *BO) { 12333 // C++11 [expr.comma]p1: 12334 // Every value computation and side effect associated with the left 12335 // expression is sequenced before every value computation and side 12336 // effect associated with the right expression. 12337 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12338 } 12339 12340 void VisitBinAssign(BinaryOperator *BO) { 12341 // The modification is sequenced after the value computation of the LHS 12342 // and RHS, so check it before inspecting the operands and update the 12343 // map afterwards. 12344 Object O = getObject(BO->getLHS(), true); 12345 if (!O) 12346 return VisitExpr(BO); 12347 12348 notePreMod(O, BO); 12349 12350 // C++11 [expr.ass]p7: 12351 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated 12352 // only once. 12353 // 12354 // Therefore, for a compound assignment operator, O is considered used 12355 // everywhere except within the evaluation of E1 itself. 12356 if (isa<CompoundAssignOperator>(BO)) 12357 notePreUse(O, BO); 12358 12359 Visit(BO->getLHS()); 12360 12361 if (isa<CompoundAssignOperator>(BO)) 12362 notePostUse(O, BO); 12363 12364 Visit(BO->getRHS()); 12365 12366 // C++11 [expr.ass]p1: 12367 // the assignment is sequenced [...] before the value computation of the 12368 // assignment expression. 12369 // C11 6.5.16/3 has no such rule. 12370 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12371 : UK_ModAsSideEffect); 12372 } 12373 12374 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) { 12375 VisitBinAssign(CAO); 12376 } 12377 12378 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12379 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12380 void VisitUnaryPreIncDec(UnaryOperator *UO) { 12381 Object O = getObject(UO->getSubExpr(), true); 12382 if (!O) 12383 return VisitExpr(UO); 12384 12385 notePreMod(O, UO); 12386 Visit(UO->getSubExpr()); 12387 // C++11 [expr.pre.incr]p1: 12388 // the expression ++x is equivalent to x+=1 12389 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12390 : UK_ModAsSideEffect); 12391 } 12392 12393 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12394 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12395 void VisitUnaryPostIncDec(UnaryOperator *UO) { 12396 Object O = getObject(UO->getSubExpr(), true); 12397 if (!O) 12398 return VisitExpr(UO); 12399 12400 notePreMod(O, UO); 12401 Visit(UO->getSubExpr()); 12402 notePostMod(O, UO, UK_ModAsSideEffect); 12403 } 12404 12405 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated. 12406 void VisitBinLOr(BinaryOperator *BO) { 12407 // The side-effects of the LHS of an '&&' are sequenced before the 12408 // value computation of the RHS, and hence before the value computation 12409 // of the '&&' itself, unless the LHS evaluates to zero. We treat them 12410 // as if they were unconditionally sequenced. 12411 EvaluationTracker Eval(*this); 12412 { 12413 SequencedSubexpression Sequenced(*this); 12414 Visit(BO->getLHS()); 12415 } 12416 12417 bool Result; 12418 if (Eval.evaluate(BO->getLHS(), Result)) { 12419 if (!Result) 12420 Visit(BO->getRHS()); 12421 } else { 12422 // Check for unsequenced operations in the RHS, treating it as an 12423 // entirely separate evaluation. 12424 // 12425 // FIXME: If there are operations in the RHS which are unsequenced 12426 // with respect to operations outside the RHS, and those operations 12427 // are unconditionally evaluated, diagnose them. 12428 WorkList.push_back(BO->getRHS()); 12429 } 12430 } 12431 void VisitBinLAnd(BinaryOperator *BO) { 12432 EvaluationTracker Eval(*this); 12433 { 12434 SequencedSubexpression Sequenced(*this); 12435 Visit(BO->getLHS()); 12436 } 12437 12438 bool Result; 12439 if (Eval.evaluate(BO->getLHS(), Result)) { 12440 if (Result) 12441 Visit(BO->getRHS()); 12442 } else { 12443 WorkList.push_back(BO->getRHS()); 12444 } 12445 } 12446 12447 // Only visit the condition, unless we can be sure which subexpression will 12448 // be chosen. 12449 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) { 12450 EvaluationTracker Eval(*this); 12451 { 12452 SequencedSubexpression Sequenced(*this); 12453 Visit(CO->getCond()); 12454 } 12455 12456 bool Result; 12457 if (Eval.evaluate(CO->getCond(), Result)) 12458 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr()); 12459 else { 12460 WorkList.push_back(CO->getTrueExpr()); 12461 WorkList.push_back(CO->getFalseExpr()); 12462 } 12463 } 12464 12465 void VisitCallExpr(CallExpr *CE) { 12466 // C++11 [intro.execution]p15: 12467 // When calling a function [...], every value computation and side effect 12468 // associated with any argument expression, or with the postfix expression 12469 // designating the called function, is sequenced before execution of every 12470 // expression or statement in the body of the function [and thus before 12471 // the value computation of its result]. 12472 SequencedSubexpression Sequenced(*this); 12473 Base::VisitCallExpr(CE); 12474 12475 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12476 } 12477 12478 void VisitCXXConstructExpr(CXXConstructExpr *CCE) { 12479 // This is a call, so all subexpressions are sequenced before the result. 12480 SequencedSubexpression Sequenced(*this); 12481 12482 if (!CCE->isListInitialization()) 12483 return VisitExpr(CCE); 12484 12485 // In C++11, list initializations are sequenced. 12486 SmallVector<SequenceTree::Seq, 32> Elts; 12487 SequenceTree::Seq Parent = Region; 12488 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(), 12489 E = CCE->arg_end(); 12490 I != E; ++I) { 12491 Region = Tree.allocate(Parent); 12492 Elts.push_back(Region); 12493 Visit(*I); 12494 } 12495 12496 // Forget that the initializers are sequenced. 12497 Region = Parent; 12498 for (unsigned I = 0; I < Elts.size(); ++I) 12499 Tree.merge(Elts[I]); 12500 } 12501 12502 void VisitInitListExpr(InitListExpr *ILE) { 12503 if (!SemaRef.getLangOpts().CPlusPlus11) 12504 return VisitExpr(ILE); 12505 12506 // In C++11, list initializations are sequenced. 12507 SmallVector<SequenceTree::Seq, 32> Elts; 12508 SequenceTree::Seq Parent = Region; 12509 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12510 Expr *E = ILE->getInit(I); 12511 if (!E) continue; 12512 Region = Tree.allocate(Parent); 12513 Elts.push_back(Region); 12514 Visit(E); 12515 } 12516 12517 // Forget that the initializers are sequenced. 12518 Region = Parent; 12519 for (unsigned I = 0; I < Elts.size(); ++I) 12520 Tree.merge(Elts[I]); 12521 } 12522 }; 12523 12524 } // namespace 12525 12526 void Sema::CheckUnsequencedOperations(Expr *E) { 12527 SmallVector<Expr *, 8> WorkList; 12528 WorkList.push_back(E); 12529 while (!WorkList.empty()) { 12530 Expr *Item = WorkList.pop_back_val(); 12531 SequenceChecker(*this, Item, WorkList); 12532 } 12533 } 12534 12535 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12536 bool IsConstexpr) { 12537 llvm::SaveAndRestore<bool> ConstantContext( 12538 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12539 CheckImplicitConversions(E, CheckLoc); 12540 if (!E->isInstantiationDependent()) 12541 CheckUnsequencedOperations(E); 12542 if (!IsConstexpr && !E->isValueDependent()) 12543 CheckForIntOverflow(E); 12544 DiagnoseMisalignedMembers(); 12545 } 12546 12547 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12548 FieldDecl *BitField, 12549 Expr *Init) { 12550 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12551 } 12552 12553 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12554 SourceLocation Loc) { 12555 if (!PType->isVariablyModifiedType()) 12556 return; 12557 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12558 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12559 return; 12560 } 12561 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12562 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12563 return; 12564 } 12565 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12566 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12567 return; 12568 } 12569 12570 const ArrayType *AT = S.Context.getAsArrayType(PType); 12571 if (!AT) 12572 return; 12573 12574 if (AT->getSizeModifier() != ArrayType::Star) { 12575 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12576 return; 12577 } 12578 12579 S.Diag(Loc, diag::err_array_star_in_function_definition); 12580 } 12581 12582 /// CheckParmsForFunctionDef - Check that the parameters of the given 12583 /// function are appropriate for the definition of a function. This 12584 /// takes care of any checks that cannot be performed on the 12585 /// declaration itself, e.g., that the types of each of the function 12586 /// parameters are complete. 12587 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12588 bool CheckParameterNames) { 12589 bool HasInvalidParm = false; 12590 for (ParmVarDecl *Param : Parameters) { 12591 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12592 // function declarator that is part of a function definition of 12593 // that function shall not have incomplete type. 12594 // 12595 // This is also C++ [dcl.fct]p6. 12596 if (!Param->isInvalidDecl() && 12597 RequireCompleteType(Param->getLocation(), Param->getType(), 12598 diag::err_typecheck_decl_incomplete_type)) { 12599 Param->setInvalidDecl(); 12600 HasInvalidParm = true; 12601 } 12602 12603 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12604 // declaration of each parameter shall include an identifier. 12605 if (CheckParameterNames && 12606 Param->getIdentifier() == nullptr && 12607 !Param->isImplicit() && 12608 !getLangOpts().CPlusPlus) 12609 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12610 12611 // C99 6.7.5.3p12: 12612 // If the function declarator is not part of a definition of that 12613 // function, parameters may have incomplete type and may use the [*] 12614 // notation in their sequences of declarator specifiers to specify 12615 // variable length array types. 12616 QualType PType = Param->getOriginalType(); 12617 // FIXME: This diagnostic should point the '[*]' if source-location 12618 // information is added for it. 12619 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12620 12621 // If the parameter is a c++ class type and it has to be destructed in the 12622 // callee function, declare the destructor so that it can be called by the 12623 // callee function. Do not perform any direct access check on the dtor here. 12624 if (!Param->isInvalidDecl()) { 12625 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12626 if (!ClassDecl->isInvalidDecl() && 12627 !ClassDecl->hasIrrelevantDestructor() && 12628 !ClassDecl->isDependentContext() && 12629 ClassDecl->isParamDestroyedInCallee()) { 12630 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12631 MarkFunctionReferenced(Param->getLocation(), Destructor); 12632 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12633 } 12634 } 12635 } 12636 12637 // Parameters with the pass_object_size attribute only need to be marked 12638 // constant at function definitions. Because we lack information about 12639 // whether we're on a declaration or definition when we're instantiating the 12640 // attribute, we need to check for constness here. 12641 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12642 if (!Param->getType().isConstQualified()) 12643 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12644 << Attr->getSpelling() << 1; 12645 12646 // Check for parameter names shadowing fields from the class. 12647 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12648 // The owning context for the parameter should be the function, but we 12649 // want to see if this function's declaration context is a record. 12650 DeclContext *DC = Param->getDeclContext(); 12651 if (DC && DC->isFunctionOrMethod()) { 12652 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12653 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12654 RD, /*DeclIsField*/ false); 12655 } 12656 } 12657 } 12658 12659 return HasInvalidParm; 12660 } 12661 12662 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12663 /// or MemberExpr. 12664 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12665 ASTContext &Context) { 12666 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12667 return Context.getDeclAlign(DRE->getDecl()); 12668 12669 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12670 return Context.getDeclAlign(ME->getMemberDecl()); 12671 12672 return TypeAlign; 12673 } 12674 12675 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12676 /// pointer cast increases the alignment requirements. 12677 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12678 // This is actually a lot of work to potentially be doing on every 12679 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12680 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12681 return; 12682 12683 // Ignore dependent types. 12684 if (T->isDependentType() || Op->getType()->isDependentType()) 12685 return; 12686 12687 // Require that the destination be a pointer type. 12688 const PointerType *DestPtr = T->getAs<PointerType>(); 12689 if (!DestPtr) return; 12690 12691 // If the destination has alignment 1, we're done. 12692 QualType DestPointee = DestPtr->getPointeeType(); 12693 if (DestPointee->isIncompleteType()) return; 12694 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12695 if (DestAlign.isOne()) return; 12696 12697 // Require that the source be a pointer type. 12698 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12699 if (!SrcPtr) return; 12700 QualType SrcPointee = SrcPtr->getPointeeType(); 12701 12702 // Whitelist casts from cv void*. We already implicitly 12703 // whitelisted casts to cv void*, since they have alignment 1. 12704 // Also whitelist casts involving incomplete types, which implicitly 12705 // includes 'void'. 12706 if (SrcPointee->isIncompleteType()) return; 12707 12708 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12709 12710 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12711 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12712 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12713 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12714 if (UO->getOpcode() == UO_AddrOf) 12715 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12716 } 12717 12718 if (SrcAlign >= DestAlign) return; 12719 12720 Diag(TRange.getBegin(), diag::warn_cast_align) 12721 << Op->getType() << T 12722 << static_cast<unsigned>(SrcAlign.getQuantity()) 12723 << static_cast<unsigned>(DestAlign.getQuantity()) 12724 << TRange << Op->getSourceRange(); 12725 } 12726 12727 /// Check whether this array fits the idiom of a size-one tail padded 12728 /// array member of a struct. 12729 /// 12730 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12731 /// commonly used to emulate flexible arrays in C89 code. 12732 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12733 const NamedDecl *ND) { 12734 if (Size != 1 || !ND) return false; 12735 12736 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12737 if (!FD) return false; 12738 12739 // Don't consider sizes resulting from macro expansions or template argument 12740 // substitution to form C89 tail-padded arrays. 12741 12742 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12743 while (TInfo) { 12744 TypeLoc TL = TInfo->getTypeLoc(); 12745 // Look through typedefs. 12746 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12747 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12748 TInfo = TDL->getTypeSourceInfo(); 12749 continue; 12750 } 12751 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12752 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12753 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12754 return false; 12755 } 12756 break; 12757 } 12758 12759 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12760 if (!RD) return false; 12761 if (RD->isUnion()) return false; 12762 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12763 if (!CRD->isStandardLayout()) return false; 12764 } 12765 12766 // See if this is the last field decl in the record. 12767 const Decl *D = FD; 12768 while ((D = D->getNextDeclInContext())) 12769 if (isa<FieldDecl>(D)) 12770 return false; 12771 return true; 12772 } 12773 12774 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12775 const ArraySubscriptExpr *ASE, 12776 bool AllowOnePastEnd, bool IndexNegated) { 12777 // Already diagnosed by the constant evaluator. 12778 if (isConstantEvaluated()) 12779 return; 12780 12781 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12782 if (IndexExpr->isValueDependent()) 12783 return; 12784 12785 const Type *EffectiveType = 12786 BaseExpr->getType()->getPointeeOrArrayElementType(); 12787 BaseExpr = BaseExpr->IgnoreParenCasts(); 12788 const ConstantArrayType *ArrayTy = 12789 Context.getAsConstantArrayType(BaseExpr->getType()); 12790 12791 if (!ArrayTy) 12792 return; 12793 12794 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 12795 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 12796 return; 12797 12798 Expr::EvalResult Result; 12799 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12800 return; 12801 12802 llvm::APSInt index = Result.Val.getInt(); 12803 if (IndexNegated) 12804 index = -index; 12805 12806 const NamedDecl *ND = nullptr; 12807 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12808 ND = DRE->getDecl(); 12809 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12810 ND = ME->getMemberDecl(); 12811 12812 if (index.isUnsigned() || !index.isNegative()) { 12813 // It is possible that the type of the base expression after 12814 // IgnoreParenCasts is incomplete, even though the type of the base 12815 // expression before IgnoreParenCasts is complete (see PR39746 for an 12816 // example). In this case we have no information about whether the array 12817 // access exceeds the array bounds. However we can still diagnose an array 12818 // access which precedes the array bounds. 12819 if (BaseType->isIncompleteType()) 12820 return; 12821 12822 llvm::APInt size = ArrayTy->getSize(); 12823 if (!size.isStrictlyPositive()) 12824 return; 12825 12826 if (BaseType != EffectiveType) { 12827 // Make sure we're comparing apples to apples when comparing index to size 12828 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12829 uint64_t array_typesize = Context.getTypeSize(BaseType); 12830 // Handle ptrarith_typesize being zero, such as when casting to void* 12831 if (!ptrarith_typesize) ptrarith_typesize = 1; 12832 if (ptrarith_typesize != array_typesize) { 12833 // There's a cast to a different size type involved 12834 uint64_t ratio = array_typesize / ptrarith_typesize; 12835 // TODO: Be smarter about handling cases where array_typesize is not a 12836 // multiple of ptrarith_typesize 12837 if (ptrarith_typesize * ratio == array_typesize) 12838 size *= llvm::APInt(size.getBitWidth(), ratio); 12839 } 12840 } 12841 12842 if (size.getBitWidth() > index.getBitWidth()) 12843 index = index.zext(size.getBitWidth()); 12844 else if (size.getBitWidth() < index.getBitWidth()) 12845 size = size.zext(index.getBitWidth()); 12846 12847 // For array subscripting the index must be less than size, but for pointer 12848 // arithmetic also allow the index (offset) to be equal to size since 12849 // computing the next address after the end of the array is legal and 12850 // commonly done e.g. in C++ iterators and range-based for loops. 12851 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 12852 return; 12853 12854 // Also don't warn for arrays of size 1 which are members of some 12855 // structure. These are often used to approximate flexible arrays in C89 12856 // code. 12857 if (IsTailPaddedMemberArray(*this, size, ND)) 12858 return; 12859 12860 // Suppress the warning if the subscript expression (as identified by the 12861 // ']' location) and the index expression are both from macro expansions 12862 // within a system header. 12863 if (ASE) { 12864 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 12865 ASE->getRBracketLoc()); 12866 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 12867 SourceLocation IndexLoc = 12868 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 12869 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 12870 return; 12871 } 12872 } 12873 12874 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 12875 if (ASE) 12876 DiagID = diag::warn_array_index_exceeds_bounds; 12877 12878 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12879 PDiag(DiagID) << index.toString(10, true) 12880 << size.toString(10, true) 12881 << (unsigned)size.getLimitedValue(~0U) 12882 << IndexExpr->getSourceRange()); 12883 } else { 12884 unsigned DiagID = diag::warn_array_index_precedes_bounds; 12885 if (!ASE) { 12886 DiagID = diag::warn_ptr_arith_precedes_bounds; 12887 if (index.isNegative()) index = -index; 12888 } 12889 12890 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 12891 PDiag(DiagID) << index.toString(10, true) 12892 << IndexExpr->getSourceRange()); 12893 } 12894 12895 if (!ND) { 12896 // Try harder to find a NamedDecl to point at in the note. 12897 while (const ArraySubscriptExpr *ASE = 12898 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 12899 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 12900 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12901 ND = DRE->getDecl(); 12902 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12903 ND = ME->getMemberDecl(); 12904 } 12905 12906 if (ND) 12907 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 12908 PDiag(diag::note_array_index_out_of_bounds) 12909 << ND->getDeclName()); 12910 } 12911 12912 void Sema::CheckArrayAccess(const Expr *expr) { 12913 int AllowOnePastEnd = 0; 12914 while (expr) { 12915 expr = expr->IgnoreParenImpCasts(); 12916 switch (expr->getStmtClass()) { 12917 case Stmt::ArraySubscriptExprClass: { 12918 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 12919 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 12920 AllowOnePastEnd > 0); 12921 expr = ASE->getBase(); 12922 break; 12923 } 12924 case Stmt::MemberExprClass: { 12925 expr = cast<MemberExpr>(expr)->getBase(); 12926 break; 12927 } 12928 case Stmt::OMPArraySectionExprClass: { 12929 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 12930 if (ASE->getLowerBound()) 12931 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 12932 /*ASE=*/nullptr, AllowOnePastEnd > 0); 12933 return; 12934 } 12935 case Stmt::UnaryOperatorClass: { 12936 // Only unwrap the * and & unary operators 12937 const UnaryOperator *UO = cast<UnaryOperator>(expr); 12938 expr = UO->getSubExpr(); 12939 switch (UO->getOpcode()) { 12940 case UO_AddrOf: 12941 AllowOnePastEnd++; 12942 break; 12943 case UO_Deref: 12944 AllowOnePastEnd--; 12945 break; 12946 default: 12947 return; 12948 } 12949 break; 12950 } 12951 case Stmt::ConditionalOperatorClass: { 12952 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 12953 if (const Expr *lhs = cond->getLHS()) 12954 CheckArrayAccess(lhs); 12955 if (const Expr *rhs = cond->getRHS()) 12956 CheckArrayAccess(rhs); 12957 return; 12958 } 12959 case Stmt::CXXOperatorCallExprClass: { 12960 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 12961 for (const auto *Arg : OCE->arguments()) 12962 CheckArrayAccess(Arg); 12963 return; 12964 } 12965 default: 12966 return; 12967 } 12968 } 12969 } 12970 12971 //===--- CHECK: Objective-C retain cycles ----------------------------------// 12972 12973 namespace { 12974 12975 struct RetainCycleOwner { 12976 VarDecl *Variable = nullptr; 12977 SourceRange Range; 12978 SourceLocation Loc; 12979 bool Indirect = false; 12980 12981 RetainCycleOwner() = default; 12982 12983 void setLocsFrom(Expr *e) { 12984 Loc = e->getExprLoc(); 12985 Range = e->getSourceRange(); 12986 } 12987 }; 12988 12989 } // namespace 12990 12991 /// Consider whether capturing the given variable can possibly lead to 12992 /// a retain cycle. 12993 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 12994 // In ARC, it's captured strongly iff the variable has __strong 12995 // lifetime. In MRR, it's captured strongly if the variable is 12996 // __block and has an appropriate type. 12997 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 12998 return false; 12999 13000 owner.Variable = var; 13001 if (ref) 13002 owner.setLocsFrom(ref); 13003 return true; 13004 } 13005 13006 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13007 while (true) { 13008 e = e->IgnoreParens(); 13009 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13010 switch (cast->getCastKind()) { 13011 case CK_BitCast: 13012 case CK_LValueBitCast: 13013 case CK_LValueToRValue: 13014 case CK_ARCReclaimReturnedObject: 13015 e = cast->getSubExpr(); 13016 continue; 13017 13018 default: 13019 return false; 13020 } 13021 } 13022 13023 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13024 ObjCIvarDecl *ivar = ref->getDecl(); 13025 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13026 return false; 13027 13028 // Try to find a retain cycle in the base. 13029 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13030 return false; 13031 13032 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13033 owner.Indirect = true; 13034 return true; 13035 } 13036 13037 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13038 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13039 if (!var) return false; 13040 return considerVariable(var, ref, owner); 13041 } 13042 13043 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13044 if (member->isArrow()) return false; 13045 13046 // Don't count this as an indirect ownership. 13047 e = member->getBase(); 13048 continue; 13049 } 13050 13051 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13052 // Only pay attention to pseudo-objects on property references. 13053 ObjCPropertyRefExpr *pre 13054 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13055 ->IgnoreParens()); 13056 if (!pre) return false; 13057 if (pre->isImplicitProperty()) return false; 13058 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13059 if (!property->isRetaining() && 13060 !(property->getPropertyIvarDecl() && 13061 property->getPropertyIvarDecl()->getType() 13062 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13063 return false; 13064 13065 owner.Indirect = true; 13066 if (pre->isSuperReceiver()) { 13067 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13068 if (!owner.Variable) 13069 return false; 13070 owner.Loc = pre->getLocation(); 13071 owner.Range = pre->getSourceRange(); 13072 return true; 13073 } 13074 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13075 ->getSourceExpr()); 13076 continue; 13077 } 13078 13079 // Array ivars? 13080 13081 return false; 13082 } 13083 } 13084 13085 namespace { 13086 13087 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13088 ASTContext &Context; 13089 VarDecl *Variable; 13090 Expr *Capturer = nullptr; 13091 bool VarWillBeReased = false; 13092 13093 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13094 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13095 Context(Context), Variable(variable) {} 13096 13097 void VisitDeclRefExpr(DeclRefExpr *ref) { 13098 if (ref->getDecl() == Variable && !Capturer) 13099 Capturer = ref; 13100 } 13101 13102 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13103 if (Capturer) return; 13104 Visit(ref->getBase()); 13105 if (Capturer && ref->isFreeIvar()) 13106 Capturer = ref; 13107 } 13108 13109 void VisitBlockExpr(BlockExpr *block) { 13110 // Look inside nested blocks 13111 if (block->getBlockDecl()->capturesVariable(Variable)) 13112 Visit(block->getBlockDecl()->getBody()); 13113 } 13114 13115 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13116 if (Capturer) return; 13117 if (OVE->getSourceExpr()) 13118 Visit(OVE->getSourceExpr()); 13119 } 13120 13121 void VisitBinaryOperator(BinaryOperator *BinOp) { 13122 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13123 return; 13124 Expr *LHS = BinOp->getLHS(); 13125 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13126 if (DRE->getDecl() != Variable) 13127 return; 13128 if (Expr *RHS = BinOp->getRHS()) { 13129 RHS = RHS->IgnoreParenCasts(); 13130 llvm::APSInt Value; 13131 VarWillBeReased = 13132 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13133 } 13134 } 13135 } 13136 }; 13137 13138 } // namespace 13139 13140 /// Check whether the given argument is a block which captures a 13141 /// variable. 13142 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13143 assert(owner.Variable && owner.Loc.isValid()); 13144 13145 e = e->IgnoreParenCasts(); 13146 13147 // Look through [^{...} copy] and Block_copy(^{...}). 13148 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13149 Selector Cmd = ME->getSelector(); 13150 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13151 e = ME->getInstanceReceiver(); 13152 if (!e) 13153 return nullptr; 13154 e = e->IgnoreParenCasts(); 13155 } 13156 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13157 if (CE->getNumArgs() == 1) { 13158 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13159 if (Fn) { 13160 const IdentifierInfo *FnI = Fn->getIdentifier(); 13161 if (FnI && FnI->isStr("_Block_copy")) { 13162 e = CE->getArg(0)->IgnoreParenCasts(); 13163 } 13164 } 13165 } 13166 } 13167 13168 BlockExpr *block = dyn_cast<BlockExpr>(e); 13169 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13170 return nullptr; 13171 13172 FindCaptureVisitor visitor(S.Context, owner.Variable); 13173 visitor.Visit(block->getBlockDecl()->getBody()); 13174 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13175 } 13176 13177 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13178 RetainCycleOwner &owner) { 13179 assert(capturer); 13180 assert(owner.Variable && owner.Loc.isValid()); 13181 13182 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13183 << owner.Variable << capturer->getSourceRange(); 13184 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13185 << owner.Indirect << owner.Range; 13186 } 13187 13188 /// Check for a keyword selector that starts with the word 'add' or 13189 /// 'set'. 13190 static bool isSetterLikeSelector(Selector sel) { 13191 if (sel.isUnarySelector()) return false; 13192 13193 StringRef str = sel.getNameForSlot(0); 13194 while (!str.empty() && str.front() == '_') str = str.substr(1); 13195 if (str.startswith("set")) 13196 str = str.substr(3); 13197 else if (str.startswith("add")) { 13198 // Specially whitelist 'addOperationWithBlock:'. 13199 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13200 return false; 13201 str = str.substr(3); 13202 } 13203 else 13204 return false; 13205 13206 if (str.empty()) return true; 13207 return !isLowercase(str.front()); 13208 } 13209 13210 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13211 ObjCMessageExpr *Message) { 13212 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13213 Message->getReceiverInterface(), 13214 NSAPI::ClassId_NSMutableArray); 13215 if (!IsMutableArray) { 13216 return None; 13217 } 13218 13219 Selector Sel = Message->getSelector(); 13220 13221 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13222 S.NSAPIObj->getNSArrayMethodKind(Sel); 13223 if (!MKOpt) { 13224 return None; 13225 } 13226 13227 NSAPI::NSArrayMethodKind MK = *MKOpt; 13228 13229 switch (MK) { 13230 case NSAPI::NSMutableArr_addObject: 13231 case NSAPI::NSMutableArr_insertObjectAtIndex: 13232 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13233 return 0; 13234 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13235 return 1; 13236 13237 default: 13238 return None; 13239 } 13240 13241 return None; 13242 } 13243 13244 static 13245 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13246 ObjCMessageExpr *Message) { 13247 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13248 Message->getReceiverInterface(), 13249 NSAPI::ClassId_NSMutableDictionary); 13250 if (!IsMutableDictionary) { 13251 return None; 13252 } 13253 13254 Selector Sel = Message->getSelector(); 13255 13256 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13257 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13258 if (!MKOpt) { 13259 return None; 13260 } 13261 13262 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13263 13264 switch (MK) { 13265 case NSAPI::NSMutableDict_setObjectForKey: 13266 case NSAPI::NSMutableDict_setValueForKey: 13267 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13268 return 0; 13269 13270 default: 13271 return None; 13272 } 13273 13274 return None; 13275 } 13276 13277 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13278 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13279 Message->getReceiverInterface(), 13280 NSAPI::ClassId_NSMutableSet); 13281 13282 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13283 Message->getReceiverInterface(), 13284 NSAPI::ClassId_NSMutableOrderedSet); 13285 if (!IsMutableSet && !IsMutableOrderedSet) { 13286 return None; 13287 } 13288 13289 Selector Sel = Message->getSelector(); 13290 13291 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13292 if (!MKOpt) { 13293 return None; 13294 } 13295 13296 NSAPI::NSSetMethodKind MK = *MKOpt; 13297 13298 switch (MK) { 13299 case NSAPI::NSMutableSet_addObject: 13300 case NSAPI::NSOrderedSet_setObjectAtIndex: 13301 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13302 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13303 return 0; 13304 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13305 return 1; 13306 } 13307 13308 return None; 13309 } 13310 13311 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13312 if (!Message->isInstanceMessage()) { 13313 return; 13314 } 13315 13316 Optional<int> ArgOpt; 13317 13318 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13319 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13320 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13321 return; 13322 } 13323 13324 int ArgIndex = *ArgOpt; 13325 13326 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13327 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13328 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13329 } 13330 13331 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13332 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13333 if (ArgRE->isObjCSelfExpr()) { 13334 Diag(Message->getSourceRange().getBegin(), 13335 diag::warn_objc_circular_container) 13336 << ArgRE->getDecl() << StringRef("'super'"); 13337 } 13338 } 13339 } else { 13340 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13341 13342 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13343 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13344 } 13345 13346 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13347 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13348 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13349 ValueDecl *Decl = ReceiverRE->getDecl(); 13350 Diag(Message->getSourceRange().getBegin(), 13351 diag::warn_objc_circular_container) 13352 << Decl << Decl; 13353 if (!ArgRE->isObjCSelfExpr()) { 13354 Diag(Decl->getLocation(), 13355 diag::note_objc_circular_container_declared_here) 13356 << Decl; 13357 } 13358 } 13359 } 13360 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13361 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13362 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13363 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13364 Diag(Message->getSourceRange().getBegin(), 13365 diag::warn_objc_circular_container) 13366 << Decl << Decl; 13367 Diag(Decl->getLocation(), 13368 diag::note_objc_circular_container_declared_here) 13369 << Decl; 13370 } 13371 } 13372 } 13373 } 13374 } 13375 13376 /// Check a message send to see if it's likely to cause a retain cycle. 13377 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13378 // Only check instance methods whose selector looks like a setter. 13379 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13380 return; 13381 13382 // Try to find a variable that the receiver is strongly owned by. 13383 RetainCycleOwner owner; 13384 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13385 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13386 return; 13387 } else { 13388 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13389 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13390 owner.Loc = msg->getSuperLoc(); 13391 owner.Range = msg->getSuperLoc(); 13392 } 13393 13394 // Check whether the receiver is captured by any of the arguments. 13395 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13396 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13397 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13398 // noescape blocks should not be retained by the method. 13399 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13400 continue; 13401 return diagnoseRetainCycle(*this, capturer, owner); 13402 } 13403 } 13404 } 13405 13406 /// Check a property assign to see if it's likely to cause a retain cycle. 13407 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13408 RetainCycleOwner owner; 13409 if (!findRetainCycleOwner(*this, receiver, owner)) 13410 return; 13411 13412 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13413 diagnoseRetainCycle(*this, capturer, owner); 13414 } 13415 13416 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13417 RetainCycleOwner Owner; 13418 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13419 return; 13420 13421 // Because we don't have an expression for the variable, we have to set the 13422 // location explicitly here. 13423 Owner.Loc = Var->getLocation(); 13424 Owner.Range = Var->getSourceRange(); 13425 13426 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13427 diagnoseRetainCycle(*this, Capturer, Owner); 13428 } 13429 13430 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13431 Expr *RHS, bool isProperty) { 13432 // Check if RHS is an Objective-C object literal, which also can get 13433 // immediately zapped in a weak reference. Note that we explicitly 13434 // allow ObjCStringLiterals, since those are designed to never really die. 13435 RHS = RHS->IgnoreParenImpCasts(); 13436 13437 // This enum needs to match with the 'select' in 13438 // warn_objc_arc_literal_assign (off-by-1). 13439 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13440 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13441 return false; 13442 13443 S.Diag(Loc, diag::warn_arc_literal_assign) 13444 << (unsigned) Kind 13445 << (isProperty ? 0 : 1) 13446 << RHS->getSourceRange(); 13447 13448 return true; 13449 } 13450 13451 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13452 Qualifiers::ObjCLifetime LT, 13453 Expr *RHS, bool isProperty) { 13454 // Strip off any implicit cast added to get to the one ARC-specific. 13455 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13456 if (cast->getCastKind() == CK_ARCConsumeObject) { 13457 S.Diag(Loc, diag::warn_arc_retained_assign) 13458 << (LT == Qualifiers::OCL_ExplicitNone) 13459 << (isProperty ? 0 : 1) 13460 << RHS->getSourceRange(); 13461 return true; 13462 } 13463 RHS = cast->getSubExpr(); 13464 } 13465 13466 if (LT == Qualifiers::OCL_Weak && 13467 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13468 return true; 13469 13470 return false; 13471 } 13472 13473 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13474 QualType LHS, Expr *RHS) { 13475 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13476 13477 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13478 return false; 13479 13480 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13481 return true; 13482 13483 return false; 13484 } 13485 13486 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13487 Expr *LHS, Expr *RHS) { 13488 QualType LHSType; 13489 // PropertyRef on LHS type need be directly obtained from 13490 // its declaration as it has a PseudoType. 13491 ObjCPropertyRefExpr *PRE 13492 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13493 if (PRE && !PRE->isImplicitProperty()) { 13494 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13495 if (PD) 13496 LHSType = PD->getType(); 13497 } 13498 13499 if (LHSType.isNull()) 13500 LHSType = LHS->getType(); 13501 13502 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13503 13504 if (LT == Qualifiers::OCL_Weak) { 13505 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13506 getCurFunction()->markSafeWeakUse(LHS); 13507 } 13508 13509 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13510 return; 13511 13512 // FIXME. Check for other life times. 13513 if (LT != Qualifiers::OCL_None) 13514 return; 13515 13516 if (PRE) { 13517 if (PRE->isImplicitProperty()) 13518 return; 13519 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13520 if (!PD) 13521 return; 13522 13523 unsigned Attributes = PD->getPropertyAttributes(); 13524 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13525 // when 'assign' attribute was not explicitly specified 13526 // by user, ignore it and rely on property type itself 13527 // for lifetime info. 13528 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13529 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13530 LHSType->isObjCRetainableType()) 13531 return; 13532 13533 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13534 if (cast->getCastKind() == CK_ARCConsumeObject) { 13535 Diag(Loc, diag::warn_arc_retained_property_assign) 13536 << RHS->getSourceRange(); 13537 return; 13538 } 13539 RHS = cast->getSubExpr(); 13540 } 13541 } 13542 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13543 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13544 return; 13545 } 13546 } 13547 } 13548 13549 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13550 13551 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13552 SourceLocation StmtLoc, 13553 const NullStmt *Body) { 13554 // Do not warn if the body is a macro that expands to nothing, e.g: 13555 // 13556 // #define CALL(x) 13557 // if (condition) 13558 // CALL(0); 13559 if (Body->hasLeadingEmptyMacro()) 13560 return false; 13561 13562 // Get line numbers of statement and body. 13563 bool StmtLineInvalid; 13564 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13565 &StmtLineInvalid); 13566 if (StmtLineInvalid) 13567 return false; 13568 13569 bool BodyLineInvalid; 13570 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13571 &BodyLineInvalid); 13572 if (BodyLineInvalid) 13573 return false; 13574 13575 // Warn if null statement and body are on the same line. 13576 if (StmtLine != BodyLine) 13577 return false; 13578 13579 return true; 13580 } 13581 13582 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13583 const Stmt *Body, 13584 unsigned DiagID) { 13585 // Since this is a syntactic check, don't emit diagnostic for template 13586 // instantiations, this just adds noise. 13587 if (CurrentInstantiationScope) 13588 return; 13589 13590 // The body should be a null statement. 13591 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13592 if (!NBody) 13593 return; 13594 13595 // Do the usual checks. 13596 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13597 return; 13598 13599 Diag(NBody->getSemiLoc(), DiagID); 13600 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13601 } 13602 13603 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13604 const Stmt *PossibleBody) { 13605 assert(!CurrentInstantiationScope); // Ensured by caller 13606 13607 SourceLocation StmtLoc; 13608 const Stmt *Body; 13609 unsigned DiagID; 13610 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13611 StmtLoc = FS->getRParenLoc(); 13612 Body = FS->getBody(); 13613 DiagID = diag::warn_empty_for_body; 13614 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13615 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13616 Body = WS->getBody(); 13617 DiagID = diag::warn_empty_while_body; 13618 } else 13619 return; // Neither `for' nor `while'. 13620 13621 // The body should be a null statement. 13622 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13623 if (!NBody) 13624 return; 13625 13626 // Skip expensive checks if diagnostic is disabled. 13627 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13628 return; 13629 13630 // Do the usual checks. 13631 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13632 return; 13633 13634 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13635 // noise level low, emit diagnostics only if for/while is followed by a 13636 // CompoundStmt, e.g.: 13637 // for (int i = 0; i < n; i++); 13638 // { 13639 // a(i); 13640 // } 13641 // or if for/while is followed by a statement with more indentation 13642 // than for/while itself: 13643 // for (int i = 0; i < n; i++); 13644 // a(i); 13645 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13646 if (!ProbableTypo) { 13647 bool BodyColInvalid; 13648 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13649 PossibleBody->getBeginLoc(), &BodyColInvalid); 13650 if (BodyColInvalid) 13651 return; 13652 13653 bool StmtColInvalid; 13654 unsigned StmtCol = 13655 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13656 if (StmtColInvalid) 13657 return; 13658 13659 if (BodyCol > StmtCol) 13660 ProbableTypo = true; 13661 } 13662 13663 if (ProbableTypo) { 13664 Diag(NBody->getSemiLoc(), DiagID); 13665 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13666 } 13667 } 13668 13669 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13670 13671 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13672 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13673 SourceLocation OpLoc) { 13674 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13675 return; 13676 13677 if (inTemplateInstantiation()) 13678 return; 13679 13680 // Strip parens and casts away. 13681 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13682 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13683 13684 // Check for a call expression 13685 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13686 if (!CE || CE->getNumArgs() != 1) 13687 return; 13688 13689 // Check for a call to std::move 13690 if (!CE->isCallToStdMove()) 13691 return; 13692 13693 // Get argument from std::move 13694 RHSExpr = CE->getArg(0); 13695 13696 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13697 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13698 13699 // Two DeclRefExpr's, check that the decls are the same. 13700 if (LHSDeclRef && RHSDeclRef) { 13701 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13702 return; 13703 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13704 RHSDeclRef->getDecl()->getCanonicalDecl()) 13705 return; 13706 13707 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13708 << LHSExpr->getSourceRange() 13709 << RHSExpr->getSourceRange(); 13710 return; 13711 } 13712 13713 // Member variables require a different approach to check for self moves. 13714 // MemberExpr's are the same if every nested MemberExpr refers to the same 13715 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13716 // the base Expr's are CXXThisExpr's. 13717 const Expr *LHSBase = LHSExpr; 13718 const Expr *RHSBase = RHSExpr; 13719 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13720 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13721 if (!LHSME || !RHSME) 13722 return; 13723 13724 while (LHSME && RHSME) { 13725 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13726 RHSME->getMemberDecl()->getCanonicalDecl()) 13727 return; 13728 13729 LHSBase = LHSME->getBase(); 13730 RHSBase = RHSME->getBase(); 13731 LHSME = dyn_cast<MemberExpr>(LHSBase); 13732 RHSME = dyn_cast<MemberExpr>(RHSBase); 13733 } 13734 13735 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13736 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13737 if (LHSDeclRef && RHSDeclRef) { 13738 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13739 return; 13740 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13741 RHSDeclRef->getDecl()->getCanonicalDecl()) 13742 return; 13743 13744 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13745 << LHSExpr->getSourceRange() 13746 << RHSExpr->getSourceRange(); 13747 return; 13748 } 13749 13750 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13751 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13752 << LHSExpr->getSourceRange() 13753 << RHSExpr->getSourceRange(); 13754 } 13755 13756 //===--- Layout compatibility ----------------------------------------------// 13757 13758 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13759 13760 /// Check if two enumeration types are layout-compatible. 13761 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13762 // C++11 [dcl.enum] p8: 13763 // Two enumeration types are layout-compatible if they have the same 13764 // underlying type. 13765 return ED1->isComplete() && ED2->isComplete() && 13766 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13767 } 13768 13769 /// Check if two fields are layout-compatible. 13770 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13771 FieldDecl *Field2) { 13772 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13773 return false; 13774 13775 if (Field1->isBitField() != Field2->isBitField()) 13776 return false; 13777 13778 if (Field1->isBitField()) { 13779 // Make sure that the bit-fields are the same length. 13780 unsigned Bits1 = Field1->getBitWidthValue(C); 13781 unsigned Bits2 = Field2->getBitWidthValue(C); 13782 13783 if (Bits1 != Bits2) 13784 return false; 13785 } 13786 13787 return true; 13788 } 13789 13790 /// Check if two standard-layout structs are layout-compatible. 13791 /// (C++11 [class.mem] p17) 13792 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13793 RecordDecl *RD2) { 13794 // If both records are C++ classes, check that base classes match. 13795 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13796 // If one of records is a CXXRecordDecl we are in C++ mode, 13797 // thus the other one is a CXXRecordDecl, too. 13798 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13799 // Check number of base classes. 13800 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13801 return false; 13802 13803 // Check the base classes. 13804 for (CXXRecordDecl::base_class_const_iterator 13805 Base1 = D1CXX->bases_begin(), 13806 BaseEnd1 = D1CXX->bases_end(), 13807 Base2 = D2CXX->bases_begin(); 13808 Base1 != BaseEnd1; 13809 ++Base1, ++Base2) { 13810 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13811 return false; 13812 } 13813 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13814 // If only RD2 is a C++ class, it should have zero base classes. 13815 if (D2CXX->getNumBases() > 0) 13816 return false; 13817 } 13818 13819 // Check the fields. 13820 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13821 Field2End = RD2->field_end(), 13822 Field1 = RD1->field_begin(), 13823 Field1End = RD1->field_end(); 13824 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13825 if (!isLayoutCompatible(C, *Field1, *Field2)) 13826 return false; 13827 } 13828 if (Field1 != Field1End || Field2 != Field2End) 13829 return false; 13830 13831 return true; 13832 } 13833 13834 /// Check if two standard-layout unions are layout-compatible. 13835 /// (C++11 [class.mem] p18) 13836 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 13837 RecordDecl *RD2) { 13838 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 13839 for (auto *Field2 : RD2->fields()) 13840 UnmatchedFields.insert(Field2); 13841 13842 for (auto *Field1 : RD1->fields()) { 13843 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 13844 I = UnmatchedFields.begin(), 13845 E = UnmatchedFields.end(); 13846 13847 for ( ; I != E; ++I) { 13848 if (isLayoutCompatible(C, Field1, *I)) { 13849 bool Result = UnmatchedFields.erase(*I); 13850 (void) Result; 13851 assert(Result); 13852 break; 13853 } 13854 } 13855 if (I == E) 13856 return false; 13857 } 13858 13859 return UnmatchedFields.empty(); 13860 } 13861 13862 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 13863 RecordDecl *RD2) { 13864 if (RD1->isUnion() != RD2->isUnion()) 13865 return false; 13866 13867 if (RD1->isUnion()) 13868 return isLayoutCompatibleUnion(C, RD1, RD2); 13869 else 13870 return isLayoutCompatibleStruct(C, RD1, RD2); 13871 } 13872 13873 /// Check if two types are layout-compatible in C++11 sense. 13874 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 13875 if (T1.isNull() || T2.isNull()) 13876 return false; 13877 13878 // C++11 [basic.types] p11: 13879 // If two types T1 and T2 are the same type, then T1 and T2 are 13880 // layout-compatible types. 13881 if (C.hasSameType(T1, T2)) 13882 return true; 13883 13884 T1 = T1.getCanonicalType().getUnqualifiedType(); 13885 T2 = T2.getCanonicalType().getUnqualifiedType(); 13886 13887 const Type::TypeClass TC1 = T1->getTypeClass(); 13888 const Type::TypeClass TC2 = T2->getTypeClass(); 13889 13890 if (TC1 != TC2) 13891 return false; 13892 13893 if (TC1 == Type::Enum) { 13894 return isLayoutCompatible(C, 13895 cast<EnumType>(T1)->getDecl(), 13896 cast<EnumType>(T2)->getDecl()); 13897 } else if (TC1 == Type::Record) { 13898 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 13899 return false; 13900 13901 return isLayoutCompatible(C, 13902 cast<RecordType>(T1)->getDecl(), 13903 cast<RecordType>(T2)->getDecl()); 13904 } 13905 13906 return false; 13907 } 13908 13909 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 13910 13911 /// Given a type tag expression find the type tag itself. 13912 /// 13913 /// \param TypeExpr Type tag expression, as it appears in user's code. 13914 /// 13915 /// \param VD Declaration of an identifier that appears in a type tag. 13916 /// 13917 /// \param MagicValue Type tag magic value. 13918 /// 13919 /// \param isConstantEvaluated wether the evalaution should be performed in 13920 13921 /// constant context. 13922 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 13923 const ValueDecl **VD, uint64_t *MagicValue, 13924 bool isConstantEvaluated) { 13925 while(true) { 13926 if (!TypeExpr) 13927 return false; 13928 13929 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 13930 13931 switch (TypeExpr->getStmtClass()) { 13932 case Stmt::UnaryOperatorClass: { 13933 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 13934 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 13935 TypeExpr = UO->getSubExpr(); 13936 continue; 13937 } 13938 return false; 13939 } 13940 13941 case Stmt::DeclRefExprClass: { 13942 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 13943 *VD = DRE->getDecl(); 13944 return true; 13945 } 13946 13947 case Stmt::IntegerLiteralClass: { 13948 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 13949 llvm::APInt MagicValueAPInt = IL->getValue(); 13950 if (MagicValueAPInt.getActiveBits() <= 64) { 13951 *MagicValue = MagicValueAPInt.getZExtValue(); 13952 return true; 13953 } else 13954 return false; 13955 } 13956 13957 case Stmt::BinaryConditionalOperatorClass: 13958 case Stmt::ConditionalOperatorClass: { 13959 const AbstractConditionalOperator *ACO = 13960 cast<AbstractConditionalOperator>(TypeExpr); 13961 bool Result; 13962 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 13963 isConstantEvaluated)) { 13964 if (Result) 13965 TypeExpr = ACO->getTrueExpr(); 13966 else 13967 TypeExpr = ACO->getFalseExpr(); 13968 continue; 13969 } 13970 return false; 13971 } 13972 13973 case Stmt::BinaryOperatorClass: { 13974 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 13975 if (BO->getOpcode() == BO_Comma) { 13976 TypeExpr = BO->getRHS(); 13977 continue; 13978 } 13979 return false; 13980 } 13981 13982 default: 13983 return false; 13984 } 13985 } 13986 } 13987 13988 /// Retrieve the C type corresponding to type tag TypeExpr. 13989 /// 13990 /// \param TypeExpr Expression that specifies a type tag. 13991 /// 13992 /// \param MagicValues Registered magic values. 13993 /// 13994 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 13995 /// kind. 13996 /// 13997 /// \param TypeInfo Information about the corresponding C type. 13998 /// 13999 /// \param isConstantEvaluated wether the evalaution should be performed in 14000 /// constant context. 14001 /// 14002 /// \returns true if the corresponding C type was found. 14003 static bool GetMatchingCType( 14004 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14005 const ASTContext &Ctx, 14006 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14007 *MagicValues, 14008 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14009 bool isConstantEvaluated) { 14010 FoundWrongKind = false; 14011 14012 // Variable declaration that has type_tag_for_datatype attribute. 14013 const ValueDecl *VD = nullptr; 14014 14015 uint64_t MagicValue; 14016 14017 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14018 return false; 14019 14020 if (VD) { 14021 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14022 if (I->getArgumentKind() != ArgumentKind) { 14023 FoundWrongKind = true; 14024 return false; 14025 } 14026 TypeInfo.Type = I->getMatchingCType(); 14027 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14028 TypeInfo.MustBeNull = I->getMustBeNull(); 14029 return true; 14030 } 14031 return false; 14032 } 14033 14034 if (!MagicValues) 14035 return false; 14036 14037 llvm::DenseMap<Sema::TypeTagMagicValue, 14038 Sema::TypeTagData>::const_iterator I = 14039 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14040 if (I == MagicValues->end()) 14041 return false; 14042 14043 TypeInfo = I->second; 14044 return true; 14045 } 14046 14047 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14048 uint64_t MagicValue, QualType Type, 14049 bool LayoutCompatible, 14050 bool MustBeNull) { 14051 if (!TypeTagForDatatypeMagicValues) 14052 TypeTagForDatatypeMagicValues.reset( 14053 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14054 14055 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14056 (*TypeTagForDatatypeMagicValues)[Magic] = 14057 TypeTagData(Type, LayoutCompatible, MustBeNull); 14058 } 14059 14060 static bool IsSameCharType(QualType T1, QualType T2) { 14061 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14062 if (!BT1) 14063 return false; 14064 14065 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14066 if (!BT2) 14067 return false; 14068 14069 BuiltinType::Kind T1Kind = BT1->getKind(); 14070 BuiltinType::Kind T2Kind = BT2->getKind(); 14071 14072 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14073 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14074 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14075 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14076 } 14077 14078 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14079 const ArrayRef<const Expr *> ExprArgs, 14080 SourceLocation CallSiteLoc) { 14081 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14082 bool IsPointerAttr = Attr->getIsPointer(); 14083 14084 // Retrieve the argument representing the 'type_tag'. 14085 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14086 if (TypeTagIdxAST >= ExprArgs.size()) { 14087 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14088 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14089 return; 14090 } 14091 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14092 bool FoundWrongKind; 14093 TypeTagData TypeInfo; 14094 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14095 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14096 TypeInfo, isConstantEvaluated())) { 14097 if (FoundWrongKind) 14098 Diag(TypeTagExpr->getExprLoc(), 14099 diag::warn_type_tag_for_datatype_wrong_kind) 14100 << TypeTagExpr->getSourceRange(); 14101 return; 14102 } 14103 14104 // Retrieve the argument representing the 'arg_idx'. 14105 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14106 if (ArgumentIdxAST >= ExprArgs.size()) { 14107 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14108 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14109 return; 14110 } 14111 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14112 if (IsPointerAttr) { 14113 // Skip implicit cast of pointer to `void *' (as a function argument). 14114 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14115 if (ICE->getType()->isVoidPointerType() && 14116 ICE->getCastKind() == CK_BitCast) 14117 ArgumentExpr = ICE->getSubExpr(); 14118 } 14119 QualType ArgumentType = ArgumentExpr->getType(); 14120 14121 // Passing a `void*' pointer shouldn't trigger a warning. 14122 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14123 return; 14124 14125 if (TypeInfo.MustBeNull) { 14126 // Type tag with matching void type requires a null pointer. 14127 if (!ArgumentExpr->isNullPointerConstant(Context, 14128 Expr::NPC_ValueDependentIsNotNull)) { 14129 Diag(ArgumentExpr->getExprLoc(), 14130 diag::warn_type_safety_null_pointer_required) 14131 << ArgumentKind->getName() 14132 << ArgumentExpr->getSourceRange() 14133 << TypeTagExpr->getSourceRange(); 14134 } 14135 return; 14136 } 14137 14138 QualType RequiredType = TypeInfo.Type; 14139 if (IsPointerAttr) 14140 RequiredType = Context.getPointerType(RequiredType); 14141 14142 bool mismatch = false; 14143 if (!TypeInfo.LayoutCompatible) { 14144 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14145 14146 // C++11 [basic.fundamental] p1: 14147 // Plain char, signed char, and unsigned char are three distinct types. 14148 // 14149 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14150 // char' depending on the current char signedness mode. 14151 if (mismatch) 14152 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14153 RequiredType->getPointeeType())) || 14154 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14155 mismatch = false; 14156 } else 14157 if (IsPointerAttr) 14158 mismatch = !isLayoutCompatible(Context, 14159 ArgumentType->getPointeeType(), 14160 RequiredType->getPointeeType()); 14161 else 14162 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14163 14164 if (mismatch) 14165 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14166 << ArgumentType << ArgumentKind 14167 << TypeInfo.LayoutCompatible << RequiredType 14168 << ArgumentExpr->getSourceRange() 14169 << TypeTagExpr->getSourceRange(); 14170 } 14171 14172 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14173 CharUnits Alignment) { 14174 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14175 } 14176 14177 void Sema::DiagnoseMisalignedMembers() { 14178 for (MisalignedMember &m : MisalignedMembers) { 14179 const NamedDecl *ND = m.RD; 14180 if (ND->getName().empty()) { 14181 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14182 ND = TD; 14183 } 14184 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14185 << m.MD << ND << m.E->getSourceRange(); 14186 } 14187 MisalignedMembers.clear(); 14188 } 14189 14190 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14191 E = E->IgnoreParens(); 14192 if (!T->isPointerType() && !T->isIntegerType()) 14193 return; 14194 if (isa<UnaryOperator>(E) && 14195 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14196 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14197 if (isa<MemberExpr>(Op)) { 14198 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14199 if (MA != MisalignedMembers.end() && 14200 (T->isIntegerType() || 14201 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14202 Context.getTypeAlignInChars( 14203 T->getPointeeType()) <= MA->Alignment)))) 14204 MisalignedMembers.erase(MA); 14205 } 14206 } 14207 } 14208 14209 void Sema::RefersToMemberWithReducedAlignment( 14210 Expr *E, 14211 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14212 Action) { 14213 const auto *ME = dyn_cast<MemberExpr>(E); 14214 if (!ME) 14215 return; 14216 14217 // No need to check expressions with an __unaligned-qualified type. 14218 if (E->getType().getQualifiers().hasUnaligned()) 14219 return; 14220 14221 // For a chain of MemberExpr like "a.b.c.d" this list 14222 // will keep FieldDecl's like [d, c, b]. 14223 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14224 const MemberExpr *TopME = nullptr; 14225 bool AnyIsPacked = false; 14226 do { 14227 QualType BaseType = ME->getBase()->getType(); 14228 if (ME->isArrow()) 14229 BaseType = BaseType->getPointeeType(); 14230 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl(); 14231 if (RD->isInvalidDecl()) 14232 return; 14233 14234 ValueDecl *MD = ME->getMemberDecl(); 14235 auto *FD = dyn_cast<FieldDecl>(MD); 14236 // We do not care about non-data members. 14237 if (!FD || FD->isInvalidDecl()) 14238 return; 14239 14240 AnyIsPacked = 14241 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14242 ReverseMemberChain.push_back(FD); 14243 14244 TopME = ME; 14245 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14246 } while (ME); 14247 assert(TopME && "We did not compute a topmost MemberExpr!"); 14248 14249 // Not the scope of this diagnostic. 14250 if (!AnyIsPacked) 14251 return; 14252 14253 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14254 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14255 // TODO: The innermost base of the member expression may be too complicated. 14256 // For now, just disregard these cases. This is left for future 14257 // improvement. 14258 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14259 return; 14260 14261 // Alignment expected by the whole expression. 14262 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14263 14264 // No need to do anything else with this case. 14265 if (ExpectedAlignment.isOne()) 14266 return; 14267 14268 // Synthesize offset of the whole access. 14269 CharUnits Offset; 14270 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14271 I++) { 14272 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14273 } 14274 14275 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14276 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14277 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14278 14279 // The base expression of the innermost MemberExpr may give 14280 // stronger guarantees than the class containing the member. 14281 if (DRE && !TopME->isArrow()) { 14282 const ValueDecl *VD = DRE->getDecl(); 14283 if (!VD->getType()->isReferenceType()) 14284 CompleteObjectAlignment = 14285 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14286 } 14287 14288 // Check if the synthesized offset fulfills the alignment. 14289 if (Offset % ExpectedAlignment != 0 || 14290 // It may fulfill the offset it but the effective alignment may still be 14291 // lower than the expected expression alignment. 14292 CompleteObjectAlignment < ExpectedAlignment) { 14293 // If this happens, we want to determine a sensible culprit of this. 14294 // Intuitively, watching the chain of member expressions from right to 14295 // left, we start with the required alignment (as required by the field 14296 // type) but some packed attribute in that chain has reduced the alignment. 14297 // It may happen that another packed structure increases it again. But if 14298 // we are here such increase has not been enough. So pointing the first 14299 // FieldDecl that either is packed or else its RecordDecl is, 14300 // seems reasonable. 14301 FieldDecl *FD = nullptr; 14302 CharUnits Alignment; 14303 for (FieldDecl *FDI : ReverseMemberChain) { 14304 if (FDI->hasAttr<PackedAttr>() || 14305 FDI->getParent()->hasAttr<PackedAttr>()) { 14306 FD = FDI; 14307 Alignment = std::min( 14308 Context.getTypeAlignInChars(FD->getType()), 14309 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14310 break; 14311 } 14312 } 14313 assert(FD && "We did not find a packed FieldDecl!"); 14314 Action(E, FD->getParent(), FD, Alignment); 14315 } 14316 } 14317 14318 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14319 using namespace std::placeholders; 14320 14321 RefersToMemberWithReducedAlignment( 14322 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14323 _2, _3, _4)); 14324 } 14325